<div class="row">
    <div class="col-sm-12">
        <div class="page-title-box d-flex align-items-center justify-content-between">
            <h2 class="page-title">Online Order Management</h2>
            <div>
                <span class="badge badge-pill badge-soft-warning font-size-13" id="pending-count">Loading...</span>
                <button class="btn btn-sm btn-outline-secondary ml-2" onclick="loadOrders()">
                    <i class="fe-refresh-cw"></i> Refresh
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Status filter tabs -->
<div class="row mb-3">
    <div class="col-12">
        <ul class="nav nav-tabs" id="statusTabs">
            <li class="nav-item"><a class="nav-link active" href="#" data-status="all">All</a></li>
            <li class="nav-item"><a class="nav-link" href="#" data-status="0">Pending</a></li>
            <li class="nav-item"><a class="nav-link" href="#" data-status="1">Accepted</a></li>
            <li class="nav-item"><a class="nav-link" href="#" data-status="2">Food Ready</a></li>
            <li class="nav-item"><a class="nav-link" href="#" data-status="3">Dispatched</a></li>
            <li class="nav-item"><a class="nav-link" href="#" data-status="4">Completed</a></li>
            <li class="nav-item"><a class="nav-link" href="#" data-status="5">Cancelled</a></li>
        </ul>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <div id="orders-container">
            <?php if (empty($orders)): ?>
                <div class="alert alert-info">No online orders in the last 24 hours.</div>
            <?php else: ?>
                <?php foreach ($orders as $order): ?>
                <div class="card order-card mb-2" data-status="<?php echo $order['status']; ?>" data-ref="<?php echo h($order['reference_id']); ?>">
                    <div class="card-body p-3">
                        <div class="row align-items-center">
                            <!-- Platform + Order ID -->
                            <div class="col-md-2">
                                <div class="font-weight-bold text-uppercase text-muted small"><?php echo h($order['platform'] ?: 'Online'); ?></div>
                                <div class="font-size-13"><?php echo h($order['order_id']); ?></div>
                                <div class="text-muted small"><?php echo date('d M H:i', strtotime($order['created'])); ?></div>
                            </div>
                            <!-- Customer -->
                            <div class="col-md-2">
                                <div class="font-weight-bold"><?php echo h($order['cust_name'] ?: 'Guest'); ?></div>
                                <div class="text-muted small"><?php echo h($order['cust_phone']); ?></div>
                            </div>
                            <!-- Items -->
                            <div class="col-md-4">
                                <?php foreach ($order['items'] as $it): ?>
                                    <span class="badge badge-light mr-1">
                                        <?php echo h($it['name']); ?> x<?php echo $it['qty']; ?>
                                    </span>
                                <?php endforeach; ?>
                                <?php if (empty($order['items'])): ?>
                                    <span class="text-muted small">No item details</span>
                                <?php endif; ?>
                            </div>
                            <!-- Amount + Status -->
                            <div class="col-md-2 text-right">
                                <div class="font-weight-bold">&#8377;<?php echo number_format($order['total_amount'], 2); ?></div>
                                <?php
                                $badgeClass = array(
                                    0 => 'warning',
                                    1 => 'info',
                                    2 => 'success',
                                    3 => 'primary',
                                    4 => 'secondary',
                                    5 => 'danger',
                                );
                                $cls = isset($badgeClass[$order['status']]) ? $badgeClass[$order['status']] : 'light';
                                ?>
                                <span class="badge badge-<?php echo $cls; ?>"><?php echo h($order['status_label']); ?></span>
                            </div>
                            <!-- Action buttons -->
                            <div class="col-md-2 text-right">
                                <?php if ($order['status'] == 0): ?>
                                    <button class="btn btn-success btn-sm mr-1"
                                        onclick="acceptOrder('<?php echo h($order['reference_id']); ?>', this)">
                                        Accept
                                    </button>
                                    <button class="btn btn-danger btn-sm"
                                        onclick="rejectOrder('<?php echo h($order['reference_id']); ?>', this)">
                                        Reject
                                    </button>
                                <?php elseif ($order['status'] == 1): ?>
                                    <button class="btn btn-primary btn-sm"
                                        onclick="foodReadyOrder('<?php echo h($order['reference_id']); ?>', this)">
                                        Food Ready
                                    </button>
                                <?php elseif ($order['status'] == 2): ?>
                                    <span class="text-success small">Ready &#10003;</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
var CASHIER_ID = "<?php echo isset($_SESSION['Auth']['User']['id']) ? $_SESSION['Auth']['User']['id'] : '1'; ?>";
var currentFilter = 'all';
var autoRefreshInterval = null;

// Status tab filter
document.querySelectorAll('#statusTabs .nav-link').forEach(function(tab) {
    tab.addEventListener('click', function(e) {
        e.preventDefault();
        document.querySelectorAll('#statusTabs .nav-link').forEach(function(t) { t.classList.remove('active'); });
        this.classList.add('active');
        currentFilter = this.dataset.status;
        applyFilter();
    });
});

function applyFilter() {
    document.querySelectorAll('.order-card').forEach(function(card) {
        if (currentFilter === 'all' || card.dataset.status === currentFilter) {
            card.style.display = '';
        } else {
            card.style.display = 'none';
        }
    });
    updatePendingCount();
}

function updatePendingCount() {
    var pending = document.querySelectorAll('.order-card[data-status="0"]').length;
    document.getElementById('pending-count').textContent = pending + ' pending';
}

function acceptOrder(refId, btn) {
    btn.disabled = true;
    btn.textContent = '...';
    fetch('/erp/Apis/online_order_accept?id=' + CASHIER_ID + '&reference_id=' + encodeURIComponent(refId))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.status) {
                var card = document.querySelector('.order-card[data-ref="' + refId + '"]');
                if (card) {
                    card.dataset.status = '1';
                    card.querySelector('.badge').textContent = 'Accepted';
                    card.querySelector('.badge').className = 'badge badge-info';
                    // Replace action buttons
                    var actionDiv = card.querySelector('.col-md-2.text-right');
                    actionDiv.innerHTML = '<button class="btn btn-primary btn-sm" onclick="foodReadyOrder(\'' + refId + '\', this)">Food Ready</button>';
                }
                applyFilter();
            } else {
                btn.disabled = false;
                btn.textContent = 'Accept';
                alert('Error: ' + (data.message || 'Unknown'));
            }
        })
        .catch(function() {
            btn.disabled = false;
            btn.textContent = 'Accept';
            alert('Network error');
        });
}

function rejectOrder(refId, btn) {
    if (!confirm('Cancel this order?')) return;
    btn.disabled = true;
    btn.textContent = '...';
    fetch('/erp/Apis/online_order_cancelled?id=' + CASHIER_ID + '&reference_id=' + encodeURIComponent(refId) + '&status_code=store_busy')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var card = document.querySelector('.order-card[data-ref="' + refId + '"]');
            if (card) {
                card.dataset.status = '5';
                card.querySelector('.badge').textContent = 'Cancelled';
                card.querySelector('.badge').className = 'badge badge-danger';
                var actionDiv = card.querySelector('.col-md-2.text-right');
                actionDiv.innerHTML = '';
            }
            applyFilter();
        })
        .catch(function() {
            btn.disabled = false;
            btn.textContent = 'Reject';
            alert('Network error');
        });
}

function foodReadyOrder(refId, btn) {
    btn.disabled = true;
    btn.textContent = '...';
    fetch('/erp/Apis/online_order_food_ready?id=' + CASHIER_ID + '&reference_id=' + encodeURIComponent(refId))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var card = document.querySelector('.order-card[data-ref="' + refId + '"]');
            if (card) {
                card.dataset.status = '2';
                card.querySelector('.badge').textContent = 'Food Ready';
                card.querySelector('.badge').className = 'badge badge-success';
                var actionDiv = card.querySelector('.col-md-2.text-right');
                actionDiv.innerHTML = '<span class="text-success small">Ready &#10003;</span>';
            }
            applyFilter();
        })
        .catch(function() {
            btn.disabled = false;
            btn.textContent = 'Food Ready';
            alert('Network error');
        });
}

function loadOrders() {
    window.location.reload();
}

// Auto-refresh every 20 seconds
autoRefreshInterval = setInterval(function() {
    // Only auto-reload if there are pending orders
    var pending = document.querySelectorAll('.order-card[data-status="0"]').length;
    if (pending > 0) {
        loadOrders();
    }
}, 20000);

// Initial filter apply
updatePendingCount();
</script>
