<?php
$pageTitle = 'Kitchen Display';
require_once __DIR__ . '/includes/header.php';

$pendingOrders = $db->query("
    SELECT o.*, t.table_number
    FROM orders o
    LEFT JOIN tables t ON o.table_id = t.id
    WHERE o.restaurant_id = ? AND o.order_status IN ('confirmed', 'preparing')
    ORDER BY CASE o.order_status WHEN 'confirmed' THEN 1 WHEN 'preparing' THEN 2 END, o.created_at ASC
", [$restaurantId])->fetchAll();

foreach ($pendingOrders as &$po) {
    $po['items'] = $db->query("SELECT oi.*, GROUP_CONCAT(oia.addon_name SEPARATOR ', ') as addons_list FROM order_items oi LEFT JOIN order_item_addons oia ON oi.id = oia.order_item_id WHERE oi.order_id = ? GROUP BY oi.id", [$po['id']])->fetchAll();
}
unset($po);
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0"><i class="fas fa-fire me-2"></i>Kitchen Display</h6>
        <small class="text-muted">Active orders for kitchen preparation</small>
    </div>
    <button class="btn btn-outline-secondary btn-sm" onclick="location.reload()"><i class="fas fa-sync me-1"></i>Refresh</button>
</div>

<div class="row" id="kitchenOrders">
    <?php if (empty($pendingOrders)): ?>
        <div class="col-12">
            <div class="table-card">
                <div class="card-body text-center text-muted py-5">
                    <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                    <h5>All caught up!</h5>
                    <p>No pending orders in the kitchen.</p>
                </div>
            </div>
        </div>
    <?php else: ?>
        <?php foreach ($pendingOrders as $po): ?>
        <div class="col-xl-4 col-md-6 mb-3" id="order_<?php echo $po['id']; ?>">
            <div class="card border-<?php echo $po['order_status'] === 'preparing' ? 'warning' : 'primary'; ?>">
                <div class="card-header d-flex justify-content-between align-items-center bg-<?php echo $po['order_status'] === 'preparing' ? 'warning' : 'primary'; ?> text-white">
                    <div>
                        <strong><?php echo sanitize($po['order_number']); ?></strong>
                        <small class="ms-2"><?php echo $po['table_number'] ? 'Table ' . sanitize($po['table_number']) : ucfirst(str_replace('_', ' ', $po['order_type'])); ?></small>
                    </div>
                    <small><?php echo timeAgo($po['created_at']); ?></small>
                </div>
                <div class="card-body p-2">
                    <span class="badge order-status-<?php echo $po['order_status']; ?> mb-2"><?php echo ucfirst($po['order_status']); ?></span>
                    <?php if ($po['order_notes']): ?>
                        <div class="alert alert-info py-1 px-2 small mb-2"><i class="fas fa-sticky-note me-1"></i><?php echo sanitize($po['order_notes']); ?></div>
                    <?php endif; ?>
                    <table class="table table-sm mb-0">
                        <thead><tr><th>Item</th><th class="text-center">Qty</th></tr></thead>
                        <tbody>
                            <?php foreach ($po['items'] as $item): ?>
                            <tr>
                                <td>
                                    <strong><?php echo sanitize($item['item_name']); ?></strong>
                                    <?php echo $item['variation_name'] ? '<br><small class="text-muted">' . sanitize($item['variation_name']) . '</small>' : ''; ?>
                                    <?php echo $item['addons_list'] ? '<br><small class="text-info">' . sanitize($item['addons_list']) . '</small>' : ''; ?>
                                    <?php echo $item['item_notes'] ? '<br><small class="text-warning"><i class="fas fa-sticky-note"></i> ' . sanitize($item['item_notes']) . '</small>' : ''; ?>
                                </td>
                                <td class="text-center fw-bold"><?php echo $item['quantity']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="card-footer p-2">
                    <?php if ($po['order_status'] === 'confirmed'): ?>
                        <button class="btn btn-warning btn-sm w-100 kitchen-action" data-id="<?php echo $po['id']; ?>" data-action="preparing">
                            <i class="fas fa-fire me-1"></i>Start Preparing
                        </button>
                    <?php elseif ($po['order_status'] === 'preparing'): ?>
                        <button class="btn btn-success btn-sm w-100 kitchen-action" data-id="<?php echo $po['id']; ?>" data-action="ready">
                            <i class="fas fa-bell me-1"></i>Mark Ready
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<script>
document.querySelectorAll('.kitchen-action').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var orderId = this.dataset.id;
        var action = this.dataset.action;
        ajaxPost(BASE_URL + '/restaurant-admin/order_action.php', 'order_id=' + orderId + '&order_status=' + action + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (data.success) { showAlert('success', data.message); setTimeout(function(){location.reload();},500); }
            else showAlert('danger', data.message);
        });
    });
});

setInterval(function(){ location.reload(); }, 30000);
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
