<?php
// FILE: api/admin/confirm_payment.php
// --- SETUP ---
ini_set('display_errors', 1);
error_reporting(E_ALL);
header("Content-Type: application/json; charset=UTF-8");

require_once '../config/cors.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];
$token = $_GET['token'] ?? null;

// --- ROUTING ---
try {
    if (empty($token)) {
        $input = json_decode(file_get_contents('php://input'), true);
        $token = $input['token'] ?? null;
    }
    if (empty($token)) {
        throw new Exception("Payment confirmation token is required.", 400);
    }

    if ($method === 'GET') {
        handleGetRequest($db, $token);
    } elseif ($method === 'POST') {
        handlePostRequest($db, $token);
    } else {
        throw new Exception("Method not allowed.", 405);
    }
} catch (Exception $e) {
    $statusCode = $e->getCode() >= 400 ? $e->getCode() : 500;
    http_response_code($statusCode);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

// --- FUNCTIONS ---
function handleGetRequest($db, $token) {
    $stmt = $db->prepare("SELECT id, status, payment_status, total_price, payment_method FROM orders WHERE payment_confirmation_token = ?");
    $stmt->bind_param('s', $token);
    $stmt->execute();
    $result = $stmt->get_result();
    $order = $result->fetch_assoc();
    $stmt->close();

    if (!$order) {
        throw new Exception("Invalid payment confirmation link or token.", 404);
    }
    echo json_encode(['success' => true, 'data' => $order]);
}

function handlePostRequest($db, $token) {
    $stmt = $db->prepare("UPDATE orders SET payment_status = 'paid', updated_at = CURRENT_TIMESTAMP WHERE payment_confirmation_token = ? AND payment_status = 'pending'");
    $stmt->bind_param('s', $token);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        echo json_encode(['success' => true, 'message' => "Payment confirmed successfully!"]);
    } else {
        // Check if it's already paid
        $checkStmt = $db->prepare("SELECT id FROM orders WHERE payment_confirmation_token = ? AND payment_status = 'paid'");
        $checkStmt->bind_param('s', $token);
        $checkStmt->execute();
        $result = $checkStmt->get_result();
        if ($result->num_rows > 0) {
            echo json_encode(['success' => true, 'message' => 'Payment has already been confirmed.']);
        } else {
            throw new Exception("Order not found or no update was needed.", 404);
        }
        $checkStmt->close();
    }
    $stmt->close();
}
?>