<?php
// File: order_status.php (NEW FILE - User-facing)

require_once 'session_init.php'; // Start session
require_once 'db.php';
require_once 'phonepe_config.php';

// --- 1. Get Order ID from the URL ---
$order_id = $_GET['order_id'] ?? null;
if (!$order_id || !is_numeric($order_id)) {
    // If no order ID, send them home.
    header("Location: index.php");
    exit();
}

$page_title = "Payment Pending";
$message = "We are checking your payment status. Please wait...";
$is_success = false;
$order = null;

// --- 2. Fetch the Order from *our* Database ---
$stmt = $conn->prepare("SELECT merchant_transaction_id, payment_status FROM orders WHERE id = ? AND user_id = ?");
$stmt->bind_param("ii", $order_id, $_SESSION['user_id']); // Security check
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    $order = $result->fetch_assoc();
}
$stmt->close();

if (!$order) {
    // Order not found or doesn't belong to this user
    $message = "Invalid order ID. Your payment status cannot be verified.";
} else {
    // --- 3. Check PhonePe's Payment Status API ---
    $merchantTransactionId = $order['merchant_transaction_id'];

    $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 = "Thank you! Your order (ID: #$order_id) has been received. A confirmation email is on its way.";
                $is_success = true;
                
                // Clear the cart now that payment is confirmed
                $_SESSION['cart'] = []; 

            } elseif ($payment_status === 'PAYMENT_PENDING') {
                 $page_title = "Payment Pending";
                 $message = "Your payment for order #$order_id is pending. We will update you by email once it is confirmed.";
                 $is_success = false; 
            } else {
                $page_title = "Payment Failed";
                $message = "Your payment for order #$order_id was not successful. (Status: " . htmlspecialchars($payment_status) . ")";
                $is_success = false;
            }
        } else {
            // This happens if the API call is valid but PhonePe has an error (e.g., hash mismatch)
            $message = "Payment status could not be verified. " . htmlspecialchars($json_response['message'] ?? 'Unknown API error.');
        }
    } else {
        // This happens if the cURL request itself fails
        $message = "We could not verify your payment at this time. Please contact support with order ID #$order_id.";
    }
}

// --- 4. 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): ?>
            <a href="index.php" class="mt-6 inline-block bg-ucf-green text-white font-bold py-3 px-6 rounded-lg">Continue Shopping</a>
        <?php else: ?>
             <a href="checkout.php" class="mt-6 inline-block bg-gray-600 text-white font-bold py-3 px-6 rounded-lg">Try Again</a>
        <?php endif; ?>
    </div>
</div>
<?php
include 'footer.php';
?>