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

// Ensure the user is a logged-in restaurant owner
if (!isset($_SESSION['restaurant_user_id'])) {
    header('Location: ../restaurant_login.php');
    exit;
}

$restaurant_id = $_SESSION['restaurant_id'];

// Fetch orders belonging to this restaurant
$stmt = $pdo->prepare("
    SELECT o.id, o.total_price, o.status, o.created_at, u.name as user_name
    FROM orders o
    JOIN users u ON o.user_id = u.id
    WHERE o.restaurant_id = ?
    ORDER BY o.created_at DESC
");
$stmt->execute([$restaurant_id]);
$orders = $stmt->fetchAll();

$possible_statuses = ['Pending', 'Confirmed', 'Preparing', 'Out for Delivery', 'Delivered', 'Cancelled'];
?>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2>Your Restaurant's Orders</h2>
        <span class="badge badge-success" id="update-indicator" style="display: none;">Updated just now</span>
    </div>

    <div id="orders-table-container">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Order ID</th>
                    <th>Customer</th>
                    <th>Total Price</th>
                    <th>Order Date</th>
                    <th>Status</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody id="orders-tbody">
                <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="6" class="text-center">No orders found.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                        <tr data-order-id="<?php echo $order['id']; ?>">
                            <td><?php echo $order['id']; ?></td>
                            <td><?php echo htmlspecialchars($order['user_name']); ?></td>
                            <td>$<?php echo number_format($order['total_price'], 2); ?></td>
                            <td><?php echo $order['created_at']; ?></td>
                            <td>
                                <select class="form-control form-control-sm status-select">
                                    <?php foreach ($possible_statuses as $status): ?>
                                        <option value="<?php echo $status; ?>" <?php echo ($order['status'] === $status) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($status); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td>
                                <a href="order_details.php?order_id=<?php echo $order['id']; ?>" class="btn btn-info btn-sm">View Details</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const ordersTbody = document.getElementById('orders-tbody');
    const updateIndicator = document.getElementById('update-indicator');

    // --- Function to update status via API ---
    async function updateOrderStatus(orderId, newStatus) {
        try {
            const response = await fetch('update_order_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ order_id: orderId, status: newStatus }),
            });
            const result = await response.json();
            if (!response.ok) {
                throw new Error(result.error || 'Failed to update status');
            }
            console.log('Status updated:', result.message);
            showUpdateIndicator();
        } catch (error) {
            console.error('Error updating status:', error);
            alert('Error: ' + error.message);
        }
    }

    // --- Attach event listener to dropdowns ---
    ordersTbody.addEventListener('change', function (e) {
        if (e.target.classList.contains('status-select')) {
            const selectedStatus = e.target.value;
            const orderId = e.target.closest('tr').dataset.orderId;
            updateOrderStatus(orderId, selectedStatus);
        }
    });

    // --- Function to show a brief update indicator ---
    function showUpdateIndicator() {
        updateIndicator.style.display = 'inline';
        setTimeout(() => {
            updateIndicator.style.display = 'none';
        }, 2000);
    }

    // --- Function to fetch and refresh the order list ---
    async function fetchOrders() {
        try {
            const response = await fetch(window.location.href, { // Fetch the same page
                headers: {
                    'X-Requested-With': 'XMLHttpRequest' // To identify AJAX request on server if needed
                }
            });
            const html = await response.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const newTbody = doc.getElementById('orders-tbody');
            if (newTbody && ordersTbody.innerHTML.trim() !== newTbody.innerHTML.trim()) {
                ordersTbody.innerHTML = newTbody.innerHTML;
                console.log('Orders refreshed');
                showUpdateIndicator();
            }
        } catch (error) {
            console.error('Error fetching orders:', error);
        }
    }

    // --- Polling: Refresh orders every 15 seconds ---
    setInterval(fetchOrders, 15000);
});
</script>

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