<?php
// File: competition_status.php
require_once 'session_init.php';
require_once 'db.php';
require_once 'phonepe_config.php';

$status_param = $_GET['status'] ?? '';
// Check URL first (GET), then fallback to session
$merchantTransactionId = $_GET['txn_id'] ?? null;

if (!$merchantTransactionId && $status_param !== 'free') {
    $merchantTransactionId = $_SESSION['comp_phonepe_txnid'] ?? null;
    unset($_SESSION['comp_phonepe_txnid']);
}

$page_title = "Registration Status";
$message = "Checking status...";
$is_success = false;

if ($status_param === 'free') {
    $page_title = "Registration Successful!";
    $message = "You have successfully registered for this free competition.";
    $is_success = true;

} elseif ($merchantTransactionId) {
    // Check PhonePe Status via API
    $api_endpoint = $PHONEPE_STATUS_ENDPOINT . $merchantTransactionId;
    $hash_string = $api_endpoint . $PHONEPE_SALT_KEY;
    $sha256_hash = hash('sha256', $hash_string);
    $x_verify_header = $sha256_hash . '###' . $PHONEPE_SALT_INDEX;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $PHONEPE_HOST_URL . $api_endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [ 
        'Content-Type: application/json', 
        'X-VERIFY: ' . $x_verify_header, 
        'X-MERCHANT-ID: ' . $PHONEPE_MERCHANT_ID 
    ]);
    $response = curl_exec($ch);
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_status == 200) {
        $json_response = json_decode($response, true);
        if (isset($json_response['success']) && $json_response['success'] === true) {
            if ($json_response['code'] === 'PAYMENT_SUCCESS') {
                $page_title = "Registration Successful!";
                $message = "Your payment was successful and your spot is confirmed. Email has been sent please check your Inbox/Spam folder to upload the files.";
                $is_success = true;
            } elseif ($json_response['code'] === 'PAYMENT_PENDING') {
                $page_title = "Payment Pending";
                $message = "Your payment is processing. We will notify you via email once it is confirmed.";
                $is_success = false;
                echo '<meta http-equiv="refresh" content="5">'; // Auto-refresh to check again
            } else {
                $page_title = "Payment Failed";
                $message = "Your payment was not successful. Please try registering again.";
                $is_success = false;
            }
        } else {
             $message = "Could not verify payment status. Please contact support.";
        }
    } else {
        $message = "We could not verify your payment at this time. Please contact support.";
    }
} else {
    // No ID and not free
    $message = "Invalid request. No transaction found.";
}

include 'header.php';
?>
<div class="bg-gray-50 py-12">
    <div class="max-w-lg mx-auto bg-white p-8 rounded-xl shadow-lg text-center">
        <h2 class="text-3xl font-extrabold <?php echo $is_success ? 'text-ucf-green' : 'text-red-600'; ?> mb-4">
            <?php echo $page_title; ?>
        </h2>
        <p class="text-gray-600 mb-6"><?php echo $message; ?></p>
        
        <?php if ($is_success): ?>
            <a href="competition.php" class="mt-6 inline-block bg-ucf-green text-white font-bold py-3 px-6 rounded-lg hover:bg-ucf-green-dark">Back to Competitions</a>
        <?php else: ?>
            <a href="competition.php" class="mt-6 inline-block bg-gray-600 text-white font-bold py-3 px-6 rounded-lg hover:bg-gray-700">Try Again</a>
        <?php endif; ?>
    </div>
</div>
<?php include 'footer.php'; ?>