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

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

if (!isset($_GET['order_id'])) {
    echo "<div class='container mt-5'><p>No order specified.</p></div>";
    include 'footer.php';
    exit();
}

$order_id = $_GET['order_id'];
$user_id = $_SESSION['user_id'];
$pdo = db();

// Fetch order details to ensure the user owns this order
$p_order = $pdo->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 = $pdo->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 Status for #<?php echo $order['id']; ?></h2>
    <hr>
    <div class="card mb-4">
        <div class="card-body">
            <h5 class="card-title">Live Status</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>
            <div id="order-status-container">
                <p><strong>Status:</strong> <span class="badge bg-primary fs-6" id="order-status"><?php echo htmlspecialchars(ucwords($order['status'])); ?></span></p>
            </div>
             <div class="progress" style="height: 25px;">
                <div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <h5 class="card-title">Order Summary</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; ?>
                 <li class="list-group-item d-flex justify-content-between align-items-center">
                    <strong>Total</strong>
                    <strong>$<?php echo number_format($order['total_price'], 2); ?></strong>
                </li>
            </ul>
        </div>
    </div>
    <a href="order_history.php" class="btn btn-secondary mt-3">Back to Order History</a>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const orderId = <?php echo $order_id; ?>;
    const statusElement = document.getElementById('order-status');
    const progressBar = document.getElementById('progress-bar');
    
    const statusToProgress = {
        'Pending': 10,
        'Preparing': 40,
        'Out For Delivery': 75,
        'Delivered': 100,
        'Cancelled': 0 
    };

    function updateProgress(status) {
        const progress = statusToProgress[status] || 0;
        progressBar.style.width = progress + '%';
        progressBar.textContent = status;
        
        if (status === 'Delivered') {
            progressBar.classList.remove('progress-bar-animated', 'bg-primary');
            progressBar.classList.add('bg-success');
        } else if (status === 'Cancelled') {
            progressBar.classList.remove('progress-bar-animated', 'bg-primary');
            progressBar.classList.add('bg-danger');
        } else {
            progressBar.classList.remove('bg-success', 'bg-danger');
            progressBar.classList.add('bg-primary', 'progress-bar-animated');
        }
    }

    function fetchStatus() {
        fetch(`api/get_order_status.php?order_id=${orderId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status && data.status !== statusElement.textContent) {
                    statusElement.textContent = data.status;
                    updateProgress(data.status);
                }
            })
            .catch(error => console.error('Error fetching status:', error));
    }
    
    updateProgress(statusElement.textContent);
    setInterval(fetchStatus, 10000); // Poll every 10 seconds
});
</script>

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