<?php
// File: payment_status.php (User-facing - Final Fix)

require_once 'session_init.php'; // Start session to check for fallback
require_once 'db.php';
require_once 'phonepe_config.php';

// --- 1. ⭐️ FIX: Check URL, then fall back to SESSION ---
$merchantTransactionId = $_GET['txn_id'] ?? null;

if (!$merchantTransactionId) {
    // If GET is empty, check the session
    $merchantTransactionId = $_SESSION['phonepe_txnid'] ?? null;
}
unset($_SESSION['phonepe_txnid']); // Clear it after use, no matter what
// --- END OF FIX ---

if (!$merchantTransactionId) {
    // This happens if the user just visits the page directly
    header("Location: register.php?error=invalid_payment_response");
    exit();
}

$page_title = "Payment Pending";
$message = "We are checking your payment status. Please wait...";
$is_success = false;

// --- 2. Check PhonePe's Payment Status 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) {
        $payment_status = $json_response['code'];
        
        if ($payment_status === 'PAYMENT_SUCCESS') {
            $page_title = "Payment Successful!";
            $message = "Your payment was successful. Your account is being created. You will receive a welcome email shortly.";
            $is_success = true;
        } elseif ($payment_status === 'PAYMENT_PENDING') {
             $page_title = "Payment Pending";
             $message = "Your payment is pending. We will update you by email once it is confirmed.";
             $is_success = false; 
        } else {
            $page_title = "Payment Failed";
            $message = "Your payment was not successful. (Status: " . htmlspecialchars($payment_status) . ")";
            $is_success = false;
        }
    } else {
        $message = "Payment status could not be verified. " . htmlspecialchars($json_response['message'] ?? '');
    }
} else {
    $message = "We could not verify your payment at this time. Please contact support.";
}

// --- 3. DISPLAY THE FINAL RESULT TO THE USER ---
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): ?>
            <p>You can now log in to your account. If you don't receive an email within 5 minutes, please check your spam folder.</p>
            <a href="login.php" class="mt-6 inline-block bg-ucf-green text-white font-bold py-3 px-6 rounded-lg">Go to Login</a>
        <?php else: ?>
             <a href="register.php" class="mt-6 inline-block bg-gray-600 text-white font-bold py-3 px-6 rounded-lg">Try Registration Again</a>
        <?php endif; ?>
    </div>
</div>
<?php
include 'footer.php';
?>