<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';
include '../auth.php';
checkAuth();
$user = getCurrentUser();

// Get products for the POS terminal  
$products = $conn->query("SELECT id, name, category, price, half_price, stock, barcode FROM products WHERE stock > 0 ORDER BY name");
$customers = $conn->query("SELECT * FROM customers ORDER BY name");
// Get categories with images
$categories_result = $conn->query("SELECT name, image FROM categories ORDER BY name");
$categories = [];
while ($row = $categories_result->fetch_assoc()) {
    $categories[] = $row;
}

// Ensure sales officers and commission tables exist
$conn->query("CREATE TABLE IF NOT EXISTS sales_officers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, is_active TINYINT(1) DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
$conn->query("CREATE TABLE IF NOT EXISTS sales_commissions (id INT AUTO_INCREMENT PRIMARY KEY, sale_id INT NOT NULL, sales_officer_id INT NOT NULL, commission_amount DECIMAL(10,2) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (sale_id) REFERENCES sales(id) ON DELETE CASCADE, FOREIGN KEY (sales_officer_id) REFERENCES sales_officers(id) ON DELETE CASCADE)");

// Load active sales officers
$sales_officers = $conn->query("SELECT id, name FROM sales_officers WHERE is_active = 1 ORDER BY name");
?>
<!DOCTYPE html>
<html>
<head>
    <title>POS Terminal - Dilrukshi Tex</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; font-family: 'Segoe UI', sans-serif; }
        .pos-container { height: 100vh; overflow: hidden; }
        .product-grid { height: 60vh; overflow-y: auto; }
        .product-card { 
            cursor: pointer; 
            transition: all 0.3s ease; 
            border: 2px solid transparent;
        }
        .product-card:hover { 
            border-color: #007bff; 
            transform: scale(1.02); 
        }
        .cart-section { 
            background: white; 
            border-left: 3px solid #007bff; 
            height: 100vh; 
            overflow-y: auto;
        }
        .cart-item { 
            border-bottom: 1px solid #eee; 
            padding: 10px 0; 
        }
        .total-section { 
            background: #007bff; 
            color: white; 
            position: sticky; 
            bottom: 0; 
        }
        .barcode-input { 
            font-size: 1.2rem; 
            border: 3px solid #28a745; 
        }
        .qty-btn { 
            width: 35px; 
            height: 35px; 
            border-radius: 50%; 
        }
    </style>
</head>
<body>
    <div class="container-fluid pos-container">
        <div class="row h-100">
            <!-- Left Side - Products -->
            <div class="col-8 p-3">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h3><i class="fas fa-cash-register"></i> POS Terminal</h3>
                    <div>
                        <a href="../" class="btn btn-secondary me-2"><i class="fas fa-home"></i> Dashboard</a>
                        <a href="../logout.php" class="btn btn-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
                    </div>
                </div>
                
                <!-- Barcode Scanner Input -->
                <div class="mb-3 position-relative">
                    <input type="text" id="barcodeInput" class="form-control barcode-input" 
                           placeholder="Scan barcode or search product..." autofocus>
                    <!-- Suggestions dropdown -->
                    <div id="brandSuggestions" class="list-group" style="position:absolute;left:0;top:100%;width:100%;">
                        <!-- dynamically filled -->
                    </div>
                </div>
                
                <!-- Product Categories -->
                <style>
                .category-btn {
                    position: relative;
                    width: 90px;
                    height: 90px;
                    padding: 0;
                    margin-right: 16px;
                    margin-bottom: 12px;
                    border-radius: 10px !important;
                    overflow: hidden;
                    display: inline-block;
                    background: #e9ecef;
                }
                .category-btn img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    border-radius: 10px;
                }
                .category-label {
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    width: 100%;
                    background: rgba(0,0,0,0.5);
                    color: #fff;
                    font-weight: bold;
                    text-align: center;
                    padding: 6px 0;
                    font-size: 1rem;
                    border-bottom-left-radius: 10px;
                    border-bottom-right-radius: 10px;
                }
                </style>
                <div class="mb-3 d-flex flex-wrap align-items-center">
                    <button class="btn btn-outline-primary me-2 category-filter category-btn" data-category="all">
                        <span class="category-label">All</span>
                    </button>
                    <?php foreach ($categories as $cat): ?>
                        <button class="btn btn-outline-primary category-filter category-btn" data-category="<?= htmlspecialchars($cat['name']) ?>">
                            <?php if (!empty($cat['image'])): ?>
                                <img src="../products/<?= htmlspecialchars($cat['image']) ?>" alt="Category Image">
                            <?php else: ?>
                                <div style="width:100%;height:100%;background:#adb5bd;"></div>
                            <?php endif; ?>
                            <span class="category-label"><?= htmlspecialchars($cat['name']) ?></span>
                        </button>
                    <?php endforeach; ?>
                </div>
                
                <!-- Products Grid -->
                <div class="product-grid">
                    <div class="row" id="productsGrid">
                        <?php $all_products = [];
                        while ($product = $products->fetch_assoc()) {
                            $all_products[] = $product;
                        }
                        foreach ($all_products as $product): ?>
                        <div class="col-md-4 col-lg-3 mb-3 product-item" data-category="<?= htmlspecialchars($product['category']) ?>">
                            <div class="card product-card" onclick='addToCart(<?= htmlspecialchars(json_encode($product)) ?>)'>
                                <div class="card-body text-center">
                                    <h6 class="card-title"><?= htmlspecialchars($product['name']) ?></h6>
                                    <p class="text-muted small"><?= htmlspecialchars($product['category']) ?></p>
                                    <h5 class="text-primary">Rs <?= number_format($product['price'], 2) ?></h5>
                                    <small class="text-success">Stock: <?= $product['stock'] ?></small>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <script>
                document.querySelectorAll('.category-filter').forEach(function(btn) {
                    btn.addEventListener('click', function() {
                        var selected = this.getAttribute('data-category');
                        document.querySelectorAll('.category-filter').forEach(b => b.classList.remove('active'));
                        this.classList.add('active');
                        document.querySelectorAll('.product-item').forEach(function(item) {
                            if (selected === 'all' || item.getAttribute('data-category') === selected) {
                                item.style.display = '';
                            } else {
                                item.style.display = 'none';
                            }
                        });
                    });
                });
                </script>
            </div>
            
            <!-- Right Side - Cart -->
            <div class="col-4 cart-section p-0">
                <div class="p-3">
                    <h4><i class="fas fa-shopping-cart"></i> Cart</h4>
                    
                    <!-- Customer Selection -->
                    <div class="mb-3">
                        <select class="form-select mb-2" id="customerSelect">
                            <option value="">Walk-in Customer</option>
                            <?php while ($customer = $customers->fetch_assoc()): ?>
                            <option value="<?= $customer['id'] ?>"><?= htmlspecialchars($customer['name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                        <!-- Hidden fields for compatibility with hold order functionality -->
                        <input type="text" class="form-control mb-2" id="customerName" placeholder="Customer Name (optional)" maxlength="100" style="display:none;">
                        <input type="text" class="form-control mb-2" id="customerPhone" placeholder="Customer Phone (optional)" maxlength="20">
                        <select class="form-select mb-2" id="salesOfficerSelect">
                            <option value="">Select Sales Officer (optional)</option>
                            <?php if ($sales_officers && $sales_officers->num_rows > 0): ?>
                                <?php while ($officer = $sales_officers->fetch_assoc()): ?>
                                    <option value="<?= $officer['id'] ?>"><?= htmlspecialchars($officer['name']) ?></option>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <option value="" disabled>No sales officers yet</option>
                            <?php endif; ?>
                        </select>
                        <input type="text" class="form-control" id="tableNumber" placeholder="Table Number (optional)" maxlength="20" style="display:none;">
                    </div>
                    
                    <!-- Held Order Indicator -->
                    <div id="heldOrderIndicator" style="display: none;" class="alert alert-info py-2 mb-2">
                        <small><i class="fas fa-info-circle"></i> Working with resumed held order</small>
                    </div>
                    
                    <!-- Cart Items -->
                    <div id="cartItems" style="min-height: 300px;">
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-shopping-cart fa-3x"></i>
                            <p>Cart is empty</p>
                        </div>
                    </div>
                    <!-- Custom Product Quick Add -->
                    <div class="card my-3">
                        <div class="card-body p-2">
                            <h6 class="mb-2"><i class="fas fa-plus-circle"></i> Quick Bill Custom Product</h6>
                            <div class="row g-1 align-items-end">
                                <div class="col-5">
                                    <input type="text" id="customProductName" class="form-control form-control-sm" placeholder="Product Name">
                                </div>
                                <div class="col-3">
                                    <input type="number" id="customProductPrice" class="form-control form-control-sm" placeholder="Price" min="0" step="0.01">
                                </div>
                                <div class="col-2">
                                    <input type="number" id="customProductQty" class="form-control form-control-sm" placeholder="Qty" min="1" value="1">
                                </div>
                                <div class="col-2">
                                    <button class="btn btn-primary btn-sm w-100" onclick="addCustomProductToCart()"><i class="fas fa-plus"></i> Add</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Cart Summary -->
                    <div class="border-top pt-3">
                        <div class="d-flex justify-content-between">
                            <span>Subtotal:</span>
                            <span id="subtotal">Rs 0.00</span>
                        </div>
                        <div class="d-flex justify-content-between">
                <span>Discount:</span>
                <input type="text" id="discount" class="form-control form-control-sm w-50" 
                    value="0" placeholder="e.g. 10% or 100" onchange="updateTotals()">
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between h5">
                            <strong>Total:</strong>
                            <strong id="total">Rs 0.00</strong>
                        </div>
                    </div>
                    
                    <!-- Payment Methods -->
                    <div class="mb-3">
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="paymentMethod" id="cash" value="cash" checked>
                            <label class="btn btn-outline-success" for="cash"><i class="fas fa-money-bill"></i> Cash</label>
                            
                            <input type="radio" class="btn-check" name="paymentMethod" id="card" value="card">
                            <label class="btn btn-outline-primary" for="card"><i class="fas fa-credit-card"></i> Card</label>
                            
                            <input type="radio" class="btn-check" name="paymentMethod" id="voucher" value="voucher">
                            <label class="btn btn-outline-warning" for="voucher"><i class="fas fa-ticket-alt"></i> Voucher</label>
                        </div>
                        <div id="voucherValueSection" style="display:none; margin-top:10px;">
                            <label for="voucherValue" class="form-label">Voucher Value</label>
                            <input type="number" class="form-control" id="voucherValue" min="0" step="0.01" placeholder="Enter voucher value">
                            <div id="voucherSplitSection" style="display:none; margin-top:10px;">
                                <label class="form-label">Remaining Amount Payment Method</label>
                                <select class="form-select" id="secondaryPaymentMethod">
                                    <option value="cash">Cash</option>
                                    <option value="card">Card</option>
                                </select>
                                <label for="secondaryAmount" class="form-label mt-2">Amount to pay</label>
                                <input type="number" class="form-control" id="secondaryAmount" min="0" step="0.01" readonly>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="d-grid gap-2">
                        <input type="number" class="form-control mb-2" id="paidAmount" placeholder="Amount Paid by Customer" min="0" step="0.01" oninput="updateRemaining()">
                        <div id="remainingAmountDisplay" class="mb-2" style="font-weight:bold;color:#d63333;"></div>
                        <button class="btn btn-success btn-lg" onclick="processPayment()">
                            <i class="fas fa-check"></i> Complete Sale
                        </button>
                        <button class="btn btn-warning btn-lg" onclick="showHoldOrderModal()">
                            <i class="fas fa-pause"></i> Hold Order
                        </button>
                        <div class="row g-1 mb-2">
                            <div class="col-6">
                                <button class="btn btn-info btn-sm w-100" onclick="showHeldOrders()">
                                    <i class="fas fa-list"></i> View Held Orders
                                </button>
                            </div>
                            <div class="col-6">
                                <button class="btn btn-danger btn-sm w-100" onclick="clearCart()">
                                    <i class="fas fa-trash"></i> Clear Cart
                                </button>
                            </div>
                        </div>
                        <button class="btn btn-secondary" id="openRefundBtn">
                            <i class="fas fa-undo"></i> Refund / Exchange
                        </button>
                    </div>
                    <!-- Refund/Exchange Modal -->
                    <div id="refundModal" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.4);z-index:9999;">
                        <div style="background:#fff;max-width:400px;margin:60px auto;padding:24px;border-radius:8px;box-shadow:0 2px 12px #0002;position:relative;">
                            <button onclick="closeRefundModal()" style="position:absolute;top:8px;right:8px;" class="btn btn-sm btn-secondary">&times;</button>
                            <h4>Refund / Exchange</h4>
                            <input type="text" id="refundReceiptId" class="form-control mb-2" placeholder="Enter Receipt Number">
                            <button class="btn btn-primary mb-2" onclick="searchSale()">Search Sale</button>
                            <div id="refundSaleItems"></div>
                        </div>
                    </div>
                    
                    <!-- Hold Order Modal -->
                    <div id="holdOrderModal" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.4);z-index:9999;">
                        <div style="background:#fff;max-width:450px;margin:60px auto;padding:24px;border-radius:8px;box-shadow:0 2px 12px #0002;position:relative;">
                            <button onclick="closeHoldOrderModal()" style="position:absolute;top:8px;right:8px;" class="btn btn-sm btn-secondary">&times;</button>
                            <h4><i class="fas fa-pause"></i> Hold Order</h4>
                            <p class="text-muted mb-3">Enter customer details for this order</p>
                            
                            <div class="mb-3">
                                <label for="holdCustomerName" class="form-label">Customer Name</label>
                                <input type="text" class="form-control" id="holdCustomerName" placeholder="Enter customer name (optional)" maxlength="100">
                            </div>
                            
                            <div class="mb-3">
                                <label for="holdTableNumber" class="form-label">Table Number</label>
                                <input type="text" class="form-control" id="holdTableNumber" placeholder="Enter table number (optional)" maxlength="20">
                            </div>
                            
                            <div class="mb-3">
                                <label for="holdCustomerPhone" class="form-label">Phone Number</label>
                                <input type="text" class="form-control" id="holdCustomerPhone" placeholder="Enter phone number (optional)" maxlength="20">
                            </div>
                            
                            <div class="mb-4">
                                <label for="holdOrderNotes" class="form-label">Notes</label>
                                <textarea class="form-control" id="holdOrderNotes" rows="2" placeholder="Any special notes for this order (optional)"></textarea>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button class="btn btn-warning btn-lg" onclick="confirmHoldOrder()">
                                    <i class="fas fa-pause"></i> Hold This Order
                                </button>
                                <button class="btn btn-secondary" onclick="closeHoldOrderModal()">
                                    Cancel
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Held Orders Modal -->
                    <div id="heldOrdersModal" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.4);z-index:9999;">
                        <div style="background:#fff;max-width:600px;margin:30px auto;padding:24px;border-radius:8px;box-shadow:0 2px 12px #0002;position:relative;max-height:80vh;overflow-y:auto;">
                            <button onclick="closeHeldOrdersModal()" style="position:absolute;top:8px;right:8px;" class="btn btn-sm btn-secondary">&times;</button>
                            <h4><i class="fas fa-pause"></i> Held Orders</h4>
                            <div id="heldOrdersList">
                                <div class="text-center py-3">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Price Selection Modal -->
                    <div class="modal fade" id="priceSelectionModal" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title"><i class="fas fa-tags"></i> Select Price</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body text-center">
                                    <h6 id="modalProductName" class="mb-4"></h6>
                                    <p class="text-muted mb-4">This product has multiple price options. Please select one:</p>
                                    <div class="d-grid gap-3">
                                        <button type="button" class="btn btn-primary btn-lg" id="fullPriceBtn">
                                            <i class="fas fa-tag"></i> Full Price
                                        </button>
                                        <button type="button" class="btn btn-success btn-lg" id="halfPriceBtn">
                                            <i class="fas fa-percentage"></i> Half Price
                                        </button>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        var btn = document.getElementById('openRefundBtn');
                        if (btn) {
                            btn.onclick = function() {
                                document.getElementById('refundModal').style.display = 'block';
                            };
                        }
                    });
                    function closeRefundModal() {
                        document.getElementById('refundModal').style.display = 'none';
                    }
                    
                    function showHeldOrders() {
                        document.getElementById('heldOrdersModal').style.display = 'block';
                        loadHeldOrders();
                    }
                    
                    function closeHeldOrdersModal() {
                        document.getElementById('heldOrdersModal').style.display = 'none';
                    }
                    
                    function loadHeldOrders() {
                        fetch('get_held_orders.php')
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    displayHeldOrders(data.orders);
                                } else {
                                    document.getElementById('heldOrdersList').innerHTML = '<div class="alert alert-danger">Error loading held orders</div>';
                                }
                            })
                            .catch(error => {
                                document.getElementById('heldOrdersList').innerHTML = '<div class="alert alert-danger">Error loading held orders</div>';
                            });
                    }
                    
                    function displayHeldOrders(orders) {
                        var html = '';
                        if (orders.length === 0) {
                            html = '<div class="text-center py-4"><i class="fas fa-inbox fa-3x text-muted"></i><p class="text-muted mt-2">No held orders found</p></div>';
                        } else {
                            orders.forEach(function(order) {
                                html += '<div class="card mb-2">';
                                html += '<div class="card-body p-3">';
                                html += '<div class="d-flex justify-content-between align-items-start">';
                                html += '<div>';
                                html += '<h6 class="mb-1">Order #' + order.order_number + '</h6>';
                                if (order.table_number) {
                                    html += '<span class="badge bg-info text-dark me-2"><i class="fas fa-table"></i> Table ' + order.table_number + '</span>';
                                }
                                if (order.customer_name) {
                                    html += '<span class="badge bg-secondary"><i class="fas fa-user"></i> ' + order.customer_name + '</span>';
                                }
                                html += '<br><small class="text-muted">' + order.created_at + '</small>';
                                if (order.customer_phone) {
                                    html += '<br><small><i class="fas fa-phone"></i> ' + order.customer_phone + '</small>';
                                }
                                html += '</div>';
                                html += '<div class="text-end">';
                                html += '<div class="h6 text-primary">Rs ' + parseFloat(order.total_amount).toFixed(2) + '</div>';
                                html += '<button class="btn btn-sm btn-success me-1" onclick="resumeOrder(' + order.id + ')">Resume</button>';
                                html += '<button class="btn btn-sm btn-danger" onclick="cancelHeldOrder(' + order.id + ')">Cancel</button>';
                                html += '</div>';
                                html += '</div>';
                                html += '</div>';
                                html += '</div>';
                            });
                        }
                        document.getElementById('heldOrdersList').innerHTML = html;
                    }
                    
                    function showHoldOrderModal() {
                        if (cart.length === 0) {
                            alert('Cart is empty. Cannot hold an empty order.');
                            return;
                        }
                        
                        // Pre-fill with existing customer info if available
                        document.getElementById('holdCustomerName').value = document.getElementById('customerName').value || '';
                        document.getElementById('holdTableNumber').value = document.getElementById('tableNumber').value || '';
                        document.getElementById('holdCustomerPhone').value = document.getElementById('customerPhone').value || '';
                        document.getElementById('holdOrderNotes').value = '';
                        
                        document.getElementById('holdOrderModal').style.display = 'block';
                    }
                    
                    function closeHoldOrderModal() {
                        document.getElementById('holdOrderModal').style.display = 'none';
                    }
                    
                    function confirmHoldOrder() {
                        // Get values from the modal
                        var customerName = document.getElementById('holdCustomerName').value.trim();
                        var tableNumber = document.getElementById('holdTableNumber').value.trim();
                        var customerPhone = document.getElementById('holdCustomerPhone').value.trim();
                        var notes = document.getElementById('holdOrderNotes').value.trim();
                        
                        // Close the modal
                        closeHoldOrderModal();
                        
                        // Call the original hold order function with the modal data
                        holdOrderWithDetails(customerName, tableNumber, customerPhone, notes);
                    }
                    
                    function holdOrderWithDetails(customerName, tableNumber, customerPhone, notes) {
                        // Use the cart array directly instead of parsing DOM
                        if (cart.length === 0) {
                            alert('Cart is empty. Cannot hold an empty order.');
                            return;
                        }
                        
                        var cartItems = cart.map(function(item) {
                            return {
                                product_id: item.id,
                                quantity: item.quantity,
                                price: item.price,
                                total: item.total
                            };
                        });
                        
                        var orderData = {
                            items: cartItems,
                            customer_id: document.getElementById('customerSelect').value || null,
                            customer_name: customerName || null,
                            customer_phone: customerPhone || null,
                            table_number: tableNumber || null,
                            discount: parseFloat(document.getElementById('discount').value) || 0,
                            notes: notes || null
                        };
                        
                        fetch('process_hold_order.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(orderData)
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert('Order #' + data.order_number + ' has been held successfully!');
                                clearCart();
                            } else {
                                alert('Error holding order: ' + (data.message || 'Unknown error'));
                            }
                        })
                        .catch(error => {
                            alert('Error holding order: ' + error.message);
                        });
                    }
                    
                    function resumeOrder(orderId) {
                        fetch('get_held_order.php?id=' + orderId)
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    // Clear current cart
                                    clearCart();
                                    
                                    // Load the held order data
                                    var orderData = JSON.parse(data.order.order_data);
                                    
                                    // Set customer info
                                    if (data.order.customer_id) {
                                        document.getElementById('customerSelect').value = data.order.customer_id;
                                    }
                                    if (data.order.customer_name) {
                                        document.getElementById('customerName').value = data.order.customer_name;
                                    }
                                    if (data.order.customer_phone) {
                                        document.getElementById('customerPhone').value = data.order.customer_phone;
                                    }
                                    if (data.order.table_number) {
                                        document.getElementById('tableNumber').value = data.order.table_number;
                                    }
                                    
                                    // Set discount
                                    document.getElementById('discount').value = data.order.discount;
                                    
                                    // Set the current held order ID for tracking
                                    currentHeldOrderId = orderId;
                                    
                                    // Show held order indicator
                                    document.getElementById('heldOrderIndicator').style.display = 'block';
                                    
                                    // Add items to cart
                                    var itemsProcessed = 0;
                                    var totalItems = orderData.items.length;
                                    
                                    orderData.items.forEach(function(item) {
                                        // Fetch product details and add to cart
                                        fetch('get_product.php?id=' + item.product_id)
                                            .then(response => response.json())
                                            .then(productData => {
                                                if (productData.success) {
                                                    for (var i = 0; i < item.quantity; i++) {
                                                        addToCart(productData.data);
                                                    }
                                                    itemsProcessed++;
                                                    if (itemsProcessed === totalItems) {
                                                        updateTotals();
                                                    }
                                                }
                                            });
                                    });
                                    
                                    closeHeldOrdersModal();
                                    alert('Order #' + data.order.order_number + ' has been resumed!');
                                } else {
                                    alert('Error resuming order: ' + (data.message || 'Unknown error'));
                                }
                            })
                            .catch(error => {
                                alert('Error resuming order: ' + error.message);
                            });
                    }
                    
                    function cancelHeldOrder(orderId) {
                        if (confirm('Are you sure you want to cancel this held order? This action cannot be undone.')) {
                            fetch('update_held_order_status.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({id: orderId, status: 'cancelled'})
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    loadHeldOrders(); // Refresh the list
                                    alert('Order has been cancelled.');
                                } else {
                                    alert('Error cancelling order: ' + (data.message || 'Unknown error'));
                                }
                            })
                            .catch(error => {
                                alert('Error cancelling order: ' + error.message);
                            });
                        }
                    }
                    </script>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Preload products into a client-side map for instant barcode lookup -->
    <script>
        window.ALL_PRODUCTS = <?php echo json_encode($all_products, JSON_UNESCAPED_UNICODE); ?>;
        (function(){
            const clean = (s) => (String(s||''))
                .replace(/[\u00A0\u1680\u2000-\u200D\u202F\u205F\u3000]/g, '')
                .replace(/[\u0000-\u001F\u007F]/g, '')
                .trim();
            const alnum = (s) => (String(s||'')).replace(/[^A-Za-z0-9]/g, '').trim();
            const byBarcode = {};
            (window.ALL_PRODUCTS || []).forEach(p => {
                const key = clean(p.barcode);
                if (!key) return;
                if (!byBarcode[key]) byBarcode[key] = [];
                byBarcode[key].push(p);
                // also index a more permissive key (alphanumeric only) to tolerate separators in scans/db
                const k2 = alnum(key);
                if (k2 && k2 !== key) {
                    if (!byBarcode[k2]) byBarcode[k2] = [];
                    byBarcode[k2].push(p);
                }
            });
            window.PRODUCTS_BY_BARCODE = byBarcode;
        })();
    </script>
    <script src="pos.js"></script>
    <script>
    // Light styles for suggestions (kept inline to minimize file changes)
    (function(){
        const style = document.createElement('style');
        style.textContent = `
        #brandSuggestions { position: absolute; z-index: 1000; width: 100%; max-height: 250px; overflow-y: auto; display:none; }
        #brandSuggestions .suggestion-item { cursor: pointer; }
        #brandSuggestions .suggestion-item:hover { background: #f1f3f5; }
        `;
        document.head.appendChild(style);
    })();

    function updateRemaining() {
        var total = parseFloat(document.getElementById('total').textContent.replace(/[^\d.]/g, '')) || 0;
        var paid = parseFloat(document.getElementById('paidAmount').value) || 0;
        var voucherRadio = document.getElementById('voucher');
        var display = '';
        if (voucherRadio && voucherRadio.checked) {
            var voucherValue = parseFloat(document.getElementById('voucherValue').value) || 0;
            var secondaryAmount = total - voucherValue;
            if (voucherValue > 0 && voucherValue < total) {
                display = 'Remaining to be paid by ' + document.getElementById('secondaryPaymentMethod').value + ': Rs ' + secondaryAmount.toFixed(2);
            } else if (voucherValue >= total) {
                display = 'Voucher covers full amount: Rs ' + total.toFixed(2);
            } else {
                display = 'Enter voucher value.';
            }
        } else {
            var remaining = total - paid;
            if (remaining > 0) {
                display = 'Remaining to be paid: Rs ' + remaining.toFixed(2);
            } else if (remaining < 0) {
                display = 'Change to give: Rs ' + Math.abs(remaining).toFixed(2);
            } else {
                display = 'Paid in full.';
            }
        }
        document.getElementById('remainingAmountDisplay').textContent = display;
    }
    document.getElementById('paidAmount').addEventListener('input', updateRemaining);
    document.getElementById('voucherValue').addEventListener('input', updateRemaining);
    document.getElementById('secondaryPaymentMethod').addEventListener('change', updateRemaining);
    </script>
    <script>
    // Voucher logic
    function handlePaymentMethodChange() {
        var voucherSection = document.getElementById('voucherValueSection');
        var splitSection = document.getElementById('voucherSplitSection');
        var voucherRadio = document.getElementById('voucher');
        var total = parseFloat(document.getElementById('total').textContent.replace(/[^\d.]/g, '')) || 0;
        if (voucherRadio.checked) {
            voucherSection.style.display = '';
        } else {
            voucherSection.style.display = 'none';
            splitSection.style.display = 'none';
        }
    }
    document.querySelectorAll('input[name="paymentMethod"]').forEach(function(radio) {
        radio.addEventListener('change', handlePaymentMethodChange);
    });

    document.getElementById('voucherValue').addEventListener('input', function() {
        var voucherValue = parseFloat(this.value) || 0;
        var total = parseFloat(document.getElementById('total').textContent.replace(/[^\d.]/g, '')) || 0;
        var splitSection = document.getElementById('voucherSplitSection');
        var secondaryAmountInput = document.getElementById('secondaryAmount');
        if (voucherValue < total) {
            splitSection.style.display = '';
            secondaryAmountInput.value = (total - voucherValue).toFixed(2);
        } else {
            splitSection.style.display = 'none';
            secondaryAmountInput.value = '';
        }
    });

    // Update remaining for non-voucher payments
    function updateRemaining() {
        var paid = parseFloat(document.getElementById('paidAmount').value) || 0;
        var total = parseFloat(document.getElementById('total').textContent.replace(/[^\d.]/g, '')) || 0;
        var display = '';
        if (paid < total) {
            display = 'Remaining to be paid: Rs ' + (total - paid).toFixed(2);
        } else if (paid > total) {
            display = 'Change to give: Rs ' + (paid - total).toFixed(2);
        } else {
            display = 'Paid in full.';
        }
        document.getElementById('remainingAmountDisplay').textContent = display;
    }
    document.getElementById('paidAmount').addEventListener('input', updateRemaining);
    </script>
    <script>
    function updateRemaining() {
        var paid = parseFloat(document.getElementById('paidAmount').value) || 0;
        var total = parseFloat(document.getElementById('total').textContent.replace(/[^\d.]/g, '')) || 0;
        var remaining = total - paid;
        var display = '';
        if (remaining > 0) {
            display = 'Remaining to be paid: Rs ' + remaining.toFixed(2);
        } else if (remaining < 0) {
            display = 'Change to give: Rs ' + Math.abs(remaining).toFixed(2);
        } else {
            display = 'Paid in full.';
        }
        document.getElementById('remainingAmountDisplay').textContent = display;
    }
    document.getElementById('paidAmount').addEventListener('input', updateRemaining);
    </script>
<!-- Removed legacy inline barcode handler; pos.js manages scanning reliably -->
<script src="refund.js"></script>
</body>
</html>
