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

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

if (!isset($_GET['id'])) {
    header("Location: profile.php");
    exit();
}

$order_id = $_GET['id'];
$user_id = $_SESSION['user_id'];

// Fetch order details
$p_order = $db->prepare("SELECT o.*, r.name as restaurant_name FROM orders o JOIN restaurants r ON o.restaurant_id = r.id WHERE o.id = ? AND o.user_id = ?");
$p_order->execute([$order_id, $user_id]);
$order = $p_order->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    echo "<div class='container mt-5'><p>Order not found or you do not have permission to view it.</p></div>";
    include 'footer.php';
    exit();
}

// Fetch order items
$p_items = $db->prepare("SELECT oi.*, mi.name as item_name FROM order_items oi JOIN menu_items mi ON oi.menu_item_id = mi.id WHERE oi.order_id = ?");
$p_items->execute([$order_id]);
$items = $p_items->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container mt-5">
    <h2>Order Details #<?php echo $order['id']; ?></h2>
    <hr>
    <div class="card mb-4">
        <div class="card-body">
            <h5 class="card-title">Summary</h5>
            <p><strong>Restaurant:</strong> <?php echo htmlspecialchars($order['restaurant_name']); ?></p>
            <p><strong>Order Date:</strong> <?php echo date("F j, Y, g:i a", strtotime($order['created_at'])); ?></p>
            <p><strong>Total:</strong> $<?php echo number_format($order['total_price'], 2); ?></p>
            <p><strong>Status:</strong> <?php echo htmlspecialchars($order['status']); ?></p>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <h5 class="card-title">Items</h5>
            <ul class="list-group list-group-flush">
                <?php foreach ($items as $item): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <?php echo htmlspecialchars($item['item_name']); ?> (x<?php echo $item['quantity']; ?>)
                        <span>$<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>
    <a href="profile.php" class="btn btn-primary mt-3">Back to My Orders</a>
</div>

<?php include 'footer.php'; ?>
