<!DOCTYPE html>
<html Dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="POS & Billing - Granny Restaurant Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="manager-styles.css">

    <title>POS & Billing - Granny Restaurant</title>

    <style>
        .main-content {
            padding: 30px 30px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .page-header h1 {
            color: #1e3c72;
            font-size: 28px;
        }

        .header-actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(42, 82, 152, 0.3);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }



        .pos-container {
            display: grid;
            grid-template-columns: 1fr 1fr 300px;
            gap: 20px;
            margin-bottom: 30px;
        }

        .bills-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .bills-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 20px;
            font-size: 16px;
            font-weight: 600;
        }

        .server-orders-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .server-orders-header {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            padding: 20px;
            font-size: 16px;
            font-weight: 600;
        }

        .server-orders-list {
            max-height: 600px;
            overflow-y: auto;
        }

        .bills-list {
            max-height: 600px;
            overflow-y: auto;
        }

        .bill-item {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .bill-item:hover {
            background: #f8f9fa;
        }

        .bill-item.active {
            background: #e8f4fd;
            border-left: 4px solid #2a5298;
        }

        .bill-number {
            font-weight: 600;
            color: #1e3c72;
            margin-bottom: 5px;
        }

        .bill-meta {
            font-size: 12px;
            color: #999;
        }

        .bill-amount {
            font-size: 14px;
            color: #28a745;
            margin-top: 5px;
            font-weight: 600;
        }

        .pos-sidebar {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .pos-sidebar-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .pos-sidebar-card h3 {
            color: #1e3c72;
            font-size: 14px;
            margin-bottom: 15px;
            text-transform: uppercase;
            font-weight: 600;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #666;
            font-size: 12px;
            font-weight: 600;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            font-size: 13px;
        }

        .bill-detail {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .bill-detail-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .bill-detail-header h2 {
            color: #1e3c72;
            font-size: 20px;
        }

        .bill-detail-status {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-open {
            background: #cce5ff;
            color: #004085;
        }

        .status-billed {
            background: #fff3cd;
            color: #856404;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .items-section {
            margin-bottom: 20px;
        }

        .items-header {
            font-weight: 600;
            color: #1e3c72;
            padding: 10px 0;
            border-bottom: 2px solid #eee;
            margin-bottom: 10px;
        }

        .item-row {
            display: grid;
            grid-template-columns: 1fr 80px 80px 100px;
            gap: 10px;
            padding: 10px 0;
            border-bottom: 1px solid #f0f0f0;
            align-items: center;
        }

        .item-name {
            font-weight: 500;
            color: #333;
        }

        .item-qty {
            text-align: center;
            color: #666;
        }

        .item-price {
            text-align: right;
            color: #666;
        }

        .item-total {
            text-align: right;
            font-weight: 600;
            color: #1e3c72;
        }

        .summary-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            color: #666;
        }

        .summary-row.total {
            font-size: 18px;
            font-weight: 700;
            color: #1e3c72;
            border-top: 2px solid #ddd;
            padding-top: 10px;
            margin-top: 10px;
        }

        .actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .large-btn {
            flex: 1;
            padding: 12px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-print {
            background: #6c757d;
            color: white;
        }

        .btn-print:hover {
            background: #5a6268;
        }

        .btn-pay {
            background: #28a745;
            color: white;
        }

        .btn-pay:hover {
            background: #218838;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        @media (max-width: 1024px) {
            .pos-container {
                grid-template-columns: 1fr 1fr;
            }

            .item-row {
                grid-template-columns: 1fr 60px 60px 80px;
            }
        }

        @media (max-width: 768px) {
            .pos-container {
                grid-template-columns: 1fr;
            }

            .page-header {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }

            .bill-detail {
                padding: 20px;
            }

            .item-row {
                grid-template-columns: 1fr 50px 50px;
            }

            .item-price {
                display: none;
            }

            .main-content {
                padding: 20px;
                padding-top: 80px;
            }
        }
    </style>
</head>

<body>
    <div class="dashboard-container">
        <?php include 'sidebar.php'; ?>
        <div class="main-content">
            <div class="container">
                <div class="page-header">
            <h1><i class="fas fa-cash-register"></i> POS & Billing</h1>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="createNewBill()">
                    <i class="fas fa-plus"></i> New Bill
                </button>
                <button class="btn btn-primary" onclick="refreshBills()">
                    <i class="fas fa-sync"></i> Refresh
                </button>
            </div>
        </div>

                <div class="pos-container">
                    <!-- Open Bills List -->
                    <div class="bills-section">
                        <div class="bills-header">
                            <i class="fas fa-list"></i> Open Bills
                        </div>
                        <div class="bills-list" id="billsList">
                            <div style="padding: 40px 20px; text-align: center; color: #999;">
                                <i class="fas fa-spinner fa-spin"></i> Loading...
                            </div>
                        </div>
                    </div>

                    <!-- Server Orders List -->
                    <div class="server-orders-section">
                        <div class="server-orders-header">
                            <i class="fas fa-utensils"></i> Pending Server Orders
                        </div>
                        <div class="server-orders-list" id="serverOrdersList">
                            <div style="padding: 40px 20px; text-align: center; color: #999;">
                                <i class="fas fa-spinner fa-spin"></i> Loading...
                            </div>
                        </div>
                    </div>

                    <!-- Right Sidebar Panel -->
                    <div class="pos-sidebar">
                        <div class="pos-sidebar-card">
                            <h3>Create Bill</h3>
                            <div class="form-group">
                                <label>Select Table</label>
                                <select id="tableSelect" onchange="selectTableForBilling()">
                                    <option value="">Select a table...</option>
                                </select>
                            </div>
                            <button class="btn btn-primary" style="width: 100%;" onclick="createBillForTable()">
                                Create Bill
                            </button>
                        </div>

                        <div class="pos-sidebar-card">
                            <h3>Quick Actions</h3>
                            <button class="btn btn-success" style="width: 100%; margin-bottom: 10px;" onclick="printBill()">
                                <i class="fas fa-print"></i> Print Bill
                            </button>
                            <button class="btn btn-primary" style="width: 100%;" onclick="processBillPayment()">
                                <i class="fas fa-credit-card"></i> Process Payment
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Bill Detail -->
                <div class="bill-detail" id="billDetail">
                    <div class=\"empty-state\">
                        <i class=\"fas fa-inbox\"></i>
                        <p>Select a bill to view details</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        let currentBill = null;

        $(document).ready(function() {
            checkAuthentication();
            loadOpenBills();
            loadPendingServerOrders();
            loadAvailableTables();
            
            // Refresh both lists every 15 seconds
            setInterval(function() {
                loadOpenBills();
                loadPendingServerOrders();
            }, 15000);
        });

        function checkAuthentication() {
            if (!localStorage.getItem('manager_id')) {
                window.location.href = 'login.php';
            }
        }

        function loadOpenBills() {
            $.ajax({
                url: '../backend/manager_pos_api.php?action=get_open_bills',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayBillsList(response.data);
                    }
                }
            });
        }

        function displayBillsList(bills) {
            if (bills.length === 0) {
                $('#billsList').html('<div style="padding: 30px 20px; text-align: center; color: #999;">No open bills</div>');
                return;
            }

            let html = '';
            bills.forEach(bill => {
                html += `
                    <div class="bill-item" onclick="selectBill(${bill.id})">
                        <div class="bill-number">${bill.billing_number}</div>
                        <div class="bill-meta">Table ${bill.table_number}</div>
                        <div class="bill-amount">₹${parseFloat(bill.total).toFixed(2)}</div>
                    </div>
                `;
            });

            $('#billsList').html(html);
        }

        // Load pending server orders
        function loadPendingServerOrders() {
            $.ajax({
                url: '../backend/manager_pos_api.php?action=get_pending_server_orders',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayServerOrdersList(response.data);
                    }
                }
            });
        }

        // Display pending server orders
        function displayServerOrdersList(orders) {
            if (orders.length === 0) {
                $('#serverOrdersList').html('<div style="padding: 30px 20px; text-align: center; color: #999;"><i class="fas fa-check-circle"></i> <p>No pending orders from servers</p></div>');
                return;
            }

            let html = '';
            orders.forEach(order => {
                html += `
                    <div class="bill-item" onclick="selectServerOrder(${order.order_id})" style="cursor: pointer;">
                        <div class="bill-number">Order #${order.order_number}</div>
                        <div class="bill-meta">
                            <i class="fas fa-user-tie"></i> ${order.server_name} | 
                            <i class="fas fa-chair"></i> Table ${order.table_number}
                        </div>
                        <div class="bill-meta">
                            <i class="fas fa-list"></i> ${order.items_count} item(s) | 
                            <span style="color: #28a745; font-weight: 600;">₹${parseFloat(order.total_amount).toFixed(2)}</span>
                        </div>
                        <button class="btn btn-primary" style="width: 100%; margin-top: 10px; padding: 8px; font-size: 12px;" onclick="event.stopPropagation(); convertServerOrderToBill(${order.order_id})">
                            <i class="fas fa-exchange-alt"></i> Convert to Bill
                        </button>
                    </div>
                `;
            });

            $('#serverOrdersList').html(html);
        }

        // Select server order to view details
        function selectServerOrder(orderId) {
            $.ajax({
                url: `../backend/manager_pos_api.php?action=get_server_order_details&order_id=${orderId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayServerOrderDetail(response.data);
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }
            });
        }

        // Display server order details
        function displayServerOrderDetail(data) {
            const order = data.order;
            const items = data.items;

            let itemsHtml = '';
            if (items && items.length > 0) {
                itemsHtml += '<div class="items-header"><div style="grid-column: 1/-1; display:grid; grid-template-columns: 1fr 80px 80px 100px; gap: 10px;"><strong>Item</strong><div style="text-align: center;"><strong>Qty</strong></div><div style="text-align: right;"><strong>Price</strong></div><div style="text-align: right;"><strong>Total</strong></div></div></div>';
                items.forEach(item => {
                    itemsHtml += `
                        <div class="item-row">
                            <div class="item-name">
                                <strong>${item.item_name}</strong>
                                ${item.special_instructions ? `<div style="font-size: 12px; color: #999;">Note: ${item.special_instructions}</div>` : ''}
                            </div>
                            <div class="item-qty">${item.quantity}</div>
                            <div class="item-price">₹${parseFloat(item.unit_price).toFixed(2)}</div>
                            <div class="item-total">₹${parseFloat(item.total_price).toFixed(2)}</div>
                        </div>
                    `;
                });
            }

            const html = `
                <div class="bill-detail-header">
                    <div>
                        <h2>Order #${order.order_number}</h2>
                        <div style="font-size: 14px; color: #666; margin-top: 5px;">
                            <i class="fas fa-chair"></i> Table ${order.table_number} (Capacity: ${order.capacity}) | 
                            <i class="fas fa-user-tie"></i> ${order.server_name}
                        </div>
                        <div style="font-size: 12px; color: #999; margin-top: 3px;">
                            Location: Floor ${order.floor} - ${order.section}
                        </div>
                    </div>
                    <span class="bill-detail-status" style="background: #ff6b6b; color: white; font-weight: 600;">PENDING</span>
                </div>

                ${order.special_requests ? `
                <div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 12px; margin: 15px 0; border-radius: 4px; color: #856404; font-size: 13px;">
                    <strong><i class="fas fa-sticky-note"></i> Special Requests:</strong><br>
                    ${order.special_requests}
                </div>
                ` : ''}

                <div class="items-section">
                    ${itemsHtml || '<div style="padding: 20px; text-align: center; color: #999;">No items</div>'}
                </div>

                <div class="summary-section">
                    <div class="summary-row total">
                        <span>Total Amount:</span>
                        <span>₹${parseFloat(order.total_amount).toFixed(2)}</span>
                    </div>
                </div>

                <div class="actions">
                    <button class="large-btn btn-pay" onclick="convertServerOrderToBill(${order.id})" style="background: #27ae60; color: white; flex: 1;">
                        <i class="fas fa-exchange-alt"></i> Convert to Bill
                    </button>
                    <button class="large-btn btn-print" onclick="printServerOrder(${order.id})">
                        <i class="fas fa-print"></i> Print
                    </button>
                </div>
            `;

            $('#billDetail').html(html);
        }

        // Convert server order to bill
        function convertServerOrderToBill(orderId) {
            if (!orderId) {
                Swal.fire('Error', 'Please select an order', 'error');
                return;
            }

            Swal.fire({
                title: 'Convert Order to Bill?',
                text: 'This will create a bill from the server order and mark it ready for payment.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#27ae60',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Convert'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '../backend/manager_pos_api.php?action=convert_server_order_to_bill',
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({ order_id: orderId }),
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    title: 'Success!',
                                    text: `Bill ${response.data.billing_number} created successfully`,
                                    icon: 'success',
                                    confirmButtonColor: '#d4a574'
                                }).then(() => {
                                    // Refresh both lists
                                    loadOpenBills();
                                    loadPendingServerOrders();
                                    // Select the newly created bill
                                    selectBill(response.data.billing_id);
                                    $('#billDetail').html('<div class="empty-state"><i class="fas fa-inbox"></i><p>Select a bill to view details</p></div>');
                                });
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Failed to convert order', 'error');
                        }
                    });
                }
            });
        }

        // Print server order details
        function printServerOrder(orderId) {
            window.print();
        }

        function selectBill(billId) {
            currentBill = billId;
            $('.bill-item').removeClass('active');
            $(`[onclick="selectBill(${billId})"]`).addClass('active');

            $.ajax({
                url: `../backend/manager_pos_api.php?action=get_bill&billing_id=${billId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayBillDetail(response.data);
                    }
                }
            });
        }

        function displayBillDetail(bill) {
            let itemsHtml = '';

            if (bill.items && bill.items.length > 0) {
                itemsHtml += '<div class="items-header"><div style="grid-column: 1/-1; display:grid; grid-template-columns: 1fr 80px 80px 100px; gap: 10px;">Item<div style="text-align: center;">Qty</div><div style="text-align: right;">Price</div><div style="text-align: right;">Total</div></div></div>';
                bill.items.forEach(item => {
                    itemsHtml += `
                        <div class="item-row">
                            <div class="item-name">${item.item_name}</div>
                            <div class="item-qty">${item.quantity}</div>
                            <div class="item-price">₹${parseFloat(item.unit_price).toFixed(2)}</div>
                            <div class="item-total">₹${parseFloat(item.total_price).toFixed(2)}</div>
                        </div>
                    `;
                });
            }

            const html = `
                <div class="bill-detail-header">
                    <h2>${bill.billing_number}</h2>
                    <span class="bill-detail-status status-${bill.status}">${bill.status.toUpperCase()}</span>
                </div>

                <div style="font-size: 14px; color: #666; margin-bottom: 20px;">
                    <strong>Table:</strong> ${bill.table_number} | 
                    <strong>Created:</strong> ${new Date(bill.created_at).toLocaleString()}
                </div>

                <div class="items-section">
                    ${itemsHtml || '<div style="padding: 20px; text-align: center; color: #999;">No items</div>'}
                </div>

                <div class="summary-section">
                    <div class="summary-row">
                        <span>Subtotal:</span>
                        <span>₹${parseFloat(bill.subtotal || 0).toFixed(2)}</span>
                    </div>
                    <div class="summary-row">
                        <span>Tax (5%):</span>
                        <span>₹${parseFloat(bill.tax || 0).toFixed(2)}</span>
                    </div>
                    ${bill.discount > 0 ? `
                        <div class="summary-row">
                            <span>Discount:</span>
                            <span>-₹${parseFloat(bill.discount).toFixed(2)}</span>
                        </div>
                    ` : ''}
                    <div class="summary-row total">
                        <span>Total:</span>
                        <span>₹${parseFloat(bill.total || 0).toFixed(2)}</span>
                    </div>
                </div>

                <div class="actions">
                    <button class="large-btn btn-print" onclick="printBill()">
                        <i class="fas fa-print"></i> Print
                    </button>
                    ${bill.status === 'open' ? `
                        <button class="large-btn btn-pay" onclick="completeBill()">
                            <i class="fas fa-credit-card"></i> Bill Customer
                        </button>
                    ` : `
                        <button class="large-btn btn-pay" onclick="processBillPayment()">
                            <i class="fas fa-money-bill"></i> Process Payment
                        </button>
                    `}
                </div>
            `;

            $('#billDetail').html(html);
        }

        function loadAvailableTables() {
            $.ajax({
                url: '../backend/manager_tables_api.php?action=list&status=available',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        let options = '<option value="">Select a table...</option>';
                        response.data.forEach(table => {
                            options += `<option value="${table.id}">Table ${table.table_number} (${table.current_capacity} seats)</option>`;
                        });
                        $('#tableSelect').html(options);
                    }
                }
            });
        }

        function createNewBill() {
            Swal.fire({
                title: 'Select Table',
                input: 'select',
                inputOptions: {
                    '': 'Select a table'
                },
                inputPlaceholder: 'Choose a table',
                showCancelButton: true,
                confirmButtonText: 'Create Bill',
                preConfirm: (value) => {
                    if (!value) {
                        Swal.showValidationMessage('Please select a table');
                        return false;
                    }
                    return value;
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    createBillForTable(result.value);
                }
            });
        }

        function createBillForTable(tableId = null) {
            tableId = tableId || $('#tableSelect').val();
            if (!tableId) {
                Swal.fire('Error', 'Please select a table', 'error');
                return;
            }

            $.ajax({
                url: '../backend/manager_pos_api.php?action=create_bill',
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({ table_id: parseInt(tableId) }),
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Success', 'Bill created successfully', 'success');
                        loadOpenBills();
                        selectBill(response.data.billing_id);
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }
            });
        }

        function completeBill() {
            if (!currentBill) return;

            $.ajax({
                url: '../backend/manager_pos_api.php?action=complete_bill',
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({ billing_id: currentBill }),
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Success', 'Bill presented to customer', 'success');
                        loadOpenBills();
                        selectBill(currentBill);
                    }
                }
            });
        }

        function processBillPayment() {
            if (!currentBill) {
                Swal.fire('Error', 'Please select a bill', 'error');
                return;
            }

            Swal.fire({
                title: 'Process Payment',
                html: `
                    <div style="text-align: left;">
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600;">Payment Method</label>
                            <select id="paymentMethod" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                <option value="">Select method</option>
                                <option value="cash">Cash</option>
                                <option value="card">Credit/Debit Card</option>
                                <option value="upi">UPI</option>
                                <option value="online">Online Transfer</option>
                                <option value="cheque">Cheque</option>
                            </select>
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 5px; font-weight: 600;">Amount Paid</label>
                            <input type="number" id="amountPaid" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;" placeholder="Enter amount">
                        </div>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Complete Payment',
                preConfirm: () => {
                    const method = $('#paymentMethod').val();
                    const amount = $('#amountPaid').val();

                    if (!method || !amount) {
                        Swal.showValidationMessage('Please fill all fields');
                        return false;
                    }

                    return { method, amount };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '../backend/manager_pos_api.php?action=process_payment',
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({
                            billing_id: currentBill,
                            payment_method: result.value.method,
                            amount_paid: parseFloat(result.value.amount)
                        }),
                        success: function(response) {
                            if (response.success) {
                                const change = response.data.change.toFixed(2);
                                Swal.fire('Success', `Payment received! Change: ₹${change}`, 'success');
                                loadOpenBills();
                                $('#billDetail').html('<div class="empty-state"><i class="fas fa-inbox"></i><p>Select a bill to view details</p></div>');
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        }
                    });
                }
            });
        }

        function printBill() {
            if (!currentBill) {
                Swal.fire('Error', 'No bill selected', 'error');
                return;
            }

            window.print();
        }

        function refreshBills() {
            loadOpenBills();
            loadPendingServerOrders();
            Swal.fire('Success', 'Bills and Orders refreshed', 'success');
        }

        function selectTableForBilling() {
            // Method for selecting table
        }
    </script>

    <!-- Manager Sidebar Script -->
    <script src="manager-sidebar.js"></script>
</body>

</html>
