<?php
session_start();
require_once 'db/config.php';

$order_id = $_SESSION['order_id'] ?? $_GET['order_id'] ?? null;
$user_id = $_SESSION['user_id'] ?? null;
$guest_token = $_SESSION['token'] ?? $_GET['token'] ?? null;

if (!$order_id) {
    header("Location: index.php");
    exit();
}

$pdo = db();
$order = null;

if ($user_id) {
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ?");
    $stmt->execute([$order_id, $user_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
} elseif ($guest_token) {
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND token = ?");
    $stmt->execute([$order_id, $guest_token]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$order) {
    // If the order is not found or doesn't belong to the user/guest, redirect.
    header("Location: index.php");
    exit();
}

// Fetch order items
$itemsStmt = $pdo->prepare("
    SELECT oi.quantity, mi.name, mi.price
    FROM order_items oi
    JOIN menu_items mi ON oi.menu_item_id = mi.id
    WHERE oi.order_id = :order_id
");
$itemsStmt->bindParam(':order_id', $order_id);
$itemsStmt->execute();
$orderItems = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);

// Determine the correct tracking URL
$tracking_url = "order_status.php?order_id=" . $order_id;
if (!$user_id && $guest_token) {
    $tracking_url .= "&token=" . $guest_token;
}

include 'header.php';
?>

<div class="container mt-5 mb-5">
    <div class="row d-flex justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white text-center">
                    <h2 class="mb-0">Thank You for Your Order!</h2>
                </div>
                <div class="card-body">
                    <div class="text-center mb-4">
                        <p class="lead">Your order has been placed successfully.</p>
                        <p>Your Order ID is: <strong><?php echo htmlspecialchars($order['id']); ?></strong></p>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <h5>Delivery Details</h5>
                            <p>
                                <strong>Name:</strong> <?php echo htmlspecialchars($order['guest_name'] ?? 'N/A'); ?><br>
                                <strong>Address:</strong> <?php echo htmlspecialchars($order['delivery_address']); ?><br>
                                <strong>Phone:</strong> <?php echo htmlspecialchars($order['phone_number']); ?>
                            </p>
                        </div>
                        <div class="col-md-6 text-md-end">
                            <h5>Order Summary</h5>
                            <p>
                                <strong>Date:</strong> <?php echo date("F j, Y, g:i a", strtotime($order['created_at'])); ?><br>
                                <strong>Status:</strong> <span class="badge bg-warning text-dark"><?php echo htmlspecialchars(ucfirst($order['status'])); ?></span>
                            </p>
                        </div>
                    </div>

                    <h5 class="mt-4">Items Ordered</h5>
                    <ul class="list-group mb-3">
                        <?php foreach ($orderItems as $item): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <?php echo htmlspecialchars($item['name']); ?> (x<?php echo $item['quantity']; ?>)
                                <span>$<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>

                    <ul class="list-group mb-4">
                        <li class="list-group-item d-flex justify-content-between">
                            <span>Subtotal</span>
                            <span>$<?php echo number_format($order['total_price'] - ($order['discount_amount'] ?? 0), 2); ?></span>
                        </li>
                        <?php if (isset($order['discount_amount']) && $order['discount_amount'] > 0): ?>
                        <li class="list-group-item d-flex justify-content-between">
                            <span>Discount</span>
                            <span class="text-success">-$<?php echo number_format($order['discount_amount'], 2); ?></span>
                        </li>
                        <?php endif; ?>
                        <li class="list-group-item d-flex justify-content-between fw-bold">
                            <span>Total</span>
                            <span>$<?php echo number_format($order['total_price'], 2); ?></span>
                        </li>
                    </ul>

                    <div class="text-center order-confirmation-actions">
                        <p>We've received your order and will begin processing it shortly. You can track the progress of your order using the button below.</p>
                        <a href="index.php" class="btn btn-secondary">Continue Shopping</a>
                        <a href="<?php echo $tracking_url; ?>" class="btn btn-primary">Track Order</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php 
include 'footer.php'; 
// Clear session variables for the next order
unset($_SESSION['order_id']);
if(isset($_SESSION['token'])){
    unset($_SESSION['token']);
}
?>
