<?php
// confirmation.php - Display payment processing and poll for order status
ob_start();
session_start();
error_log("Entering confirmation.php: Session ID = " . session_id());

include_once 'config.php';
include_once 'auth.php';

// Fallback for display_flash_message
if (!function_exists('display_flash_message')) {
    error_log("display_flash_message() not defined, using fallback");
    function display_flash_message() {
        if (isset($_SESSION['flash_message'])) {
            $type = $_SESSION['flash_message']['type'] === 'success' ? 'success' : 'danger';
            $message = htmlspecialchars($_SESSION['flash_message']['message']);
            echo "<div class='alert alert-$type alert-dismissible fade show' role='alert'>
                    $message
                    <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                  </div>";
            unset($_SESSION['flash_message']);
        }
    }
}

if (!is_logged_in()) {
    error_log("User not logged in, redirecting to login.php");
    set_flash_message('error', 'Please log in to view this page.');
    header("Location: login.php?redirect=confirmation");
    ob_end_flush();
    exit();
}

if (!isset($_GET['order_id'])) {
    error_log("No order_id provided, redirecting to cart.php");
    set_flash_message('error', 'Invalid order ID.');
    header("Location: cart.php");
    ob_end_flush();
    exit();
}

$order_id = intval($_GET['order_id']);
try {
    $stmt = $conn->prepare("SELECT status, total, delivery_date, delivery_location FROM orders WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $order_id, $_SESSION['user_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $order = $result->fetch_assoc();
    if (!$order) {
        throw new Exception("Order not found or access denied for order ID: $order_id");
    }
    error_log("Confirmation page: Displaying for Order #$order_id, Status = " . $order['status']);
} catch (Exception $e) {
    error_log("Error fetching order: " . $e->getMessage());
    set_flash_message('error', 'Error loading order details: ' . htmlspecialchars($e->getMessage()));
    header("Location: cart.php");
    ob_end_flush();
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Confirmation - Doyle Enterprise</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <?php include_once 'header.php'; ?>
    <div class="container mt-4">
        <h2 class="text-center mb-4">Payment Confirmation</h2>
        <?php display_flash_message(); ?>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body text-center">
                        <h5 class="card-title">Processing Payment</h5>
                        <p class="card-text">Processing payment for Order #<?php echo $order_id; ?>. Please wait...</p>
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3">Please complete the payment in the M-Pesa prompt on your phone.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Starting payment status polling for Order #<?php echo $order_id; ?>');
            const maxAttempts = 30; // 5 minutes (30 * 10 seconds)
            let attempts = 0;

            function checkPaymentStatus() {
                fetch('check_payment_status.php?order_id=<?php echo $order_id; ?>')
                    .then(response => response.json())
                    .then(data => {
                        console.log('Response:', data);
                        if (data.status === 'completed') {
                            console.log('Payment confirmed, redirecting...');
                            window.location.href = 'checkout.php?order_id=<?php echo $order_id; ?>&check_payment=1';
                        } else if (data.status === 'failed') {
                            console.log('Payment failed, redirecting to cart...');
                            window.location.href = 'cart.php';
                        } else if (attempts < maxAttempts) {
                            attempts++;
                            console.log('Attempt ' + attempts + ' of ' + maxAttempts + ': Status = ' + data.status);
                            setTimeout(checkPaymentStatus, 10000); // Poll every 10 seconds
                        } else {
                            console.error('Max polling attempts reached, redirecting to cart');
                            window.location.href = 'cart.php';
                        }
                    })
                    .catch(error => {
                        console.error('Polling error:', error);
                        if (attempts < maxAttempts) {
                            attempts++;
                            console.log('Retrying, attempt ' + attempts + ' of ' + maxAttempts);
                            setTimeout(checkPaymentStatus, 10000);
                        } else {
                            console.error('Max polling attempts reached, redirecting to cart');
                            window.location.href = 'cart.php';
                        }
                    });
            }

            checkPaymentStatus();
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <?php include_once 'footer.php'; ?>
</body>
</html>
<?php ob_end_flush(); ?>