<?php
require_once __DIR__ . '/../../config/db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$referenceCode = $input['reference_code'] ?? null;
$fingerprint = $input['fingerprint'] ?? null;

if (!$referenceCode || !$fingerprint) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing reference_code or fingerprint']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT status FROM cliq_payments WHERE reference_code = :ref AND fingerprint = :fingerprint LIMIT 1");
    $stmt->execute([':ref' => $referenceCode, ':fingerprint' => $fingerprint]);
    $payment = $stmt->fetch();

    if ($payment) {
        // If it's still pending but older than 15 minutes, mark it as expired
        if ($payment['status'] === 'pending') {
            $stmtDate = $pdo->prepare("UPDATE cliq_payments SET status = 'expired' WHERE reference_code = :ref AND created_at < NOW() - INTERVAL 15 MINUTE");
            $stmtDate->execute([':ref' => $referenceCode]);
            
            // Re-fetch if we just expired it
            if ($stmtDate->rowCount() > 0) {
                $payment['status'] = 'expired';
            }
        }

        echo json_encode([
            'success' => true,
            'status' => $payment['status'] // 'pending', 'paid', or 'expired'
        ]);
    } else {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Payment not found']);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
