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

$filterStatus = $_GET['status'] ?? '';
$filterType = $_GET['type'] ?? '';
$filterDateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-7 days'));
$filterDateTo = $_GET['date_to'] ?? date('Y-m-d');

$where = "o.restaurant_id = ?";
$params = [$restaurantId];

if ($filterStatus) {
    $where .= " AND o.order_status = ?";
    $params[] = $filterStatus;
}
if ($filterType) {
    $where .= " AND o.order_type = ?";
    $params[] = $filterType;
}
if ($filterDateFrom) {
    $where .= " AND DATE(o.created_at) >= ?";
    $params[] = $filterDateFrom;
}
if ($filterDateTo) {
    $where .= " AND DATE(o.created_at) <= ?";
    $params[] = $filterDateTo;
}

$orders = $db->query("
    SELECT o.*, t.table_number, c.name as customer_name_full
    FROM orders o
    LEFT JOIN tables t ON o.table_id = t.id
    LEFT JOIN customers c ON o.customer_id = c.id
    WHERE {$where}
    ORDER BY o.created_at DESC
    LIMIT 500
", $params)->fetchAll();

$settings = $restaurantSettings;
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Orders</h6>
        <small class="text-muted">Manage incoming and past orders</small>
    </div>
    <div>
        <button class="btn btn-outline-secondary btn-sm" onclick="location.reload()"><i class="fas fa-sync me-1"></i>Refresh</button>
    </div>
</div>

<div class="table-card mb-3">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-2">
                <label class="form-label small">Status</label>
                <select class="form-select form-select-sm" name="status">
                    <option value="">All</option>
                    <?php foreach (['new'=>'New','confirmed'=>'Confirmed','preparing'=>'Preparing','ready'=>'Ready','served'=>'Served','completed'=>'Completed','cancelled'=>'Cancelled','rejected'=>'Rejected'] as $val => $lbl): ?>
                    <option value="<?php echo $val; ?>" <?php echo $filterStatus === $val ? 'selected' : ''; ?>><?php echo $lbl; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small">Type</label>
                <select class="form-select form-select-sm" name="type">
                    <option value="">All</option>
                    <option value="dine_in" <?php echo $filterType === 'dine_in' ? 'selected' : ''; ?>>Dine In</option>
                    <option value="takeaway" <?php echo $filterType === 'takeaway' ? 'selected' : ''; ?>>Takeaway</option>
                    <option value="delivery" <?php echo $filterType === 'delivery' ? 'selected' : ''; ?>>Delivery</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small">From</label>
                <input type="date" class="form-control form-control-sm" name="date_from" value="<?php echo sanitize($filterDateFrom); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label small">To</label>
                <input type="date" class="form-control form-control-sm" name="date_to" value="<?php echo sanitize($filterDateTo); ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-filter me-1"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Order #</th>
                        <th>Table</th>
                        <th>Type</th>
                        <th>Customer</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Payment</th>
                        <th>Time</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $ord): ?>
                        <tr>
                            <td><a href="<?php echo $baseUrl; ?>/restaurant-admin/order_detail.php?id=<?php echo $ord['id']; ?>" class="fw-bold text-decoration-none"><?php echo sanitize($ord['order_number']); ?></a></td>
                            <td><?php echo sanitize($ord['table_number'] ?? 'N/A'); ?></td>
                            <td><span class="badge bg-secondary"><?php echo ucfirst(str_replace('_', ' ', $ord['order_type'])); ?></span></td>
                            <td><?php echo sanitize($ord['customer_name'] ?? $ord['customer_name_full'] ?? 'Walk-in'); ?></td>
                            <td><strong><?php echo formatCurrency($ord['grand_total'], $currency); ?></strong></td>
                            <td><span class="badge order-status-<?php echo $ord['order_status']; ?>"><?php echo ucfirst($ord['order_status']); ?></span></td>
                            <td><span class="badge bg-<?php echo $ord['payment_status'] === 'paid' ? 'success' : ($ord['payment_status'] === 'failed' ? 'danger' : 'warning'); ?>"><?php echo ucfirst($ord['payment_status']); ?></span></td>
                            <td><small><?php echo timeAgo($ord['created_at']); ?></small></td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="<?php echo $baseUrl; ?>/restaurant-admin/order_detail.php?id=<?php echo $ord['id']; ?>" class="btn btn-outline-primary" title="View"><i class="fas fa-eye"></i></a>
                                    <?php if ($ord['order_status'] === 'new'): ?>
                                        <button class="btn btn-outline-success order-action-btn" data-id="<?php echo $ord['id']; ?>" data-action="confirmed" title="Accept"><i class="fas fa-check"></i></button>
                                        <button class="btn btn-outline-danger order-action-btn" data-id="<?php echo $ord['id']; ?>" data-action="rejected" title="Reject"><i class="fas fa-times"></i></button>
                                    <?php elseif ($ord['order_status'] === 'confirmed'): ?>
                                        <button class="btn btn-outline-warning order-action-btn" data-id="<?php echo $ord['id']; ?>" data-action="preparing" title="Preparing"><i class="fas fa-fire"></i></button>
                                    <?php elseif ($ord['order_status'] === 'preparing'): ?>
                                        <button class="btn btn-outline-success order-action-btn" data-id="<?php echo $ord['id']; ?>" data-action="ready" title="Ready"><i class="fas fa-bell"></i></button>
                                    <?php elseif ($ord['order_status'] === 'ready'): ?>
                                        <button class="btn btn-outline-info order-action-btn" data-id="<?php echo $ord['id']; ?>" data-action="served" title="Served"><i class="fas fa-concierge-bell"></i></button>
                                    <?php elseif ($ord['order_status'] === 'served'): ?>
                                        <button class="btn btn-outline-success order-action-btn" data-id="<?php echo $ord['id']; ?>" data-action="completed" title="Complete"><i class="fas fa-check-double"></i></button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reject / Cancel Order</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="rejectOrderId">
                <input type="hidden" id="rejectOrderAction">
                <div class="mb-3">
                    <label class="form-label">Reason <span class="text-danger">*</span></label>
                    <textarea class="form-control" id="rejectReason" rows="3" placeholder="Enter reason..." required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmRejectBtn">Confirm</button>
            </div>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.order-action-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var orderId = this.dataset.id;
        var action = this.dataset.action;
        if (action === 'rejected') {
            document.getElementById('rejectOrderId').value = orderId;
            document.getElementById('rejectOrderAction').value = 'rejected';
            document.getElementById('rejectReason').value = '';
            new bootstrap.Modal(document.getElementById('rejectModal')).show();
        } else if (action === 'cancelled') {
            document.getElementById('rejectOrderId').value = orderId;
            document.getElementById('rejectOrderAction').value = 'cancelled';
            document.getElementById('rejectReason').value = '';
            new bootstrap.Modal(document.getElementById('rejectModal')).show();
        } else {
            if (confirm('Change order status to "' + 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();},1000); }
                    else showAlert('danger', data.message);
                });
            }
        }
    });
});

document.getElementById('confirmRejectBtn').addEventListener('click', function() {
    var orderId = document.getElementById('rejectOrderId').value;
    var action = document.getElementById('rejectOrderAction').value;
    var reason = document.getElementById('rejectReason').value.trim();
    if (!reason) { showAlert('danger', 'Please enter a reason'); return; }
    ajaxPost(BASE_URL + '/restaurant-admin/order_action.php', 'order_id=' + orderId + '&order_status=' + action + '&reason=' + encodeURIComponent(reason) + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
        if (data.success) { showAlert('success', data.message); setTimeout(function(){location.reload();},1000); }
        else showAlert('danger', data.message);
    });
});
</script>

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