<?php
require_once __DIR__ . '/includes/header.php';

$menuItems = [];
$categories = [];
if ($restaurantId) {
    $catStmt = $db->query(
        "SELECT id, name FROM categories WHERE restaurant_id = ? AND status = 1 ORDER BY sort_order, name",
        [$restaurantId]
    );
    $categories = $catStmt->fetchAll();

    $menuStmt = $db->query(
        "SELECT mi.id, mi.name, mi.regular_price, mi.offer_price, mi.is_available, c.name AS category_name, c.id AS category_id
         FROM menu_items mi
         INNER JOIN categories c ON mi.category_id = c.id
         WHERE mi.restaurant_id = ? AND mi.is_available = 1 AND c.status = 1
         ORDER BY c.sort_order, mi.sort_order, mi.name",
        [$restaurantId]
    );
    $menuItems = $menuStmt->fetchAll();
}
?>

<!-- Dashboard View -->
<div id="view-dashboard" class="view-section" style="<?php echo $currentPage === 'dashboard' ? '' : 'display:none;'; ?>">
    <div class="page-header">
        <h4 class="mb-0">Table Overview</h4>
        <div class="page-actions">
            <button class="btn btn-sm btn-outline" onclick="loadTables()">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
        </div>
    </div>
    <div id="dashboard-tables" class="row g-3">
        <div class="col-12 text-center p-4">
            <div class="spinner"></div>
            <p class="mt-2 text-muted">Loading tables...</p>
        </div>
    </div>
</div>

<!-- Table View -->
<div id="view-tables" class="view-section" style="<?php echo $currentPage === 'tables' ? '' : 'display:none;'; ?>">
    <div class="page-header">
        <h4 class="mb-0">Table View</h4>
        <div class="page-actions">
            <button class="btn btn-sm btn-outline" onclick="loadTables()">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
        </div>
    </div>
    <div id="tables-grid" class="row g-3">
        <div class="col-12 text-center p-4">
            <div class="spinner"></div>
            <p class="mt-2 text-muted">Loading tables...</p>
        </div>
    </div>
</div>

<!-- New Order View -->
<div id="view-new-order" class="view-section" style="<?php echo $currentPage === 'new-order' ? '' : 'display:none;'; ?>">
    <div class="page-header">
        <h4 class="mb-0">Create New Order</h4>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">Select Items</h6>
                    <input type="text" class="form-control" id="menu-search" placeholder="Search menu..." style="width:200px;" oninput="filterMenu()">
                </div>
                <div class="card-body">
                    <div class="category-filter mb-3">
                        <button class="category-filter-btn active" data-cat="all" onclick="filterByCategory('all', this)">All</button>
                        <?php foreach ($categories as $cat): ?>
                            <button class="category-filter-btn" data-cat="<?php echo (int) $cat['id']; ?>" onclick="filterByCategory(<?php echo (int) $cat['id']; ?>, this)"><?php echo sanitize($cat['name']); ?></button>
                        <?php endforeach; ?>
                    </div>
                    <div id="menu-items-grid" class="row g-2">
                        <?php foreach ($menuItems as $item): ?>
                            <div class="col-sm-6 col-md-4 col-lg-3 menu-item-wrapper"
                                 data-id="<?php echo (int) $item['id']; ?>"
                                 data-name="<?php echo sanitize($item['name']); ?>"
                                 data-price="<?php echo (float) ($item['offer_price'] ?? $item['regular_price']); ?>"
                                 data-cat="<?php echo (int) $item['category_id']; ?>">
                                <div class="menu-item-card" onclick="addToCart(this)">
                                    <div class="fw-bold" style="font-size:0.9rem;"><?php echo sanitize($item['name']); ?></div>
                                    <div class="text-primary fw-bold mt-1"><?php echo formatCurrency($item['offer_price'] ?? $item['regular_price']); ?></div>
                                    <div class="text-muted" style="font-size:0.75rem;"><?php echo sanitize($item['category_name']); ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">Order Details</h6>
                </div>
                <div class="card-body">
                    <div class="form-group">
                        <label class="form-label">Order Type</label>
                        <select class="form-select" id="order-type" onchange="toggleTableSelect()">
                            <option value="dine_in">Dine-In</option>
                            <option value="takeaway">Takeaway</option>
                        </select>
                    </div>
                    <div class="form-group" id="table-select-group">
                        <label class="form-label">Table</label>
                        <select class="form-select" id="order-table">
                            <option value="">Select Table</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Customer Name</label>
                        <input type="text" class="form-control" id="customer-name" placeholder="Optional">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Customer Phone</label>
                        <input type="text" class="form-control" id="customer-phone" placeholder="Optional">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Notes</label>
                        <textarea class="form-control" id="order-notes" rows="2" placeholder="Special instructions..."></textarea>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">Cart (<span id="cart-count">0</span> items)</h6>
                </div>
                <div class="card-body" id="cart-items" style="max-height:300px;overflow-y:auto;">
                    <div class="text-center text-muted p-3">No items added</div>
                </div>
                <div class="card-footer">
                    <div class="d-flex justify-content-between mb-2">
                        <span>Subtotal</span>
                        <strong id="cart-subtotal"><?php echo formatCurrency(0); ?></strong>
                    </div>
                    <button class="btn btn-primary w-100" id="submit-order-btn" onclick="submitOrder()" disabled>
                        <i class="fas fa-paper-plane"></i> Place Order
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- My Orders View -->
<div id="view-my-orders" class="view-section" style="<?php echo $currentPage === 'my-orders' ? '' : 'display:none;'; ?>">
    <div class="page-header">
        <h4 class="mb-0">My Orders</h4>
        <div class="page-actions">
            <button class="btn btn-sm btn-outline" onclick="loadMyOrders()">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
        </div>
    </div>
    <div id="my-orders-list">
        <div class="text-center p-4 text-muted">Loading orders...</div>
    </div>
</div>

<script>
var cart = [];
var menuItems = <?php echo json_encode($menuItems); ?>;
var tables = [];
var currentView = '<?php echo $currentPage; ?>';

document.addEventListener('DOMContentLoaded', function() {
    switchView(currentView);
    loadTables();
    loadMyOrders();
});

function switchView(view) {
    currentView = view;
    document.querySelectorAll('.view-section').forEach(function(el) { el.style.display = 'none'; });
    var target = document.getElementById('view-' + view);
    if (target) target.style.display = '';

    document.querySelectorAll('.sidebar-menu a').forEach(function(a) { a.classList.remove('active'); });
    var activeLink = document.querySelector('.sidebar-menu a[href*="view=' + view + '"]');
    if (activeLink) activeLink.classList.add('active');
}

function loadTables() {
    ajaxGet(BASE_URL + '/ajax/waiter_tables.php', function(data) {
        if (data.success && data.tables) {
            tables = data.tables;
            renderDashboardTables();
            renderTablesGrid();
            populateTableSelect();
        }
    });
}

function renderDashboardTables() {
    var container = document.getElementById('dashboard-tables');
    if (!tables.length) {
        container.innerHTML = '<div class="col-12 text-center p-4 text-muted">No tables configured</div>';
        return;
    }
    var html = '';
    tables.forEach(function(t) {
        var statusClass = 'status-' + t.status;
        html += '<div class="col-sm-6 col-md-4 col-lg-3">';
        html += '<div class="waiter-table-card ' + statusClass + '" onclick="tableAction(' + t.id + ')">';
        html += '<div class="table-number">' + escapeHtml(t.table_number) + '</div>';
        if (t.table_name) html += '<div class="text-muted" style="font-size:0.85rem;">' + escapeHtml(t.table_name) + '</div>';
        html += '<div class="mt-2"><span class="table-status-badge badge-' + getStatusBadge(t.status) + '">' + capitalize(t.status.replace('_', ' ')) + '</span></div>';
        if (t.current_order_id) html += '<div class="mt-1" style="font-size:0.8rem;">Order #' + escapeHtml(t.order_number) + '</div>';
        html += '</div></div>';
    });
    container.innerHTML = html;
}

function renderTablesGrid() {
    var container = document.getElementById('tables-grid');
    if (!tables.length) {
        container.innerHTML = '<div class="col-12 text-center p-4 text-muted">No tables configured</div>';
        return;
    }
    var html = '';
    tables.forEach(function(t) {
        var statusClass = 'status-' + t.status;
        html += '<div class="col-sm-6 col-md-4 col-lg-3">';
        html += '<div class="waiter-table-card ' + statusClass + '" onclick="tableAction(' + t.id + ')">';
        html += '<div class="table-number">' + escapeHtml(t.table_number) + '</div>';
        if (t.table_name) html += '<div class="text-muted" style="font-size:0.85rem;">' + escapeHtml(t.table_name) + '</div>';
        html += '<div class="capacity text-muted" style="font-size:0.75rem;"><i class="fas fa-users"></i> ' + t.capacity + '</div>';
        html += '<div class="mt-2"><span class="table-status-badge badge-' + getStatusBadge(t.status) + '">' + capitalize(t.status.replace('_', ' ')) + '</span></div>';
        if (t.current_order_id) html += '<div class="mt-1" style="font-size:0.8rem;">Order #' + escapeHtml(t.order_number) + '</div>';
        html += '</div></div>';
    });
    container.innerHTML = html;
}

function populateTableSelect() {
    var select = document.getElementById('order-table');
    if (!select) return;
    var val = select.value;
    var html = '<option value="">Select Table</option>';
    tables.forEach(function(t) {
        if (t.status === 'available' || t.status === 'occupied') {
            html += '<option value="' + t.id + '">' + escapeHtml(t.table_number) + (t.table_name ? ' - ' + escapeHtml(t.table_name) : '') + '</option>';
        }
    });
    select.innerHTML = html;
    select.value = val;
}

function tableAction(tableId) {
    var table = tables.find(function(t) { return t.id == tableId; });
    if (!table) return;

    if (table.current_order_id) {
        window.location.href = BASE_URL + '/waiter/?view=my-orders';
    } else if (table.status === 'available') {
        document.getElementById('order-type').value = 'dine_in';
        toggleTableSelect();
        document.getElementById('order-table').value = tableId;
        switchView('new-order');
    } else {
        showToast('Table is ' + table.status, 'info');
    }
}

function toggleTableSelect() {
    var type = document.getElementById('order-type').value;
    var group = document.getElementById('table-select-group');
    group.style.display = type === 'dine_in' ? '' : 'none';
}

function filterMenu() {
    var search = document.getElementById('menu-search').value.toLowerCase();
    document.querySelectorAll('.menu-item-wrapper').forEach(function(el) {
        var name = el.getAttribute('data-name').toLowerCase();
        el.style.display = name.indexOf(search) > -1 ? '' : 'none';
    });
}

function filterByCategory(catId, btn) {
    document.querySelectorAll('.category-filter-btn').forEach(function(b) { b.classList.remove('active'); });
    btn.classList.add('active');

    document.querySelectorAll('.menu-item-wrapper').forEach(function(el) {
        if (catId === 'all' || el.getAttribute('data-cat') == catId) {
            el.style.display = '';
        } else {
            el.style.display = 'none';
        }
    });
}

function addToCart(el) {
    var wrapper = el.closest('.menu-item-wrapper');
    var id = parseInt(wrapper.getAttribute('data-id'));
    var name = wrapper.getAttribute('data-name');
    var price = parseFloat(wrapper.getAttribute('data-price'));

    var existing = cart.find(function(c) { return c.menu_item_id === id; });
    if (existing) {
        existing.quantity++;
    } else {
        cart.push({
            menu_item_id: id,
            item_name: name,
            unit_price: price,
            variation_name: null,
            variation_price: 0,
            quantity: 1,
            item_notes: '',
            addons: []
        });
    }
    renderCart();
}

function removeFromCart(index) {
    cart.splice(index, 1);
    renderCart();
}

function updateCartQty(index, delta) {
    cart[index].quantity += delta;
    if (cart[index].quantity <= 0) {
        cart.splice(index, 1);
    }
    renderCart();
}

function renderCart() {
    var container = document.getElementById('cart-items');
    var countEl = document.getElementById('cart-count');
    var subtotalEl = document.getElementById('cart-subtotal');
    var submitBtn = document.getElementById('submit-order-btn');

    if (!cart.length) {
        container.innerHTML = '<div class="text-center text-muted p-3">No items added</div>';
        countEl.textContent = '0';
        subtotalEl.textContent = formatCurrency(0);
        submitBtn.disabled = true;
        return;
    }

    submitBtn.disabled = false;
    var subtotal = 0;
    var html = '';

    cart.forEach(function(item, i) {
        var lineTotal = (item.unit_price + item.variation_price) * item.quantity;
        subtotal += lineTotal;
        html += '<div class="cart-item">';
        html += '<div style="flex:1;">';
        html += '<div class="fw-bold" style="font-size:0.9rem;">' + escapeHtml(item.item_name) + '</div>';
        html += '<div class="text-muted" style="font-size:0.8rem;">' + formatCurrency(item.unit_price) + ' each</div>';
        html += '</div>';
        html += '<div class="d-flex align-items-center gap-2">';
        html += '<button class="btn btn-sm btn-outline-secondary" onclick="updateCartQty(' + i + ', -1)">-</button>';
        html += '<span class="fw-bold">' + item.quantity + '</span>';
        html += '<button class="btn btn-sm btn-outline-secondary" onclick="updateCartQty(' + i + ', 1)">+</button>';
        html += '<span class="fw-bold ms-2" style="min-width:60px;text-align:right;">' + formatCurrency(lineTotal) + '</span>';
        html += '<button class="btn btn-sm btn-outline-danger" onclick="removeFromCart(' + i + ')"><i class="fas fa-times"></i></button>';
        html += '</div></div>';
    });

    container.innerHTML = html;
    countEl.textContent = cart.length;
    subtotalEl.textContent = formatCurrency(subtotal);
}

function submitOrder() {
    if (!cart.length) return;

    var btn = document.getElementById('submit-order-btn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Placing Order...';

    var data = {
        action: 'create_order',
        csrf_token: CSRF_TOKEN,
        order_type: document.getElementById('order-type').value,
        table_id: document.getElementById('order-table').value,
        customer_name: document.getElementById('customer-name').value,
        customer_phone: document.getElementById('customer-phone').value,
        order_notes: document.getElementById('order-notes').value,
        items: cart
    };

    fetch(BASE_URL + '/ajax/waiter_action.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        credentials: 'same-origin',
        body: JSON.stringify(data)
    })
    .then(function(r) { return r.json(); })
    .then(function(result) {
        if (result.success) {
            showToast('Order ' + result.order_number + ' created!', 'success');
            cart = [];
            renderCart();
            document.getElementById('customer-name').value = '';
            document.getElementById('customer-phone').value = '';
            document.getElementById('order-notes').value = '';
            loadTables();
            loadMyOrders();
        } else {
            showToast(result.message || 'Failed to create order', 'error');
        }
    })
    .catch(function() {
        showToast('Network error', 'error');
    })
    .finally(function() {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-paper-plane"></i> Place Order';
    });
}

function loadMyOrders() {
    ajaxGet(BASE_URL + '/ajax/kitchen_orders.php', function(data) {
        if (data.success && data.orders) {
            renderMyOrders(data.orders);
        }
    });
}

function renderMyOrders(orders) {
    var container = document.getElementById('my-orders-list');
    if (!orders.length) {
        container.innerHTML = '<div class="empty-state"><i class="fas fa-clipboard"></i><h5>No active orders</h5><p>Orders will appear here</p></div>';
        return;
    }

    var html = '';
    orders.forEach(function(order) {
        var statusBadge = getStatusBadge(order.order_status);
        html += '<div class="card mb-3">';
        html += '<div class="card-header d-flex justify-content-between align-items-center">';
        html += '<div><strong>#' + escapeHtml(order.order_number) + '</strong>';
        if (order.table_number) html += ' <span class="text-muted">- Table ' + escapeHtml(order.table_number) + '</span>';
        html += '</div>';
        html += '<span class="badge badge-' + statusBadge + '">' + capitalize(order.order_status) + '</span>';
        html += '</div>';
        html += '<div class="card-body">';
        html += '<div class="mb-2" style="font-size:0.85rem;color:#666;">';
        html += capitalize(order.order_type.replace('_', ' ')) + ' | ' + order.created_at;
        if (order.customer_name) html += ' | ' + escapeHtml(order.customer_name);
        html += '</div>';

        if (order.items && order.items.length) {
            order.items.forEach(function(item) {
                html += '<div style="font-size:0.9rem;padding:2px 0;">' + item.quantity + 'x ' + escapeHtml(item.item_name);
                if (item.variation_name) html += ' <span class="text-muted">(' + escapeHtml(item.variation_name) + ')</span>';
                html += '</div>';
            });
        }

        html += '<div class="fw-bold mt-2">' + formatCurrency(order.grand_total) + '</div>';
        html += '</div>';

        if (order.order_status === 'ready') {
            html += '<div class="card-footer">';
            html += '<button class="btn btn-sm btn-success" onclick="markServed(' + order.id + ')"><i class="fas fa-check"></i> Mark Served</button>';
            html += '</div>';
        }

        html += '</div>';
    });

    container.innerHTML = html;
}

function markServed(orderId) {
    fetch(BASE_URL + '/ajax/waiter_action.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        credentials: 'same-origin',
        body: JSON.stringify({
            action: 'mark_served',
            csrf_token: CSRF_TOKEN,
            order_id: orderId
        })
    })
    .then(function(r) { return r.json(); })
    .then(function(result) {
        if (result.success) {
            showToast('Order marked as served', 'success');
            loadMyOrders();
            loadTables();
        } else {
            showToast(result.message || 'Failed', 'error');
        }
    })
    .catch(function() {
        showToast('Network error', 'error');
    });
}

function getStatusBadge(status) {
    var map = {
        available: 'success', occupied: 'warning', ordered: 'info',
        preparing: 'danger', ready: 'success', bill_requested: 'primary',
        reserved: 'secondary', cleaning: 'secondary',
        new: 'danger', confirmed: 'warning', served: 'info',
        completed: 'success', cancelled: 'secondary', rejected: 'secondary'
    };
    return map[status] || 'secondary';
}

function capitalize(str) {
    if (!str) return '';
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function formatCurrency(amount) {
    var symbols = {LKR:'Rs.', USD:'$', EUR:'\u20AC', GBP:'\u00A3', INR:'\u20B9'};
    var symbol = symbols['<?php echo $restaurantCurrency; ?>'] || '$ ';
    return symbol + parseFloat(amount || 0).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
</script>

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