<?php
// modules/sales/pos.php
session_start();

// Start output buffering
ob_start();

// Include database connection
require_once "../assets/db_connect.php";

// Check if PDO connection exists
if (!isset($pdo)) {
    die("Database connection failed. Please check your db_connect.php file.");
}

// Validate session
if (!isset($_SESSION['user'])) {
    header('Location: ../../login.php');
    exit;
}

if (!isset($_SESSION['user']['shop_id']) || !isset($_SESSION['user']['id'])) {
    header('Location: ../../login.php');
    exit;
}

$shop_id = (int)$_SESSION['user']['shop_id'];
$user_id = (int)$_SESSION['user']['id'];

// Generate invoice with shop prefix
$invoice_prefix = 'SHOP' . $shop_id . '-';
$invoice_no = $invoice_prefix . date('Ymd') . '-' . rand(100, 999);

// Get active customers for dropdown
$customers = [];
try {
    $customer_stmt = $pdo->prepare("SELECT id, name, phone FROM customers WHERE shop_id = :shop_id ORDER BY name");
    $customer_stmt->execute([':shop_id' => $shop_id]);
    $customers = $customer_stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Customer query error: " . $e->getMessage());
    // Continue without customers - don't break the page
}

// Add a default walk-in customer option
array_unshift($customers, ['id' => '', 'name' => 'Walk-in Customer', 'phone' => '']);

// Now require other files
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="content-wrapper">
    <section class="content-header">
        <h1>
            Point of Sale
            <small>Sell products</small>
        </h1>
    </section>

    <section class="content">
        <div class="row">
            <!-- LEFT: CUSTOMER + SEARCH + CART -->
            <div class="col-md-8 d-flex flex-column" style="height: calc(100vh - 120px);">
                
                <!-- CUSTOMER SECTION -->
                <div class="card mb-3 flex-shrink-0">
                    <div class="card-header bg-info text-white">
                        <h3 class="card-title"><i class="fas fa-user"></i> Customer Information</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Select Customer</label>
                                    <select id="customerSelect" class="form-control">
                                        <?php foreach ($customers as $customer): ?>
                                            <option value="<?= htmlspecialchars($customer['id'] ?? '') ?>">
                                                <?= htmlspecialchars($customer['name'] ?? '') ?> 
                                                <?php if (!empty($customer['phone'])): ?>
                                                    (<?= htmlspecialchars($customer['phone']) ?>)
                                                <?php endif; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Or Add New Customer (Quick)</label>
                                    <input type="text" id="newCustomerName" 
                                           class="form-control" placeholder="Customer Name">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- PRODUCT SEARCH WITH SELECT2 -->
                <div class="card mb-3 flex-shrink-0">
                    <div class="card-header bg-primary text-white">
                        <h3 class="card-title"><i class="fas fa-search"></i> Search & Add Product</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label>Search Product</label>
                            <select id="productSearch" class="form-control" 
                                    style="width: 100%;" data-placeholder="Type product name or SKU...">
                            </select>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> Type at least 2 characters to search products
                        </div>
                    </div>
                </div>

                <!-- CART -->
                <div class="card flex-grow-1 overflow-auto">
                    <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                        <h3 class="card-title m-0"><i class="fas fa-shopping-cart"></i> Cart</h3>
                        <div>
                            <span class="badge badge-light" id="itemCount">0 items</span>
                            <button type="button" class="btn btn-sm btn-outline-light ml-2" id="clearCart">
                                <i class="fas fa-trash"></i> Clear
                            </button>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <form id="posForm">
                            <input type="hidden" name="invoice_no" value="<?= $invoice_no ?>">
                            <input type="hidden" name="shop_id" id="formShopId" value="<?= $shop_id ?>">
                            <input type="hidden" name="user_id" id="formUserId" value="<?= $user_id ?>">
                            <input type="hidden" name="customer_id" id="formCustomerId" value="">
                            
                            <table class="table table-striped table-hover mb-0">
                                <thead class="thead-light sticky-top">
                                    <tr>
                                        <th width="30%">Product</th>
                                        <th width="60">Stock</th>
                                        <th width="80">Price</th>
                                        <th width="120">Qty</th>
                                        <th width="70">VAT%</th>
                                        <th width="100">Disc%</th>
                                        <th width="120">Total</th>
                                        <th width="40"></th>
                                    </tr>
                                </thead>
                                <tbody id="cartBody">
                                    <tr id="emptyRow">
                                        <td colspan="8" class="text-center text-muted py-4">
                                            <i class="fas fa-shopping-cart fa-2x mb-2"></i><br>
                                            No items in cart<br>
                                            <small class="text-muted">Search and add products above</small>
                                        </td>
                                    </tr>
                                </tbody>
                                <tfoot class="bg-light sticky-bottom">
                                    <tr>
                                        <td colspan="5" class="text-right font-weight-bold">Subtotal:</td>
                                        <td id="subtotal" class="font-weight-bold text-right">0.00</td>
                                        <td colspan="2"></td>
                                    </tr>
                                    <tr>
                                        <td colspan="5" class="text-right font-weight-bold">VAT:</td>
                                        <td id="vatTotal" class="font-weight-bold text-right">0.00</td>
                                        <td colspan="2"></td>
                                    </tr>
                                    <tr class="table-success">
                                        <td colspan="5" class="text-right font-weight-bold">GRAND TOTAL:</td>
                                        <td id="grandTotal" class="font-weight-bold text-right">0.00</td>
                                        <td colspan="2"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </form>
                    </div>
                </div>

            </div><!-- col-md-8 -->

            <!-- RIGHT: PAYMENT PANEL -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h3 class="card-title"><i class="fas fa-credit-card"></i> Payment</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label>Total Amount</label>
                            <input type="text" id="finalTotal"
                                   class="form-control form-control-lg text-right font-weight-bold text-success"
                                   readonly value="0.00">
                        </div>

                        <div class="form-group">
                            <label>Payment Method</label>
                            <select name="payment_method" id="paymentMethod" 
                                    class="form-control form-control-lg" required>
                                <option value="CASH">Cash</option>
                                <option value="M-PESA">M-PESA</option>
                                <option value="TIGO-PESA">Tigo Pesa</option>
                                <option value="AIRTEL-MONEY">Airtel Money</option>
                                <option value="CARD">Card</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Amount Paid</label>
                            <input type="number" name="amount_paid" id="amountPaid"
                                   class="form-control form-control-lg text-right"
                                   step="0.01" min="0" value="0" required>
                        </div>

                        <div class="form-group">
                            <label>Change</label>
                            <input type="text" id="changeAmount"
                                   class="form-control form-control-lg text-right font-weight-bold text-info"
                                   readonly value="0.00">
                        </div>

                        <button type="button" id="completeSale" class="btn btn-success btn-lg btn-block">
                            <i class="fas fa-check-circle"></i> Complete Sale
                        </button>
                        
                        <div class="mt-3">
                            <div class="btn-group d-flex" role="group">
                                <button type="button" class="btn btn-warning flex-fill" id="holdSale">
                                    <i class="fas fa-pause"></i> Hold
                                </button>
                                <button type="button" class="btn btn-info flex-fill" id="printReceipt" disabled>
                                    <i class="fas fa-print"></i> Print
                                </button>
                                <button type="button" class="btn btn-secondary flex-fill" id="newSale">
                                    <i class="fas fa-plus"></i> New
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div><!-- col-md-4 -->
        </div><!-- row -->
    </section>
</div>

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

<script>
$(document).ready(function() {
    // Cart array to hold items
    const cart = [];
    let saleId = null;

    // Initialize form values
    $('#formCustomerId').val($('#customerSelect').val());

    // ==================== INITIALIZE SELECT2 ====================

    // Initialize product search with Select2 and AJAX
    $('#productSearch').select2({
        placeholder: 'Type product name or SKU...',
        allowClear: true,
        minimumInputLength: 2,
        ajax: {
            url: 'search_products_select2.php',
            type: 'GET',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term, // search term
                    page: params.page || 1,
                    shop_id: $('#formShopId').val()
                };
            },
            processResults: function(data, params) {
                params.page = params.page || 1;
                
                return {
                    results: data.items || [],
                    pagination: {
                        more: (params.page * 10) < (data.total_count || 0)
                    }
                };
            },
            cache: true
        },
        templateResult: formatProduct,
        templateSelection: formatProductSelection,
        escapeMarkup: function(markup) { return markup; }
    });

    // When a product is selected
    $('#productSearch').on('select2:select', function(e) {
        const data = e.params.data;
        console.log('Product selected:', data);
        
        // Add to cart
        const item = {
            product_id: data.product_id,
            batch_id: data.batch_id,
            product_name: data.product_name,
            batch_no: data.batch_no,
            expiry_date: data.expiry_date,
            current_qty: parseFloat(data.current_qty),
            unit_price: parseFloat(data.sell_price),
            vat_percent: parseFloat(data.vat_percent),
            qty: 1,
            discount: 0
        };

        // Check if expired
        if (item.expiry_date && item.expiry_date !== 'N/A' && new Date(item.expiry_date) < new Date()) {
            showToast('⚠️ This product has expired! Cannot add to cart.', 'warning');
            // Clear selection
            $('#productSearch').val(null).trigger('change');
            return;
        }

        // Check stock
        if (item.current_qty <= 0) {
            showToast('⚠️ This product is out of stock!', 'warning');
            $('#productSearch').val(null).trigger('change');
            return;
        }

        // Check if already in cart
        const existingIndex = cart.findIndex(c => c.batch_id === item.batch_id);
        if (existingIndex !== -1) {
            if (cart[existingIndex].qty < cart[existingIndex].current_qty) {
                cart[existingIndex].qty += 1;
                showToast(`➕ Increased quantity of ${item.product_name}`, 'success');
            } else {
                showToast(`⚠️ Cannot add more than available stock of ${item.product_name}`, 'warning');
            }
        } else {
            cart.push(item);
            showToast(`✅ Added ${item.product_name} to cart`, 'success');
        }

        renderCart();
        // Clear the selection
        $('#productSearch').val(null).trigger('change');
    });

    // Format product display in dropdown
    function formatProduct(product) {
        if (product.loading) {
            return product.text;
        }
        
        let expiryBadge = '';
        if (product.expiry_date && product.expiry_date !== 'N/A') {
            const expiryDate = new Date(product.expiry_date);
            const today = new Date();
            const daysToExpiry = Math.floor((expiryDate - today) / (1000 * 60 * 60 * 24));
            
            if (expiryDate < today) {
                expiryBadge = '<span class="badge badge-danger float-right">EXPIRED</span>';
            } else if (daysToExpiry <= 30) {
                expiryBadge = `<span class="badge badge-warning float-right">Exp in ${daysToExpiry}d</span>`;
            }
        }
        
        const stockClass = product.current_qty < 10 ? 'text-warning font-weight-bold' : 'text-success';
        
        return $(`
            <div class="d-flex justify-content-between align-items-center">
                <div style="flex: 1;">
                    <div class="font-weight-bold">${product.product_name}</div>
                    <div class="small text-muted">
                        <span>Batch: ${product.batch_no}</span>
                        <span class="mx-1">•</span>
                        <span class="${stockClass}">Stock: ${product.current_qty}</span>
                        <span class="mx-1">•</span>
                        <span class="font-weight-bold">Price: ${parseFloat(product.sell_price).toFixed(2)}</span>
                    </div>
                    ${product.expiry_date && product.expiry_date !== 'N/A' ? 
                        `<div class="small text-muted">Exp: ${product.expiry_date}</div>` : ''}
                </div>
                <div class="ml-2">
                    ${expiryBadge}
                    <div class="text-success">
                        <i class="fas fa-cart-plus"></i>
                    </div>
                </div>
            </div>
        `);
    }

    // Format selected product display
    function formatProductSelection(product) {
        if (!product.id) {
            return product.text;
        }
        return product.product_name || product.text;
    }

    // ==================== HELPER FUNCTIONS ====================

    // Show toast notification
    function showToast(message, type = 'info') {
        // Create a simple alert instead of toast for now
        const alertClass = {
            'success': 'alert-success',
            'warning': 'alert-warning',
            'error': 'alert-danger',
            'info': 'alert-info'
        }[type] || 'alert-info';
        
        const alertId = 'alert-' + Date.now();
        const alert = $(`
            <div id="${alertId}" class="alert ${alertClass} alert-dismissible fade show" style="position: fixed; top: 20px; right: 20px; z-index: 9999; max-width: 300px;">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                ${message}
            </div>
        `);
        
        $('body').append(alert);
        
        // Auto remove after 3 seconds
        setTimeout(function() {
            $('#' + alertId).alert('close');
        }, 3000);
    }

    // ==================== CART FUNCTIONS ====================

    // Render cart items
    function renderCart() {
        const $cartBody = $('#cartBody');
        $cartBody.empty();

        if (cart.length === 0) {
            $cartBody.html(`
                <tr id="emptyRow">
                    <td colspan="8" class="text-center text-muted py-4">
                        <i class="fas fa-shopping-cart fa-2x mb-2"></i><br>
                        No items in cart<br>
                        <small class="text-muted">Search and add products above</small>
                    </td>
                </tr>
            `);
            $('#itemCount').text('0 items');
            updateTotals(0, 0, 0);
            $('#printReceipt').prop('disabled', true);
            return;
        }

        $('#itemCount').text(cart.length + ' item' + (cart.length !== 1 ? 's' : ''));
        
        let subtotal = 0;
        let vatTotal = 0;
        
        cart.forEach((item, index) => {
            const lineTotal = item.qty * item.unit_price;
            const discountAmount = lineTotal * (item.discount / 100);
            const afterDiscount = lineTotal - discountAmount;
            const vatAmount = afterDiscount * (item.vat_percent / 100);
            const finalLineTotal = afterDiscount + vatAmount;
            
            subtotal += afterDiscount;
            vatTotal += vatAmount;

            const row = $(`
                <tr data-index="${index}">
                    <td>
                        <strong>${item.product_name}</strong><br>
                        <small class="text-muted">
                            Batch: ${item.batch_no}<br>
                            Stock: <span class="badge ${item.current_qty < 10 ? 'badge-warning' : 'badge-info'}">${item.current_qty}</span>
                            ${item.expiry_date && item.expiry_date !== 'N/A' ? '| Exp: ' + item.expiry_date : ''}
                        </small>
                    </td>
                    <td class="text-center">${item.current_qty}</td>
                    <td>
                        <input type="number" class="form-control form-control-sm price-input"
                               data-index="${index}" min="0" step="0.01" value="${item.unit_price.toFixed(2)}">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm qty-input text-center"
                               data-index="${index}" value="${item.qty}"
                               title="Enter quantity (max: ${item.current_qty})"
                               placeholder="Qty">
                    </td>
                    <td class="text-center">${item.vat_percent}%</td>
                    <td>
                        <input type="number" class="form-control form-control-sm discount-input"
                               data-index="${index}" min="0" max="100" step="0.01" value="${item.discount.toFixed(2)}">
                    </td>
                    <td class="font-weight-bold text-right">${finalLineTotal.toFixed(2)}</td>
                    <td class="text-center">
                        <button type="button" class="btn btn-danger btn-sm remove-item" data-index="${index}" title="Remove">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>
            `);
            
            $cartBody.append(row);
        });

        updateTotals(subtotal, vatTotal, subtotal + vatTotal);
    }

    // Update totals
    function updateTotals(subtotal, vat, grandTotal) {
        $('#subtotal').text(subtotal.toFixed(2));
        $('#vatTotal').text(vat.toFixed(2));
        $('#grandTotal').text(grandTotal.toFixed(2));
        $('#finalTotal').val(grandTotal.toFixed(2));
        
        // Calculate change
        const paid = parseFloat($('#amountPaid').val()) || 0;
        const change = paid - grandTotal;
        $('#changeAmount').val(change >= 0 ? change.toFixed(2) : '0.00');
    }

    // Reset POS for new sale
    function resetPOS() {
        // Clear cart
        cart.length = 0;
        saleId = null;
        
        // Reset form
        $('#amountPaid').val('0');
        $('#changeAmount').val('0.00');
        $('#newCustomerName').val('');
        $('#customerSelect').val('');
        $('#formCustomerId').val('');
        $('#printReceipt').prop('disabled', true);
        $('#productSearch').val(null).trigger('change');
        
        // Generate new invoice number
        const newInvoiceNo = 'SHOP' + $('#formShopId').val() + '-' + 
                           new Date().toISOString().slice(0,10).replace(/-/g, '') + '-' + 
                           Math.floor(Math.random() * 900 + 100);
        $('input[name="invoice_no"]').val(newInvoiceNo);
        
        // Render empty cart
        renderCart();
        
        // Focus on search
        $('#productSearch').select2('open');
        
        showToast('New sale started', 'info');
    }

    // Print receipt
    function printReceipt(saleId) {
        window.open(`print_receipt.php?sale_id=${saleId}`, '_blank');
    }

    // ==================== EVENT HANDLERS ====================

    // Customer selection
    $('#customerSelect').on('change', function() {
        $('#formCustomerId').val($(this).val());
        $('#newCustomerName').val('');
    });

    // New customer name input
    $('#newCustomerName').on('input', function() {
        const name = $(this).val().trim();
        if (name.length > 0) {
            $('#customerSelect').val('');
            $('#formCustomerId').val('');
        }
    });

    // Calculate change when amount paid changes
    $('#amountPaid').on('input', function() {
        const grandTotal = parseFloat($('#grandTotal').text()) || 0;
        const paid = parseFloat($(this).val()) || 0;
        const change = paid - grandTotal;
        $('#changeAmount').val(change >= 0 ? change.toFixed(2) : '0.00');
    });

    // Quantity input handler
    $(document).on('input change blur', '.qty-input', function() {
        const index = $(this).data('index');
        let val = parseFloat($(this).val());
        
        // Handle empty or invalid values
        if (isNaN(val) || val <= 0) {
            val = 1;
            $(this).val('1');
            showToast(`Quantity set to 1 for ${cart[index].product_name}`, 'info');
        }
        
        // Check if exceeds stock
        if (val > cart[index].current_qty) {
            val = cart[index].current_qty;
            $(this).val(cart[index].current_qty);
            showToast(`⚠️ Quantity limited to available stock (${cart[index].current_qty}) for ${cart[index].product_name}`, 'warning');
        }
        
        // Allow decimal quantities for certain products (e.g., 0.5 kg)
        cart[index].qty = val;
        renderCart();
    });

    // Keyboard shortcuts for quantity
    $(document).on('keydown', '.qty-input', function(e) {
        const index = $(this).data('index');
        
        if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (cart[index].qty < cart[index].current_qty) {
                cart[index].qty += 1;
                $(this).val(cart[index].qty);
                renderCart();
            }
        } else if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (cart[index].qty > 1) {
                cart[index].qty -= 1;
                $(this).val(cart[index].qty);
                renderCart();
            }
        } else if (e.key === 'Escape') {
            $(this).val(cart[index].qty); // Reset to original value
            $(this).blur();
        } else if (e.key === 'Enter') {
            $(this).blur();
        }
    });

    // Price input handler
    $(document).on('input', '.price-input', function() {
        const index = $(this).data('index');
        const val = parseFloat($(this).val()) || 0;
        if (val >= 0) {
            cart[index].unit_price = val;
            renderCart();
            showToast(`💰 Updated price for ${cart[index].product_name}`, 'info');
        }
    });

    // Discount input handler
    $(document).on('input', '.discount-input', function() {
        const index = $(this).data('index');
        let val = parseFloat($(this).val()) || 0;
        if (val < 0) val = 0;
        if (val > 100) {
            val = 100;
            showToast(`⚠️ Discount cannot exceed 100% for ${cart[index].product_name}`, 'warning');
        }
        cart[index].discount = val;
        renderCart();
    });

    // Remove item from cart
    $(document).on('click', '.remove-item', function() {
        const index = $(this).data('index');
        const productName = cart[index].product_name;
        cart.splice(index, 1);
        renderCart();
        showToast(`🗑️ Removed ${productName} from cart`, 'info');
    });

    // Clear cart
    $('#clearCart').on('click', function() {
        if (cart.length > 0) {
            Swal.fire({
                title: 'Clear Cart?',
                text: 'This will remove all items from the cart.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, clear cart',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    cart.length = 0;
                    renderCart();
                    showToast('🛒 Cart cleared', 'info');
                }
            });
        }
    });

    // New sale button
    $('#newSale').on('click', function() {
        if (cart.length > 0) {
            Swal.fire({
                title: 'Start New Sale?',
                text: 'This will clear the current cart.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, start new sale'
            }).then((result) => {
                if (result.isConfirmed) {
                    resetPOS();
                }
            });
        } else {
            resetPOS();
        }
    });

    // Hold sale
    $('#holdSale').on('click', function() {
        if (cart.length === 0) {
            showToast('No items to hold', 'warning');
            return;
        }

        const holdData = {
            cart: cart,
            customer_id: $('#formCustomerId').val(),
            timestamp: new Date().toISOString()
        };

        localStorage.setItem('heldSale', JSON.stringify(holdData));
        
        Swal.fire({
            icon: 'info',
            title: 'Sale Held',
            text: 'Cart has been saved. You can retrieve it later.',
            timer: 2000,
            showConfirmButton: false
        });
        
        cart.length = 0;
        renderCart();
    });

    // Print receipt
    $('#printReceipt').on('click', function() {
        if (saleId) {
            printReceipt(saleId);
        }
    });

    // Complete sale
    $('#completeSale').on('click', function() {
        if (cart.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Empty Cart',
                text: 'Please add items to cart before completing sale.',
                timer: 2000
            });
            return;
        }

        const grandTotal = parseFloat($('#grandTotal').text());
        const amountPaid = parseFloat($('#amountPaid').val()) || 0;
        const paymentMethod = $('#paymentMethod').val();
        const customerId = $('#formCustomerId').val();
        const newCustomerName = $('#newCustomerName').val().trim();

        // Validate payment
        if (amountPaid <= 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Payment Required',
                text: 'Please enter payment amount.',
                timer: 2000
            });
            $('#amountPaid').focus();
            return;
        }

        if (amountPaid < grandTotal) {
            Swal.fire({
                title: 'Insufficient Payment',
                html: `Total: <strong>${grandTotal.toFixed(2)}</strong><br>
                       Paid: <strong>${amountPaid.toFixed(2)}</strong><br>
                       Balance: <strong class="text-danger">${(grandTotal - amountPaid).toFixed(2)}</strong>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Complete as Partial Payment',
                cancelButtonText: 'Enter Full Payment'
            }).then((result) => {
                if (!result.isConfirmed) {
                    $('#amountPaid').focus().select();
                } else {
                    processSale();
                }
            });
            return;
        }

        processSale();

        function processSale() {
            const saleData = {
                invoice_no: $('input[name="invoice_no"]').val(),
                shop_id: $('input[name="shop_id"]').val(),
                user_id: $('input[name="user_id"]').val(),
                customer_id: customerId,
                new_customer_name: newCustomerName,
                cart: cart,
                payment_method: paymentMethod,
                amount_paid: amountPaid,
                total: grandTotal
            };

            Swal.fire({
                title: 'Confirm Sale',
                html: `<div class="text-left">
                          <p><strong>Items:</strong> ${cart.length}</p>
                          <p><strong>Total:</strong> ${grandTotal.toFixed(2)}</p>
                          <p><strong>Paid:</strong> ${amountPaid.toFixed(2)}</p>
                          <p><strong>Change:</strong> ${(amountPaid - grandTotal).toFixed(2)}</p>
                       </div>`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Complete Sale',
                cancelButtonText: 'Review',
                showLoaderOnConfirm: true,
                preConfirm: () => {
                    return $.ajax({
                        url: 'save_sale.php',
                        method: 'POST',
                        data: saleData,
                        dataType: 'json'
                    }).fail(error => {
                        Swal.showValidationMessage(`Request failed: ${error.responseText}`);
                    });
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const response = result.value;
                    if (response.success) {
                        saleId = response.sale_id;
                        Swal.fire({
                            icon: 'success',
                            title: 'Sale Completed!',
                            html: `Invoice: <strong>${response.invoice_no}</strong><br>
                                   Total: <strong>${response.total}</strong><br>
                                   Paid: <strong>${response.paid}</strong>`,
                            showConfirmButton: true,
                            showCancelButton: true,
                            confirmButtonText: 'Print Receipt',
                            cancelButtonText: 'New Sale'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                printReceipt(response.sale_id);
                            } else {
                                resetPOS();
                            }
                        });
                        $('#printReceipt').prop('disabled', false);
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message || 'Could not save sale.'
                        });
                    }
                }
            });
        }
    });

    // Check for held sale on page load
    const heldSale = localStorage.getItem('heldSale');
    if (heldSale) {
        Swal.fire({
            title: 'Restore Held Sale?',
            text: 'You have an unsaved cart from a previous session.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Restore',
            cancelButtonText: 'Discard'
        }).then((result) => {
            if (result.isConfirmed) {
                try {
                    const restored = JSON.parse(heldSale);
                    cart.push(...restored.cart);
                    if (restored.customer_id) {
                        $('#customerSelect').val(restored.customer_id);
                        $('#formCustomerId').val(restored.customer_id);
                    }
                    renderCart();
                    showToast('Held sale restored', 'success');
                } catch (e) {
                    console.error('Error restoring held sale:', e);
                    showToast('Error restoring held sale', 'error');
                }
            }

            localStorage.removeItem('heldSale');
        });
    }

    // Initialize Bootstrap tooltips
    $('[title]').tooltip();
    
    // Focus on search input on page load
    setTimeout(() => {
        $('#productSearch').select2('open');
    }, 500);
});
</script>

<style>
.price-input, .discount-input, .qty-input {
    text-align: center;
}

.qty-input {
    width: 80px;
    display: inline-block;
    transition: all 0.3s;
}

.qty-input:focus {
    border-color: #80bdff;
    box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
    transform: scale(1.05);
}

/* Remove spinner buttons for number input in some browsers */
.qty-input::-webkit-inner-spin-button,
.qty-input::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.qty-input {
    -moz-appearance: textfield;
}

.remove-item {
    padding: 2px 6px;
}

.sticky-top {
    position: sticky;
    top: 0;
    background: white;
    z-index: 10;
}

.sticky-bottom {
    position: sticky;
    bottom: 0;
    background: white;
    z-index: 10;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

.table tfoot tr:last-child td {
    border-bottom: 2px solid #28a745;
}

/* Select2 custom styling */
.select2-container--default .select2-selection--single {
    height: calc(2.875rem + 2px) !important;
    padding: 0.5rem 0.75rem !important;
    font-size: 1.125rem !important;
    border: 1px solid #ced4da !important;
    border-radius: 0.25rem !important;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: calc(2.875rem + 2px) !important;
}

.select2-results__option {
    padding: 8px 12px !important;
}

.select2-results__option--highlighted {
    background-color: #f8f9fa !important;
    color: #495057 !important;
}

.select2-dropdown {
    border: 1px solid #dee2e6 !important;
    border-radius: 0.25rem !important;
    box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15) !important;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .qty-input {
        width: 60px;
    }
    
    .sticky-top, .sticky-bottom {
        position: static;
    }
}
</style>