<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    header('location:../login.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Get customer details if customer_id is provided
$selectedCustomer = null;
if (isset($_GET['customer_id'])) {
    $customerId = intval($_GET['customer_id']);
    $customerQuery = "SELECT * FROM tblcustomers WHERE ID = $customerId";
    $customerResult = mysqli_query($con, $customerQuery);
    if (mysqli_num_rows($customerResult) > 0) {
        $selectedCustomer = mysqli_fetch_assoc($customerResult);
    }
}

// Get customers for dropdown
$customersQuery = "SELECT ID, CustomerCode, CustomerName, Mobile, CurrentBalance, LoyaltyPoints, GSTNumber FROM tblcustomers WHERE IsActive = 1 ORDER BY CustomerName";
$customersResult = mysqli_query($con, $customersQuery);

// Get sales types
$salesTypesQuery = "SELECT SalesType, InvoicePrefix, Description FROM tblsales_type_config WHERE IsActive = 1 ORDER BY ID";
$salesTypesResult = mysqli_query($con, $salesTypesQuery);

// Default sales type
$defaultSalesType = 'GST';
$defaultPrefix = 'GST';

// Auto-generate invoice number with financial year format: GST/2025-26/0001
// Financial year: April to March
$currentMonth = date('n'); // 1-12
$currentYear = date('Y');
if ($currentMonth >= 4) {
    // April onwards - current year to next year
    $financialYear = $currentYear . '-' . substr($currentYear + 1, 2);
} else {
    // January to March - previous year to current year
    $financialYear = ($currentYear - 1) . '-' . substr($currentYear, 2);
}

$invoicePrefix = $defaultPrefix . '/' . $financialYear . '/';
$lastInvoiceQuery = "SELECT InvoiceNumber FROM tblsales WHERE InvoiceNumber LIKE '$invoicePrefix%' ORDER BY ID DESC LIMIT 1";
$lastInvoiceResult = mysqli_query($con, $lastInvoiceQuery);
if (mysqli_num_rows($lastInvoiceResult) > 0) {
    $lastInvoice = mysqli_fetch_assoc($lastInvoiceResult)['InvoiceNumber'];
    $lastNumber = intval(substr($lastInvoice, -4));
    $newNumber = $lastNumber + 1;
} else {
    $newNumber = 1;
}
$invoiceNumber = $invoicePrefix . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>POS - Sales</title>
    
    <!-- Custom fonts -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,300,400,600,700,800,900" rel="stylesheet">
    
    <!-- Custom styles -->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/quick-menu.css" rel="stylesheet">
    <link href="../css/modern-sidebar.css" rel="stylesheet">
    <link href="css/sales.css" rel="stylesheet">
    <link href="css/mobile-cart.css" rel="stylesheet">
    <link href="css/barcode-scanner.css" rel="stylesheet">
    <link href="css/keyboard-shortcuts.css" rel="stylesheet">
    <link href="css/payment-modal.css" rel="stylesheet">
    <link href="css/modern-messagebox.css" rel="stylesheet">
    
    <!-- html5-qrcode for QR and barcode scanning -->
    <script src="https://unpkg.com/html5-qrcode"></script>
</head>

<body id="page-top">
    <div id="wrapper">
        <div id="content-wrapper" class="d-flex flex-column" style="margin-left: 0;">
            <div id="content">
                <!-- Header Bar - Compact & Mobile Responsive -->
                <div class="pos-header-compact">
                    <div class="container-fluid px-2 py-1">
                        <!-- Row 1: Title + Quick Actions Buttons -->
                        <div class="d-flex justify-content-between align-items-center mb-1">
                           
                            <div class="d-flex align-items-center flex-wrap" style="gap: 3px;">
                                <a href="../dashboard.php" class="btn btn-sm btn-dark px-2 py-1" title="Go to Dashboard">
                                    <i class="fas fa-home"></i>
                                    <span class="d-none d-lg-inline ml-1">Home</span>
                                </a>
                                <button type="button" class="btn btn-sm btn-primary px-2 py-1" id="btnHoldBillHeader" title="Hold Bill">
                                    <i class="fas fa-pause-circle"></i>
                                    <span class="d-none d-lg-inline ml-1">Hold</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-info px-2 py-1" id="btnViewHoldBillsHeader" title="View Hold Bills">
                                    <i class="fas fa-list"></i>
                                    <span class="d-none d-lg-inline ml-1">View Hold Bills</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-warning px-2 py-1" id="clearCartHeader" title="Clear Cart">
                                    <i class="fas fa-eraser"></i>
                                    <span class="d-none d-lg-inline ml-1">Clear</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-secondary px-2 py-1" id="newSaleHeader" title="New Sale">
                                    <i class="fas fa-file"></i>
                                    <span class="d-none d-lg-inline ml-1">New Sale</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-success px-2 py-1" id="btnGSTDetailsHeader" title="GST Details">
                                    <i class="fas fa-file-invoice-dollar"></i>
                                    <span class="d-none d-lg-inline ml-1">GST</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-primary px-2 py-1" id="btnShippingDetailsHeader" title="Shipping">
                                    <i class="fas fa-shipping-fast"></i>
                                    <span class="d-none d-lg-inline ml-1">Shipping</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-warning px-2 py-1" id="btnPreviousHeader" title="Previous Bill">
                                    <i class="fas fa-arrow-left"></i>
                                    <span class="d-none d-lg-inline ml-1">Previous Bill</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-warning px-2 py-1" id="btnNextHeader" title="Next Bill">
                                    <i class="fas fa-arrow-right"></i>
                                    <span class="d-none d-lg-inline ml-1">Next Bill</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-danger px-2 py-1" id="btnDeleteBillHeader" title="Delete Bill">
                                    <i class="fas fa-trash"></i>
                                    <span class="d-none d-lg-inline ml-1">Delete Bill</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-danger px-2 py-1" id="btnExpensesHeader" title="Expenses">
                                    <i class="fas fa-money-bill-wave"></i>
                                    <span class="d-none d-lg-inline ml-1">Expenses</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-secondary px-2 py-1" id="btnLoyaltySettingsHeader" title="Loyalty Settings">
                                    <i class="fas fa-cog"></i>
                                    <span class="d-none d-lg-inline ml-1">Loyalty</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-info px-2 py-1" id="btnToggleLanguageHeader" title="Toggle Language" onclick="toggleLanguage()">
                                    <i class="fas fa-language"></i>
                                    <span class="d-none d-lg-inline ml-1">த</span>
                                </button>
                                <span class="badge badge-light px-2 py-1 ml-1" style="font-size: 11px;">
                                    <i class="fas fa-file-invoice"></i> <span id="currentInvoiceNumber"><?php echo $invoiceNumber; ?></span>
                                </span>
                                <span class="badge badge-success px-2 py-1" style="font-size: 11px;">
                                    <i class="fas fa-calendar"></i> <?php echo date('d-M-Y'); ?>
                                </span>
                            </div>
                        </div>
                        
                        <!-- Row 2: Sales Type + Customer Search -->
                        <div class="row mb-1">
                            <div class="col-md-2 col-6 pr-1 mb-1">
                                <select id="salesType" class="form-control form-control-sm compact-select">
                                    <?php 
                                    mysqli_data_seek($salesTypesResult, 0);
                                    while ($salesType = mysqli_fetch_assoc($salesTypesResult)): 
                                    ?>
                                        <option value="<?php echo $salesType['SalesType']; ?>" 
                                                data-prefix="<?php echo $salesType['InvoicePrefix']; ?>">
                                            <?php echo $salesType['Description']; ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2 col-6 pl-1 pr-md-1 mb-1">
                                <div class="custom-control custom-switch" style="padding-top: 8px;">
                                    <input type="checkbox" class="custom-control-input" id="barcodeScanMode" checked>
                                    <label class="custom-control-label" for="barcodeScanMode" style="font-size: 12px; font-weight: 600; cursor: pointer;">
                                        <i class="fas fa-barcode text-primary"></i> <span data-translate="autoScan">Auto Scan</span>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-4 col-12 pl-md-1 mb-1" style="position: relative;">
                                <div class="input-group input-group-sm">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; border-radius: 4px 0 0 4px;">
                                            <i class="fas fa-search" style="color: #ffffff; font-size: 14px;"></i>
                                        </span>
                                    </div>
                                    <input type="text" id="customerSearch" class="form-control form-control-sm" 
                                           placeholder="Search Customer Name / Mobile Number" 
                                           data-translate="searchPlaceholder"
                                           autocomplete="off"
                                           style="border-left: none; padding-left: 8px; border-radius: 0 4px 4px 0;">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-sm btn-success px-2" id="btnAddCustomer" data-translate-title="newCustomer" title="New Customer">
                                            <i class="fas fa-plus"></i>
                                            <span class="d-none d-xl-inline ml-1">New</span>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-primary px-2" id="btnRegisterPayment" data-translate-title="registerPayment" title="Register Payment">
                                            <i class="fas fa-money-bill-wave"></i>
                                            <span class="d-none d-xl-inline ml-1">Customer Payments</span>
                                        </button>
                                    </div>
                                </div>
                                <select id="customerSelect" class="form-control form-control-sm" style="display:none;">
                                    <option value="" data-translate="selectCustomer">Select Customer</option>
                                    <?php 
                                    mysqli_data_seek($customersResult, 0);
                                    while ($customer = mysqli_fetch_assoc($customersResult)): 
                                    ?>
                                        <option value="<?php echo $customer['ID']; ?>" 
                                                data-balance="<?php echo $customer['CurrentBalance']; ?>"
                                                data-loyalty="<?php echo $customer['LoyaltyPoints']; ?>"
                                                data-name="<?php echo htmlspecialchars($customer['CustomerName']); ?>"
                                                data-code="<?php echo htmlspecialchars($customer['CustomerCode']); ?>"
                                                data-phone="<?php echo htmlspecialchars($customer['Mobile']); ?>"
                                                data-gst="<?php echo htmlspecialchars($customer['GSTNumber'] ?? ''); ?>"
                                                <?php echo ($selectedCustomer && $selectedCustomer['ID'] == $customer['ID']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($customer['CustomerCode'] . ' - ' . $customer['CustomerName']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                                <div id="customerSuggestions" class="suggestions-box"></div>
                            </div>
                            <div class="col-md-4 col-12">
                                <!-- Empty space for future use -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Main POS Area -->
                <div class="container-fluid pos-container">
                    <div class="row">
                        <!-- Left Side - Product Entry & Cart -->
                        <div class="col-md-8 pos-left-section">
                            <!-- Product Entry -->
                            <div class="card shadow-sm mb-3">
                                <div class="card-header bg-primary text-white py-2 d-flex justify-content-between align-items-center">
                                    <h6 class="mb-0"><i class="fas fa-keyboard"></i> <span data-translate="productEntry">Product Entry</span></h6>
                                    <!-- Price Type Dropdown -->
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-light dropdown-toggle" type="button" id="priceTypeDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" title="Select Price Type">
                                            <i class="fas fa-tags"></i> <span id="selectedPriceLabel">Sales</span>
                                        </button>
                                        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="priceTypeDropdown">
                                            <a class="dropdown-item active" href="#" data-price-type="SalesPrice">
                                                <i class="fas fa-tag text-info"></i> <span data-translate="salesPrice">Sales Price</span>
                                            </a>
                                            <a class="dropdown-item" href="#" data-price-type="ShopRate">
                                                <i class="fas fa-store text-success"></i> <span data-translate="shopRate">Shop Rate</span>
                                            </a>
                                            <a class="dropdown-item" href="#" data-price-type="WholesaleRate">
                                                <i class="fas fa-warehouse text-warning"></i> <span data-translate="wholesaleRate">Wholesale Rate</span>
                                            </a>
                                            <a class="dropdown-item" href="#" data-price-type="MRP">
                                                <i class="fas fa-rupee-sign text-danger"></i> <span data-translate="mrp">MRP</span>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body p-2">
                                    <!-- Product Entry Form - Ultra Compact 3 Lines -->
                                    <div class="entry-form">
                                        <input type="hidden" id="productId">
                                        <input type="hidden" id="selectedPriceType" value="SalesPrice">
                                        <input type="hidden" id="availablePrices" value="">
                                        
                                        <!-- Line 1: Code with Camera Button (Mobile: Full width, Desktop: 50%) -->
                                        <div class="form-row mb-2">
                                            <div class="col-12 col-md-6 pr-md-1 mb-2 mb-md-0" style="position: relative;">
                                                <div class="input-group input-group-sm">
                                                    <input type="text" id="productCode" class="form-control text-uppercase" 
                                                           placeholder="Search Product" data-translate="codePlaceholder" autocomplete="off" autofocus style="font-weight: 600; font-size: 14px; height: 34px;">
                                                </div>
                                                <div id="productSuggestions" class="suggestions-box"></div>
                                            </div>
                                            <!-- Price, Qty, Add Button - Desktop only visible -->
                                            <div class="col-2 px-1 d-none d-md-block">
                                                <input type="number" id="rate" class="form-control form-control-sm" 
                                                       placeholder="Price" data-translate="pricePlaceholder" step="0.01" min="0" style="font-size: 13px; height: 34px;">
                                            </div>
                                            <div class="col-2 px-1 d-none d-md-block">
                                                <input type="number" id="quantity" class="form-control form-control-sm" 
                                                       placeholder="Qty" data-translate="qtyPlaceholder" step="0.01" min="0.01" style="font-size: 13px; height: 34px;">
                                            </div>
                                            <div class="col-2 pl-1 d-none d-md-block">
                                                <button type="button" id="addToCart" class="btn btn-success btn-sm btn-block" style="padding: 0.35rem 0.3rem; font-size: 13px; height: 34px;">
                                                    <i class="fas fa-plus"></i> <span data-translate="addButton">Add</span>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <!-- Line 2: Price, Qty, Add Button - Mobile only -->
                                        <div class="form-row mb-2 d-md-none">
                                            <div class="col-4 pr-1">
                                                <input type="number" id="rateMobile" class="form-control form-control-sm" 
                                                       placeholder="Price" data-translate="pricePlaceholder" step="0.01" min="0" style="font-size: 13px; height: 34px;">
                                            </div>
                                            <div class="col-4 px-1">
                                                <input type="number" id="quantityMobile" class="form-control form-control-sm" 
                                                       placeholder="Qty" data-translate="qtyPlaceholder" step="0.01" min="0.01" style="font-size: 13px; height: 34px;">
                                            </div>
                                            <div class="col-4 pl-1">
                                                <button type="button" id="addToCartMobile" class="btn btn-success btn-sm btn-block" style="padding: 0.35rem 0.3rem; font-size: 13px; height: 34px;">
                                                    <i class="fas fa-plus"></i> <span data-translate="addButton">Add</span>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <!-- Line 3: Product Name and Total -->
                                        <div class="form-row mb-2">
                                            <div class="col-8">
                                                <div style="background: #f8f9fa; padding: 0.3rem 0.5rem; border-radius: 3px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                                    <span class="text-muted" style="font-size: 10px;" data-translate="productName">Product</span>: 
                                                    <span id="productName" class="font-weight-bold text-primary">-</span>
                                                </div>
                                            </div>
                                            <div class="col-4">
                                                <div style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); padding: 0.3rem 0.5rem; border-radius: 3px; text-align: center;">
                                                    <span style="font-size: 10px; color: #155724;" data-translate="total">Total</span>: 
                                                    <strong id="currentItemTotal" style="font-size: 13px; color: #155724;">₹0.00</strong>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Customer Balance Display -->
                                    <div class="mt-2 p-2 bg-warning rounded" id="customerBalanceDisplay" style="display:none;">
                                        <div class="row">
                                            <div class="col-6 text-center border-right">
                                                <strong data-translate="customerBalance">Balance:</strong> 
                                                <span id="customerBalance" class="text-danger font-weight-bold d-block">₹0.00</span>
                                            </div>
                                            <div class="col-6 text-center">
                                                <strong data-translate="loyaltyPoints">Points:</strong> 
                                                <span id="customerLoyalty" class="text-success font-weight-bold d-block">
                                                    <i class="fas fa-star"></i> 0
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Cart Items Table -->
                                    <div class="mt-3">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <h6 class="text-success mb-0">
                                                <i class="fas fa-shopping-cart"></i> <span data-translate="products">Products</span>
                                            </h6>
                                            <h6 class="mb-0 text-primary font-weight-bold">
                                                <span data-translate="billAmount">Bill Amount:</span> 
                                                <span id="grandTotalCart" style="color: #155724;">₹0.00</span>
                                            </h6>
                                        </div>
                                        
                                        <!-- Desktop Table View -->
                                        <div class="table-responsive cart-table-container" style="max-height: 500px; overflow-y: auto;">
                                            <table class="table table-sm table-hover mb-0" id="cartTable">
                                                <thead class="thead-light">
                                                    <tr>
                                                        <th width="3%" data-translate="sNo">#</th>
                                                        <th width="10%" data-translate="code">Code</th>
                                                        <th width="22%" data-translate="product">Product</th>
                                                        <th width="10%" class="text-right" data-translate="basicRate">Basic</th>
                                                        <th width="12%" class="text-right" data-translate="price">Price</th>
                                                        <th width="10%" class="text-right" data-translate="quantity">Qty</th>
                                                        <th width="10%" class="text-right" data-translate="disc">Disc</th>
                                                        <th width="13%" class="text-right" data-translate="total">Total</th>
                                                        <th width="6%" class="text-center" data-translate="action">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="cartItems">
                                                    <tr class="empty-cart">
                                                        <td colspan="9" class="text-center text-muted py-4">
                                                            <i class="fas fa-shopping-cart fa-3x mb-2"></i>
                                                            <p data-translate="emptyCart">Cart is Empty</p>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                        
                                        <!-- Mobile Card View -->
                                        <div class="cart-cards-container" id="cartCards" style="display: none; max-height: 400px; overflow-y: auto;">
                                            <div class="text-center text-muted py-4 empty-cart-cards">
                                                <i class="fas fa-shopping-cart fa-3x mb-2"></i>
                                                <p data-translate="emptyCart">Cart is Empty</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Side - Payment Summary -->
                        <div class="col-md-4 pos-summary-section">

                            <!-- Totals & Payment Summary -->
                            <div class="card shadow">
                                <div class="card-body p-2">
                                    <!-- Mobile Toggle Button (Hidden on Desktop) -->
                                    <button type="button" class="mobile-details-toggle" id="mobileDetailsToggle">
                                        <span data-translate="showDetails">Show Details</span>
                                        <i class="fas fa-chevron-down"></i>
                                    </button>
                                    
                                    <!-- Mobile Totals Wrapper -->
                                    <div class="mobile-totals-wrapper">
                                        <!-- Content that will be hidden on mobile -->
                                        <div class="mobile-totals-content" id="mobileTotalsContent">
                                            <!-- Row 1: Cash + UPI + Credit -->
                                            <div class="row mb-2 no-gutters">
                                                <div class="col-4 pr-1">
                                                    <label class="mb-1 small font-weight-bold text-success" style="font-size: 13px;">
                                                        <i class="fas fa-money-bill-wave"></i> <span data-translate="cash">Cash</span> <kbd class="kbd-hint">F7</kbd>
                                                    </label>
                                                    <input type="number" id="cashAmount" class="form-control form-control-sm text-right font-weight-bold" 
                                                           value="0.00" step="0.01" min="0" placeholder="0.00" style="font-size: 16px; height: 38px; padding: 8px;">
                                                </div>
                                                <div class="col-4 px-1">
                                                    <label class="mb-1 small font-weight-bold text-primary" style="font-size: 13px;">
                                                        <i class="fas fa-mobile-alt"></i> <span data-translate="upi">UPI</span> <kbd class="kbd-hint">F8</kbd>
                                                    </label>
                                                    <input type="number" id="upiAmount" class="form-control form-control-sm text-right font-weight-bold" 
                                                           value="0.00" step="0.01" min="0" placeholder="0.00" style="font-size: 16px; height: 38px; padding: 8px;">
                                                </div>
                                                <div class="col-4 pl-1">
                                                    <label class="mb-1 small font-weight-bold text-danger" style="font-size: 13px;">
                                                        <i class="fas fa-credit-card"></i> <span data-translate="credit">Credit</span>
                                                    </label>
                                                    <input type="number" id="creditAmount" class="form-control form-control-sm text-right font-weight-bold" 
                                                           value="0.00" step="0.01" min="0" placeholder="0.00" style="font-size: 16px; height: 38px; padding: 8px;">
                                                </div>
                                            </div>

                                            <!-- Change/Balance Amount Display -->
                                            <div class="row mb-2 no-gutters" id="changeAmountDisplay" style="display: none;">
                                                <div class="col-12">
                                                    <div class="alert alert-success mb-0 py-2 px-3" style="border-left: 4px solid #28a745;">
                                                        <div class="d-flex justify-content-between align-items-center">
                                                            <strong style="font-size: 13px;">
                                                                <i class="fas fa-hand-holding-usd"></i> <span data-translate="changeReturn">Change to Return:</span>
                                                            </strong>
                                                            <strong id="changeAmount" style="font-size: 16px; color: #155724;">₹0.00</strong>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                    <div class="ultra-compact-totals">
                                        <!-- Sub Total -->
                                        <div class="uc-row">
                                            <span class="uc-label" data-translate="subTotal">Sub Total:</span>
                                            <span class="uc-value" id="subTotal">₹0.00</span>
                                        </div>

                                        <!-- GST Type -->
                                        <div class="uc-row uc-gst">
                                            <span class="uc-label" data-translate="gstType">gstType</span>
                                            <div class="uc-inline-group">
                                                <div class="btn-group btn-group-sm uc-toggle" role="group">
                                                    <button type="button" class="btn uc-btn active" id="btnGSTInclusive" data-type="inclusive" title="Tax Included">
                                                        <i class="fas fa-check-circle"></i> <span data-translate="inclusive">incl</span>
                                                    </button>
                                                    <button type="button" class="btn uc-btn" id="btnGSTExclusive" data-type="exclusive" title="Tax Added">
                                                        <i class="fas fa-plus-circle"></i> <span data-translate="exclusive">excl</span>
                                                    </button>
                                                </div>
                                                <small class="uc-hint" id="gstTypeDescription" data-translate="gstInclusiveDesc">Tax Included</small>
                                            </div>
                                        </div>

                                        <!-- Bill Discount -->
                                        <div class="uc-row uc-discount">
                                            <span class="uc-label" data-translate="billDiscount">Bill Discount:</span>
                                            <div class="uc-inline-group">
                                                <div class="btn-group btn-group-sm uc-toggle-mini" role="group">
                                                    <button type="button" class="btn uc-btn-xs" id="billDiscPercent" data-type="PERCENTAGE">%</button>
                                                    <button type="button" class="btn uc-btn-xs" id="billDiscAmount" data-type="AMOUNT">₹</button>
                                                    <button type="button" class="btn uc-btn-xs" id="billDiscPoints" data-type="POINTS" title="Redeem Points" data-translate-title="redeemPoints">⭐</button>
                                                </div>
                                                <input type="number" id="billDiscount" class="uc-input" placeholder="0" step="0.01" min="0" value="0">
                                                <small id="billDiscountValue" class="uc-disc-val">-₹0.00</small>
                                                <input type="hidden" id="billDiscountType" value="PERCENTAGE">
                                                <input type="hidden" id="redeemedPoints" value="0">
                                            </div>
                                        </div>

                                        <!-- Transport -->
                                        <div class="uc-row">
                                            <span class="uc-label" data-translate="cooliLabel">Transport amt:</span>
                                            <span class="uc-value text-info" id="cooliDisplay">₹0.00</span>
                                        </div>

                                        <!-- Round Off -->
                                        <div class="uc-row">
                                            <span class="uc-label" data-translate="roundOff">Round Off:</span>
                                            <span class="uc-value text-warning" id="roundOffDisplay">+₹0.00</span>
                                        </div>
                                        </div>
                                        <!-- End of mobile-totals-content -->
                                        </div>
                                        <!-- End of mobile-totals-wrapper -->

                                        <!-- Save Button (Always Visible) -->
                                        <button type="button" id="saveSale" class="uc-btn-save" disabled>
                                            <i class="fas fa-save"></i> <span data-translate="saveAndPrint">Save & Print (F10)</span>
                                        </button>
                                        
                                        <input type="hidden" id="editingSaleId" value="">
                                        <input type="hidden" id="isEditMode" value="0">
                                    </div>
                                </div>
                            </div>

                            <!-- Bill Amount Only -->
                            <div class="card shadow">
                                <div class="card-body p-3">
                                    <div class="uc-row uc-major" style="border: 2px solid #28a745; border-radius: 5px; padding: 15px; background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);">
                                        <span class="uc-label-bold" style="font-size: 18px;" data-translate="billAmount">Bill Amount:</span>
                                        <span class="uc-value-large" id="grandTotal" style="font-size: 24px; color: #155724;">₹0.00</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Loyalty Settings Modal -->
    <div class="modal fade" id="loyaltySettingsModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-md" role="document">
            <div class="modal-content shadow-lg border-0">
                <div class="modal-header bg-gradient-secondary text-white py-2">
                    <h6 class="modal-title mb-0">
                        <i class="fas fa-cog"></i> <span data-translate="loyaltySettingsTitle">Loyalty Points Settings</span>
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body p-3">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> <span data-translate="loyaltySettingsInfo">Configure how customers earn and redeem loyalty points</span>
                    </div>

                    <form id="loyaltySettingsForm">
                        <!-- Points Earning Rate -->
                        <div class="form-group">
                            <label class="font-weight-bold">
                                <i class="fas fa-star text-warning"></i> <span data-translate="pointsPer100">Points Per ₹100 Spent</span>
                            </label>
                            <input type="number" class="form-control" id="settingPointsPer100" 
                                   min="0" step="0.1" required>
                            <small class="form-text text-muted" data-translate="pointsPer100Help">
                                How many points customer earns for every ₹100 spent
                            </small>
                        </div>

                        <!-- Redemption Rate -->
                        <div class="form-group">
                            <label class="font-weight-bold">
                                <i class="fas fa-rupee-sign text-success"></i> <span data-translate="redemptionRate">Value of 1 Point (in ₹)</span>
                            </label>
                            <input type="number" class="form-control" id="settingRedemptionRate" 
                                   min="0" step="0.1" required>
                            <small class="form-text text-muted" data-translate="redemptionRateHelp">
                                Monetary value of 1 point when redeemed
                            </small>
                        </div>

                        <!-- Minimum Redemption -->
                        <div class="form-group">
                            <label class="font-weight-bold">
                                <i class="fas fa-gift text-danger"></i> <span data-translate="minRedemption">Minimum Points for Redemption</span>
                            </label>
                            <input type="number" class="form-control" id="settingMinRedemption" 
                                   min="0" step="1" required>
                            <small class="form-text text-muted" data-translate="minRedemptionHelp">
                                Minimum points required before customer can redeem
                            </small>
                        </div>

                        <!-- Points Expiry -->
                        <div class="form-group">
                            <label class="font-weight-bold">
                                <i class="fas fa-calendar-times text-warning"></i> <span data-translate="pointsExpiry">Points Expiry (Days)</span>
                            </label>
                            <input type="number" class="form-control" id="settingPointsExpiry" 
                                   min="0" step="1" required>
                            <small class="form-text text-muted" data-translate="pointsExpiryHelp">
                                Days until points expire (0 = never expire)
                            </small>
                        </div>

                        <!-- Example Calculation -->
                        <div class="card bg-light mt-3">
                            <div class="card-body p-2">
                                <h6 class="mb-2"><i class="fas fa-calculator"></i> <span data-translate="settingsExample">Example:</span></h6>
                                <div id="settingsExample" class="small">
                                    <div><span data-translate="purchase">Purchase:</span> ₹1,000</div>
                                    <div class="text-success"><span data-translate="pointsEarned">Points Earned:</span> <span id="examplePoints">10</span> points</div>
                                    <div class="text-primary">Redemption Value: ₹<span id="exampleValue">10</span></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer py-2 bg-light">
                    <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnSaveLoyaltySettings">
                        <i class="fas fa-save"></i> Save Settings
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Include Loyalty Points Modal -->
    <?php include('loyalty-points-modal.php'); ?>

    <!-- Include Keyboard Shortcuts Help Modal -->
    <?php include('keyboard-shortcuts-help.php'); ?>

    <!-- Hidden values -->
    <input type="hidden" id="invoiceNumber" value="<?php echo $invoiceNumber; ?>">
    <input type="hidden" id="userId" value="<?php echo $userId; ?>">
    <input type="hidden" id="currentSalesType" value="<?php echo $defaultSalesType; ?>">
    <input type="hidden" id="salesTypeCategory" value="SALE">
    <input type="hidden" id="gstType" value="inclusive">
    <input type="hidden" id="transportNameValue" value="">
    <input type="hidden" id="vehicleNumberValue" value="">
    <input type="hidden" id="transportGSTPercent" value="0">
    <input type="hidden" id="transportGSTTypeValue" value="inclusive">
    <input type="hidden" id="transportGSTAmount" value="0">
    <input type="hidden" id="cooliAmount" value="0">
    <input type="hidden" id="notes" value="">

    <!-- Hidden Buttons for Event Handlers -->
    <button type="button" id="btnHoldBill" style="display:none;"></button>
    <button type="button" id="btnViewHoldBills" style="display:none;"></button>
    <button type="button" id="clearCart" style="display:none;"></button>
    <button type="button" id="newSale" style="display:none;"></button>
    <button type="button" id="btnExpenses" style="display:none;"></button>
    <button type="button" id="btnGSTDetails" style="display:none;"></button>
    <button type="button" id="btnShippingDetails" style="display:none;"></button>
    <button type="button" id="btnPrevious" style="display:none;"></button>
    <button type="button" id="btnNext" style="display:none;"></button>
    <button type="button" id="btnLoyaltySettings" style="display:none;"></button>
    <button type="button" id="btnDeleteBill" style="display:none;"></button>

    <!-- Include Product Selection Modal -->
    <?php include('product-selection-modal.php'); ?>

    <!-- Include Add Customer Modal -->
    <?php include('add-customer-modal.php'); ?>

    <!-- Include Payment Registration Modal -->
    <?php include('payment-registration-modal.php'); ?>

    <!-- Points Redemption Modal for Discount -->
    <div class="modal fade" id="pointsRedemptionModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-md" role="document">
            <div class="modal-content shadow-lg border-warning border-2">
                <div class="modal-header bg-gradient-warning text-dark py-2">
                    <h6 class="modal-title mb-0">
                        <i class="fas fa-star"></i> Redeem Loyalty Points for Discount
                    </h6>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body p-3">
                    <!-- Customer Points Info -->
                    <div class="alert alert-warning mb-3">
                        <div class="row align-items-center">
                            <div class="col-7">
                                <strong><i class="fas fa-user"></i> <span id="redeemCustomerName">Select Customer</span></strong><br>
                                <small class="text-muted">Available Balance</small>
                            </div>
                            <div class="col-5 text-right">
                                <h3 class="mb-0 text-success">
                                    <i class="fas fa-star"></i> <span id="redeemAvailablePoints">0</span>
                                </h3>
                                <small class="text-muted">points</small>
                            </div>
                        </div>
                    </div>

                    <!-- Settings Info -->
                    <div class="card bg-light mb-3">
                        <div class="card-body p-2">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <small class="text-muted">Current Rate:</small>
                                    <strong class="ml-2">1 Point = ₹<span id="redeemPointValue">1</span></strong>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="btnRedeemSettings" title="Change Settings">
                                    <i class="fas fa-cog"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Redemption Form -->
                    <div class="form-group mb-3">
                        <label class="font-weight-bold">
                            <i class="fas fa-star text-warning"></i> Points to Redeem
                        </label>
                        <input type="number" id="redeemPointsInput" class="form-control form-control-lg text-center" 
                               placeholder="Enter points" step="1" min="0" value="0">
                        <small class="form-text text-muted">
                            Minimum: <span id="redeemMinPoints">100</span> points
                        </small>
                    </div>

                    <!-- Discount Preview -->
                    <div class="card border-success mb-3">
                        <div class="card-body p-3">
                            <div class="row align-items-center">
                                <div class="col-6">
                                    <h6 class="mb-0 text-muted">Discount Amount:</h6>
                                </div>
                                <div class="col-6 text-right">
                                    <h3 class="mb-0 text-success">
                                        ₹<span id="redeemDiscountAmount">0.00</span>
                                    </h3>
                                </div>
                            </div>
                            <hr class="my-2">
                            <div class="row">
                                <div class="col-6">
                                    <small class="text-muted">Points Used:</small><br>
                                    <strong><span id="redeemPointsUsed">0</span> points</strong>
                                </div>
                                <div class="col-6 text-right">
                                    <small class="text-muted">Remaining:</small><br>
                                    <strong class="text-info"><span id="redeemPointsRemaining">0</span> points</strong>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Warning Messages -->
                    <div id="redeemWarning" class="alert alert-danger" style="display:none;">
                        <i class="fas fa-exclamation-triangle"></i> <span id="redeemWarningText"></span>
                    </div>
                </div>
                <div class="modal-footer py-2 bg-light">
                    <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-sm btn-success" id="btnApplyPointsDiscount" disabled>
                        <i class="fas fa-check"></i> Apply Discount
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Product Discount Edit Modal -->
    <div class="modal fade" id="productDiscountModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-md" role="document">
            <div class="modal-content shadow-lg border-0">
                <div class="modal-header bg-gradient-info text-white py-2">
                    <h6 class="modal-title mb-0">
                        <i class="fas fa-percent"></i> <span data-translate="editProductDiscount">Edit Product Discount</span>
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body p-3">
                    <input type="hidden" id="editDiscountIndex">
                    
                    <!-- Product Info -->
                    <div class="alert alert-light border mb-3">
                        <div class="row">
                            <div class="col-12">
                                <strong class="text-primary"><i class="fas fa-box"></i> <span id="editProductName">Product Name</span></strong><br>
                                <small class="text-muted">Code: <span id="editProductCode">-</span></small>
                            </div>
                        </div>
                        <hr class="my-2">
                        <div class="row">
                            <div class="col-6">
                                <small class="text-muted">Base Price:</small><br>
                                <strong class="text-success" id="editProductPrice">₹0.00</strong>
                            </div>
                            <div class="col-6">
                                <small class="text-muted">Quantity:</small><br>
                                <strong class="text-info" id="editProductQty">0</strong>
                            </div>
                        </div>
                    </div>

                    <!-- Discount Form -->
                    <div class="form-group mb-3">
                        <label class="font-weight-bold">
                            <i class="fas fa-tag text-warning"></i> <span data-translate="discountAmount">Discount Amount</span>
                        </label>
                        <input type="number" id="editDiscountAmount" class="form-control form-control-lg text-center" 
                               placeholder="0" step="0.01" min="0" value="0">
                    </div>

                    <div class="form-group mb-3">
                        <label class="font-weight-bold">
                            <i class="fas fa-exchange-alt text-info"></i> <span data-translate="discountType">Discount Type</span>
                        </label>
                        <div class="btn-group btn-group-toggle w-100" data-toggle="buttons">
                            <label class="btn btn-outline-primary active">
                                <input type="radio" name="editDiscType" id="editDiscPercentage" value="PERCENTAGE" checked> 
                                <i class="fas fa-percent"></i> Percentage (%)
                            </label>
                            <label class="btn btn-outline-success">
                                <input type="radio" name="editDiscType" id="editDiscAmount" value="AMOUNT"> 
                                <i class="fas fa-rupee-sign"></i> Amount (₹)
                            </label>
                        </div>
                    </div>

                    <!-- Calculation Preview -->
                    <div class="card bg-light border-success">
                        <div class="card-body p-3">
                            <div class="row mb-2">
                                <div class="col-6 text-muted">
                                    <small data-translate="subtotalLabel">Subtotal (Qty × Price):</small>
                                </div>
                                <div class="col-6 text-right">
                                    <strong id="editSubtotal">₹0.00</strong>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-6 text-danger">
                                    <small><i class="fas fa-minus-circle"></i> <span data-translate="discount">Discount:</span></small>
                                </div>
                                <div class="col-6 text-right text-danger">
                                    <strong id="editDiscountValue">- ₹0.00</strong>
                                </div>
                            </div>
                            <hr class="my-2">
                            <div class="row">
                                <div class="col-6">
                                    <strong class="text-success" data-translate="afterDiscountLabel">After Discount:</strong>
                                </div>
                                <div class="col-6 text-right">
                                    <h5 class="mb-0 text-success" id="editFinalAmount">₹0.00</h5>
                                </div>
                            </div>
                            <small class="text-muted"><i class="fas fa-info-circle"></i> <span data-translate="taxAppliedNote">Tax will be applied on this amount</span></small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer py-2 bg-light">
                    <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i> <span data-translate="cancel">Cancel</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-danger" id="btnRemoveDiscount">
                        <i class="fas fa-eraser"></i> <span data-translate="removeDisc">Remove Discount</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-success" id="btnSaveProductDiscount">
                        <i class="fas fa-check"></i> <span data-translate="applyDisc">Apply Discount</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile Quick Edit Modal -->
    <div class="modal fade" id="mobileQuickEditModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content modern-mobile-modal border-0 shadow-lg">
                <div class="modal-header bg-gradient-primary text-white py-2 px-3 border-0">
                    <h6 class="modal-title mb-0 font-weight-bold">
                        <i class="fas fa-edit"></i> <span data-translate="quickEditItem">Quick Edit Item</span>
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body p-2 compact-mobile-body">
                    <input type="hidden" id="mobileEditIndex">
                    
                    <!-- Product Info - Compact -->
                    <div class="product-info-compact mb-2 p-2 bg-light rounded">
                        <div class="font-weight-bold text-primary" id="mobileEditProductName" style="font-size: 14px;">Product Name</div>
                        <small class="text-muted"><span data-translate="codeLabel">Code</span>: <span id="mobileEditProductCode">-</span></small>
                    </div>

                    <!-- Rate and Quantity in Single Row -->
                    <div class="row no-gutters mb-2">
                        <div class="col-6 pr-1">
                            <label class="compact-label mb-1">
                                <i class="fas fa-rupee-sign text-success"></i> <span data-translate="rate">Rate</span>
                            </label>
                            <div class="input-group input-group-sm">
                                <div class="input-group-prepend">
                                    <span class="input-group-text bg-success text-white border-success" style="padding: 0.25rem 0.4rem; font-size: 11px;">₹</span>
                                </div>
                                <input type="number" id="mobileEditRate" class="form-control text-right font-weight-bold" 
                                       step="0.01" min="0" placeholder="150.00" style="font-size: 12px;">
                            </div>
                        </div>
                        <div class="col-6 pl-1">
                            <label class="compact-label mb-1">
                                <i class="fas fa-cubes text-info"></i> <span data-translate="qty">Qty</span>
                            </label>
                            <input type="number" id="mobileEditQty" class="form-control form-control-sm text-center font-weight-bold" 
                                   step="0.01" min="0.01" placeholder="1.00" style="font-size: 12px;">
                        </div>
                    </div>

                    <!-- Quantity Suggestions - Quick Select -->
                    <div class="qty-suggestions mb-2">
                        <button type="button" class="qty-btn" data-qty="1">1</button>
                        <button type="button" class="qty-btn" data-qty="2">2</button>
                        <button type="button" class="qty-btn" data-qty="5">5</button>
                        <button type="button" class="qty-btn" data-qty="10">10</button>
                        <button type="button" class="qty-btn" data-qty="12">12</button>
                        <button type="button" class="qty-btn" data-qty="24">24</button>
                        <button type="button" class="qty-btn" data-qty="50">50</button>
                        <button type="button" class="qty-btn" data-qty="100">100</button>
                    </div>

                    <!-- Discount and Type in Single Row -->
                    <div class="form-group mb-2">
                        <label class="compact-label mb-1">
                            <i class="fas fa-tag text-warning"></i> <span data-translate="discount">Discount</span>
                        </label>
                        <div class="row no-gutters">
                            <div class="col-5 pr-1">
                                <input type="number" id="mobileEditDiscount" class="form-control form-control-sm text-center font-weight-bold" 
                                       step="0.01" min="0" placeholder="0" style="font-size: 12px;">
                            </div>
                            <div class="col-7 pl-1">
                                <div class="btn-group btn-group-toggle w-100" data-toggle="buttons">
                                    <label class="btn btn-outline-primary btn-sm py-1 active" style="font-size: 10px; padding: 0.25rem 0.3rem;">
                                        <input type="radio" name="mobileDiscType" id="mobileDiscPercentage" value="PERCENTAGE" checked> 
                                        <i class="fas fa-percent"></i> <span data-translate="percentage">%</span>
                                    </label>
                                    <label class="btn btn-outline-success btn-sm py-1" style="font-size: 10px; padding: 0.25rem 0.3rem;">
                                        <input type="radio" name="mobileDiscType" id="mobileDiscAmount" value="AMOUNT"> 
                                        <i class="fas fa-rupee-sign"></i> <span>₹</span>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Preview - Compact -->
                    <div class="preview-card bg-gradient-light border rounded p-2 mt-2">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <small class="text-muted" data-translate="subtotalLabel">Subtotal:</small>
                            <span class="font-weight-bold" style="font-size: 13px;" id="mobileEditSubtotal">₹0.00</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <small class="text-danger" data-translate="discount">Discount:</small>
                            <span class="font-weight-bold text-danger" style="font-size: 13px;" id="mobileEditDiscountValue">-₹0.00</span>
                        </div>
                        <hr class="my-1" style="border-top: 1px dashed #dee2e6;">
                        <div class="d-flex justify-content-between align-items-center">
                            <strong style="font-size: 14px;" data-translate="total">Total:</strong>
                            <strong class="text-success" style="font-size: 18px;" id="mobileEditTotal">₹0.00</strong>
                        </div>
                    </div>
                </div>
                <div class="modal-footer py-2 px-2 bg-white border-top">
                    <button type="button" class="btn btn-sm btn-light border" data-dismiss="modal" style="font-size: 12px;">
                        <i class="fas fa-times"></i> <span data-translate="cancel">Cancel</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-danger" id="btnMobileDeleteItem" style="font-size: 12px;">
                        <i class="fas fa-trash"></i> <span data-translate="deleteLabel">Delete</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-success" id="btnMobileSaveEdit" style="font-size: 12px;">
                        <i class="fas fa-check"></i> <span data-translate="saveLabel">Save</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Transport GST Configuration Modal -->
    <div class="modal fade" id="transportGSTModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-md" role="document">
            <div class="modal-content shadow-lg border-0">
                <div class="modal-header bg-gradient-info text-white py-2">
                    <h6 class="modal-title mb-0">
                        <i class="fas fa-truck"></i> <span data-translate="transportDetails">Transport Details</span>
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body p-3" style="max-height: 70vh; overflow-y: auto;">
                    <!-- Transport Name -->
                    <div class="form-group mb-2">
                        <label class="small font-weight-bold mb-1">
                            <i class="fas fa-truck text-primary"></i> <span data-translate="transportName">Transport Name</span>
                        </label>
                        <input type="text" id="transportName" class="form-control form-control-sm" 
                               placeholder="Enter transport company name" data-translate="enterTransportName">
                    </div>

                    <!-- Vehicle Number -->
                    <div class="form-group mb-2">
                        <label class="small font-weight-bold mb-1">
                            <i class="fas fa-car text-success"></i> <span data-translate="vehicleNumber">Vehicle Number</span>
                        </label>
                        <input type="text" id="vehicleNumber" class="form-control form-control-sm text-uppercase" 
                               placeholder="e.g., TN01AB1234" data-translate="enterVehicleNumber">
                    </div>

                    <!-- Transport Amount Display -->
                    <div class="form-group mb-2">
                        <label class="small font-weight-bold mb-1">
                            <i class="fas fa-rupee-sign text-danger"></i> <span data-translate="transportAmount">Transport Amount</span>
                        </label>
                        <input type="number" id="transportGSTAmount" class="form-control form-control-sm" 
                               placeholder="0.00" step="0.01" min="0" value="0" readonly>
                    </div>

                    <!-- GST Percentage -->
                    <div class="form-group mb-2">
                        <label class="small font-weight-bold mb-1">
                            <i class="fas fa-percent text-warning"></i> <span data-translate="gstPercentage">GST Percentage (%)</span>
                        </label>
                        <input type="number" id="transportGSTPercentage" class="form-control form-control-sm" 
                               placeholder="0" step="0.01" min="0" max="100" value="0">
                    </div>

                    <!-- GST Type: Inclusive/Exclusive -->
                    <div class="form-group mb-2">
                        <label class="small font-weight-bold mb-1">
                            <i class="fas fa-exchange-alt text-primary"></i> <span data-translate="gstType">GST Type</span>
                        </label>
                        <div class="btn-group btn-group-sm btn-group-toggle w-100" data-toggle="buttons">
                            <label class="btn btn-outline-success active">
                                <input type="radio" name="transportGSTType" id="gstInclusive" value="inclusive" checked> 
                                <i class="fas fa-check-circle"></i> <span data-translate="inclusive">Inclusive</span>
                            </label>
                            <label class="btn btn-outline-primary">
                                <input type="radio" name="transportGSTType" id="gstExclusive" value="exclusive"> 
                                <i class="fas fa-plus-circle"></i> <span data-translate="exclusive">Exclusive</span>
                            </label>
                        </div>
                    </div>

                    <!-- Calculation Preview -->
                    <div class="card bg-light border-success">
                        <div class="card-body p-3">
                            <h6 class="mb-2"><i class="fas fa-calculator"></i> <span data-translate="calculation">Calculation</span></h6>
                            <div class="row mb-2">
                                <div class="col-7 text-muted">
                                    <small id="transportBaseLabel" data-translate="baseAmount">Base Amount:</small>
                                </div>
                                <div class="col-5 text-right">
                                    <strong id="transportBaseAmount">₹0.00</strong>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-7 text-info">
                                    <small><i class="fas fa-plus-circle"></i> <span data-translate="gstAmount">GST Amount</span> (<span id="gstRateDisplay">0</span>%):</small>
                                </div>
                                <div class="col-5 text-right text-info">
                                    <strong id="transportGSTValue">₹0.00</strong>
                                </div>
                            </div>
                            <hr class="my-2">
                            <div class="row">
                                <div class="col-7">
                                    <strong class="text-success" id="transportTotalLabel" data-translate="totalAmount">Total Amount:</strong>
                                </div>
                                <div class="col-5 text-right">
                                    <h5 class="mb-0 text-success" id="transportTotalAmount">₹0.00</h5>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer py-2 bg-light">
                    <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i> <span data-translate="cancel">Cancel</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-danger" id="btnResetTransportGST">
                        <i class="fas fa-eraser"></i> <span data-translate="reset">Reset</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-success" id="btnApplyTransportGST">
                        <i class="fas fa-check"></i> <span data-translate="apply">Apply</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Include GST Details Modal -->
    <?php include('gst-details-modal.php'); ?>

    <!-- Expenses Modal -->
    <div class="modal fade" id="expensesModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content shadow-lg border-0">
                <div class="modal-header bg-gradient-danger text-white py-2">
                    <h6 class="modal-title mb-0">
                        <i class="fas fa-money-bill-wave"></i> <span data-translate="registerExpense">Register Expense</span>
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body p-3" style="max-height: 70vh; overflow-y: auto;">
                    <form id="expenseForm">
                        <div class="row">
                            <!-- Expense Date -->
                            <div class="col-md-6 mb-2">
                                <label class="small font-weight-bold mb-1"><i class="fas fa-calendar text-primary"></i> <span data-translate="expenseDate">Expense Date</span> <span class="text-danger">*</span></label>
                                <input type="date" class="form-control form-control-sm" id="expenseDate" required>
                            </div>

                            <!-- Expense Category -->
                            <div class="col-md-6 mb-2">
                                <label class="small font-weight-bold mb-1"><i class="fas fa-tags text-success"></i> <span data-translate="category">Category</span> <span class="text-danger">*</span></label>
                                <select class="form-control form-control-sm" id="expenseCategory" required>
                                    <option value="">Select Category</option>
                                    <option value="Rent">Rent</option>
                                    <option value="Utilities">Utilities</option>
                                    <option value="Salaries">Salaries & Wages</option>
                                    <option value="Transport">Transport & Fuel</option>
                                    <option value="Maintenance">Maintenance & Repairs</option>
                                    <option value="Supplies">Office Supplies</option>
                                    <option value="Marketing">Marketing</option>
                                    <option value="Taxes">Taxes & Fees</option>
                                    <option value="Insurance">Insurance</option>
                                    <option value="Inventory">Inventory Purchase</option>
                                    <option value="Food">Food & Refreshments</option>
                                    <option value="Travel">Travel</option>
                                    <option value="Miscellaneous">Miscellaneous</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Amount -->
                            <div class="col-md-6 mb-2">
                                <label class="small font-weight-bold mb-1"><i class="fas fa-rupee-sign text-danger"></i> <span data-translate="amount">Amount</span> <span class="text-danger">*</span></label>
                                <input type="number" class="form-control form-control-sm" id="expenseAmount" 
                                       placeholder="0.00" step="0.01" min="0" required>
                            </div>

                            <!-- Payment Mode -->
                            <div class="col-md-6 mb-2">
                                <label class="small font-weight-bold mb-1"><i class="fas fa-wallet text-warning"></i> <span data-translate="paymentMode">Payment Mode</span></label>
                                <select class="form-control form-control-sm" id="expensePaymentMode">
                                    <option value="Cash">Cash</option>
                                    <option value="UPI">UPI</option>
                                    <option value="Card">Card</option>
                                    <option value="Bank Transfer">Bank Transfer</option>
                                    <option value="Cheque">Cheque</option>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Reference -->
                            <div class="col-md-12 mb-2">
                                <label class="small font-weight-bold mb-1"><i class="fas fa-hashtag text-secondary"></i> <span data-translate="reference">Reference/Bill No</span></label>
                                <input type="text" class="form-control form-control-sm" id="expenseReference" 
                                       placeholder="Bill number, receipt number">
                            </div>
                        </div>

                        <div class="row">
                            <!-- Description -->
                            <div class="col-md-12 mb-2">
                                <label class="small font-weight-bold mb-1"><i class="fas fa-file-alt text-info"></i> <span data-translate="description">Description</span></label>
                                <textarea class="form-control form-control-sm" id="expenseDescription" rows="2" 
                                          placeholder="Enter expense details..."></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer py-2 bg-light">
                    <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i> <span data-translate="cancel">Close</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-danger" id="btnSaveExpense">
                        <i class="fas fa-save"></i> <span data-translate="saveExpense">Save Expense</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Include Shipping Details Modal -->
    <?php include('shipping-modal.php'); ?>

    <!-- Include Hold Bills Modal -->
    <?php include('hold-bills-modal.php'); ?>

    <!-- Include Delete Bill Modal -->
    <?php include('delete-bill-modal.php'); ?>

    <!-- Mobile Product Search Modal -->
    <div class="modal fade mobile-search-modal" id="mobileProductSearchModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header text-white">
                    <h6 class="modal-title mb-0">
                        <i class="fas fa-search"></i> Search Product
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal" id="closeMobileSearch">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="mobile-search-container">
                    <div class="mobile-search-input-group">
                        <div class="mobile-search-wrapper">
                            <input type="text" 
                                   class="mobile-search-input" 
                                   id="mobileSearchInput" 
                                   placeholder="Type product name, code or barcode..."
                                   autocomplete="off"
                                   autofocus>
                            <i class="fas fa-search mobile-search-icon"></i>
                        </div>
                        <button type="button" class="mobile-camera-btn" id="mobileCameraBtn" title="Scan Barcode">
                            <i class="fas fa-camera"></i>
                        </button>
                    </div>
                </div>
                <div class="mobile-search-results" id="mobileSearchResults">
                    <div class="mobile-search-empty">
                        <i class="fas fa-search"></i>
                        <p>Type to search for products</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile Quick Actions Button (Floating) -->
    <button type="button" class="mobile-quick-actions-btn d-md-none" id="mobileQuickActionsBtn">
        <i class="fas fa-bolt"></i>
    </button>

    <!-- Quick Actions Modal - WhatsApp Style -->
    <div class="modal fade" id="quickActionsModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" style="border: none; border-radius: 8px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);">
                <div class="modal-header" style="background: linear-gradient(135deg, #128C7E 0%, #075E54 100%); border-radius: 8px 8px 0 0; padding: 0.6rem 1rem; border-bottom: none;">
                    <h6 class="modal-title mb-0 text-white" style="font-size: 1rem; font-weight: 600; letter-spacing: 0.3px;">
                        <i class="fas fa-bolt"></i> Quick Actions
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal" style="opacity: 0.9; text-shadow: none; font-size: 1.5rem; font-weight: 300;">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body" style="padding: 0.75rem 1rem; background: #ffffff;">
                    <div class="row">
                        <!-- Navigation Actions -->
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-info quick-action-btn" onclick="location.href='../customer/index.php'">
                                <i class="fas fa-home"></i> Home
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-info quick-action-btn" id="btnViewLedgerModal" disabled>
                                <i class="fas fa-book"></i> Ledger
                            </button>
                        </div>
                        
                        <!-- Bill Management -->
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-primary quick-action-btn" id="btnHoldBillModal">
                                <i class="fas fa-pause-circle"></i> Hold Bill
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-primary quick-action-btn" id="btnViewHoldBillsModal">
                                <i class="fas fa-list"></i> View Hold Bills
                            </button>
                        </div>
                        
                        <!-- Cart Actions -->
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-warning quick-action-btn" id="clearCartModal">
                                <i class="fas fa-eraser"></i> Clear Cart
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-secondary quick-action-btn" id="newSaleModal">
                                <i class="fas fa-file"></i> New Sale
                            </button>
                        </div>
                        
                        <!-- Financial Actions -->
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-danger quick-action-btn" id="btnExpensesModal">
                                <i class="fas fa-money-bill-wave"></i> Expenses
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-primary quick-action-btn" id="btnRegisterPaymentModal">
                                <i class="fas fa-money-bill-wave"></i> Customer Payments
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-success quick-action-btn" id="btnGSTDetailsModal">
                                <i class="fas fa-file-invoice-dollar"></i> GST Details
                            </button>
                        </div>
                        
                        <!-- Shipping & Navigation -->
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-primary quick-action-btn" id="btnShippingDetailsModal">
                                <i class="fas fa-shipping-fast"></i> Shipping Details
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-warning quick-action-btn" id="btnPreviousModal">
                                <i class="fas fa-arrow-left"></i> Previous Bill
                            </button>
                        </div>
                        
                        <!-- Settings & Language -->
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-warning quick-action-btn" id="btnNextModal">
                                <i class="fas fa-arrow-right"></i> Next Bill
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-secondary quick-action-btn" id="btnLoyaltySettingsModal">
                                <i class="fas fa-cog"></i> Loyalty Settings
                            </button>
                        </div>
                        
                        <!-- Language & Delete -->
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-info quick-action-btn" onclick="toggleLanguage()">
                                <i class="fas fa-language"></i> Toggle Language (த)
                            </button>
                        </div>
                        <div class="col-md-6 mb-2">
                            <button type="button" class="btn btn-block btn-danger quick-action-btn" id="btnDeleteBillModal">
                                <i class="fas fa-trash"></i> Delete Bill
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>
    
    <!-- Modern Message Box - Load first -->
    <script src="js/modern-messagebox.js"></script>
    
    <!-- POS Settings Manager - Load first so other modules can use it -->
    <script src="js/pos-settings.js"></script>
    
    <script src="js/translations.js"></script>
    <script src="js/gst-type-manager.js"></script>
    <script src="js/sales-enhancements.js"></script>
    <script src="js/gst-details.js?v=<?php echo time(); ?>"></script>
    <script src="js/expenses.js"></script>
    <script src="js/shipping-details.js"></script>
    <script src="js/hold-bills.js"></script>
    <script src="js/payment-registration.js"></script>
    <script src="js/delete-bill.js"></script>
    <script src="js/sales.js?v=<?php echo time(); ?>"></script>
    
    <!-- Barcode Scanner Script - Using html5-qrcode -->
    <script>
        // Use html5-qrcode for QR and barcode scanning
        function startBarcodeScanner() {
            // Modal setup
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
                background: rgba(0,0,0,0.9); z-index: 9999; display: flex;
                align-items: center; justify-content: center; flex-direction: column;
            `;

            const content = document.createElement('div');
            content.style.cssText = `
                background: white; padding: 20px; border-radius: 10px;
                text-align: center; max-width: 90vw; max-height: 90vh;
            `;

            const title = document.createElement('h4');
            title.textContent = 'Scan QR Code or Barcode';
            title.style.marginBottom = '15px';

            const qrReaderDiv = document.createElement('div');
            qrReaderDiv.id = 'qr-reader';
            qrReaderDiv.style.cssText = 'width: 100% !important; max-width: 400px; margin: 0 auto;';

            const controlsDiv = document.createElement('div');
            controlsDiv.style.cssText = 'margin-top: 15px;';

            const flashBtn = document.createElement('button');
            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
            flashBtn.className = 'btn btn-warning mr-2';
            flashBtn.id = 'flashToggle';

            const closeBtn = document.createElement('button');
            closeBtn.innerHTML = '<i class="fas fa-times"></i> Close Scanner';
            closeBtn.className = 'btn btn-danger';

            controlsDiv.appendChild(flashBtn);
            controlsDiv.appendChild(closeBtn);

            content.appendChild(title);
            content.appendChild(qrReaderDiv);
            content.appendChild(controlsDiv);
            modal.appendChild(content);
            document.body.appendChild(modal);

            const html5QrCode = new Html5Qrcode("qr-reader");
            let isScanning = true;
            let isFlashOn = false;

            async function toggleFlash() {
                try {
                    if (html5QrCode.getState() === Html5QrcodeScannerState.SCANNING) {
                        if (isFlashOn) {
                            await html5QrCode.applyVideoConstraints({
                                advanced: [{ torch: false }]
                            });
                            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: OFF';
                            flashBtn.className = 'btn btn-secondary mr-2';
                            isFlashOn = false;
                        } else {
                            await html5QrCode.applyVideoConstraints({
                                advanced: [{ torch: true }]
                            });
                            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
                            flashBtn.className = 'btn btn-warning mr-2';
                            isFlashOn = true;
                        }
                    }
                } catch (err) {
                    console.log('Flash control not supported:', err);
                }
            }

            function stopScanner() {
                if (isScanning) {
                    isScanning = false;
                    html5QrCode.stop().then(() => {
                        if (modal.parentNode) document.body.removeChild(modal);
                    }).catch(() => {
                        if (modal.parentNode) document.body.removeChild(modal);
                    });
                }
            }

            flashBtn.onclick = toggleFlash;
            closeBtn.onclick = stopScanner;
            modal.onclick = (e) => {
                if (e.target === modal) stopScanner();
            };

            const onScanSuccess = (decodedText, decodedResult) => {
                if (!isScanning) return;
                
                // Set value in product code input
                const productCodeInput = document.getElementById('productCode');
                if (productCodeInput) {
                    productCodeInput.value = decodedText;
                    
                    // Trigger the search function from scanner-integration.js
                    if (typeof searchProductByCode === 'function') {
                        searchProductByCode(decodedText);
                    } else {
                        // Fallback: trigger change event
                        $(productCodeInput).trigger('change');
                    }
                    
                    // Show immediate scan feedback
                    if (typeof MsgBox !== 'undefined') {
                        MsgBox.success('Barcode scanned: ' + decodedText);
                    }
                }
                
                // Stop the scanner
                stopScanner();
            };

            html5QrCode.start(
                { facingMode: "environment" },
                {
                    fps: 10,
                    qrbox: 250,
                    formatsToSupport: [
                        Html5QrcodeSupportedFormats.QR_CODE,
                        Html5QrcodeSupportedFormats.CODE_128,
                        Html5QrcodeSupportedFormats.EAN_13,
                        Html5QrcodeSupportedFormats.EAN_8,
                        Html5QrcodeSupportedFormats.UPC_A,
                        Html5QrcodeSupportedFormats.UPC_E,
                        Html5QrcodeSupportedFormats.CODE_39,
                        Html5QrcodeSupportedFormats.CODE_93,
                        Html5QrcodeSupportedFormats.CODABAR
                    ]
                },
                onScanSuccess,
                (errorMessage) => {
                    // ignore scan errors, keep frame open
                }
            ).then(() => {
                // Automatically turn on flashlight when camera starts
                setTimeout(async () => {
                    try {
                        await html5QrCode.applyVideoConstraints({
                            advanced: [{ torch: true }]
                        });
                        flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
                        flashBtn.className = 'btn btn-warning mr-2';
                        isFlashOn = true;
                    } catch (err) {
                        console.log('Auto-flash not supported:', err);
                        flashBtn.style.display = 'none';
                    }
                }, 1000);
            }).catch(err => {
                alert('Camera initialization failed: ' + err);
                stopScanner();
            });
        }
        
        // Alias functions for compatibility
        window.openBarcodeScanner = startBarcodeScanner;
        window.startScanner = startBarcodeScanner;
    </script>
    
    <!-- Mobile Cart Sync -->
    <script src="js/mobile-cart-sync.js"></script>
    
    <!-- Mobile Quick Edit -->
    <script src="js/mobile-quick-edit.js"></script>
    
    <!-- Mobile Search -->
    <script src="js/mobile-search.js"></script>
    
    <!-- Keyboard Shortcuts -->
    <script src="js/keyboard-shortcuts.js"></script>
    
    <script>
        // Watch for changes in cart table
        var cartObserver = new MutationObserver(function(mutations) {
            syncCartToMobileCards();
        });
        
        // Function to update cart grand total display
        function updateCartGrandTotal() {
            var grandTotal = $('#grandTotal').text();
            $('#grandTotalCart').text(grandTotal);
        }
        
        // Function to update mobile cart calculations
        function updateMobileCartCalculations() {
            syncCartToMobileCards();
            updateCartGrandTotal();
        }
        
        // Override or extend the existing calculation function when it's available
        $(document).ready(function() {
            // Wait for all scripts to load
            setTimeout(function() {
                var originalCalculateTotals = window.calculateTotals;
                if (typeof originalCalculateTotals === 'function') {
                    window.calculateTotals = function() {
                        originalCalculateTotals();
                        updateMobileCartCalculations();
                    };
                } else {
                    console.warn('calculateTotals function not found');
                }
            }, 1000);
        });
        
        // Also update on any change to cart items or grandTotal
        var grandTotalObserver = new MutationObserver(function(mutations) {
            updateCartGrandTotal();
        });
        
        var cartItemsObserver = new MutationObserver(function(mutations) {
            syncCartToMobileCards();
        });
        
        // Load language preference on page load
        $(document).ready(function() {
            loadLanguagePreference();
            
            // Register Payment Button Event
            $('#btnRegisterPayment').on('click', function() {
                // Get selected customer
                const selectedCustomerId = $('#customerSelect').val();
                const selectedCustomerName = $('#customerSelect option:selected').data('name');
                
                if (selectedCustomerId) {
                    // Pre-select customer and load their outstanding bills
                    $('#paymentCustomerSelect').val(selectedCustomerId);
                    $('#paymentCustomerName').text(selectedCustomerName || '-');
                    $('#paymentCustomerCode').text($('#customerSelect option:selected').data('code') || '-');
                    $('#paymentCustomerInfo').slideDown();
                    
                    // Open modal
                    $('#paymentRegistrationModal').modal('show');
                    
                    // Auto-load outstanding bills after modal is shown
                    setTimeout(function() {
                        $('#btnLoadOutstanding').click();
                    }, 300);
                } else {
                    // No customer selected, just open modal
                    $('#paymentRegistrationModal').modal('show');
                }
            });
            
            // Mobile Product Search Modal Functionality
            var mobileSearchTimeout;
            var isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;
            
            // Auto-open mobile search modal on page load for mobile devices
            if (isMobileDevice) {
                setTimeout(function() {
                    $('#mobileProductSearchModal').modal('show');
                }, 500);
            }
            
            // Auto-focus search input when modal opens
            $('#mobileProductSearchModal').on('shown.bs.modal', function() {
                $('#mobileSearchInput').focus();
            });
            
            // Show mobile search modal when CODE input is focused on mobile
            $('#productCode').on('focus', function(e) {
                if (isMobileDevice) {
                    e.preventDefault();
                    $(this).blur(); // Prevent keyboard from showing
                    $('#mobileProductSearchModal').modal('show');
                }
            });
            
            // Mobile Search Input Handler
            $('#mobileSearchInput').on('input', function() {
                var searchTerm = $(this).val().trim();
                
                // Clear previous timeout
                clearTimeout(mobileSearchTimeout);
                
                if (searchTerm.length < 2) {
                    $('#mobileSearchResults').html(
                        '<div class="mobile-search-empty">' +
                        '<i class="fas fa-search"></i>' +
                        '<p>Type at least 2 characters to search</p>' +
                        '</div>'
                    );
                    return;
                }
                
                // Show loading state
                $('#mobileSearchResults').html(
                    '<div class="mobile-search-loading">' +
                    '<div class="spinner-border" role="status">' +
                    '<span class="sr-only">Loading...</span>' +
                    '</div>' +
                    '</div>'
                );
                
                // Search with debounce
                mobileSearchTimeout = setTimeout(function() {
                    searchMobileProducts(searchTerm);
                }, 300);
            });
            
            // Mobile Camera Button - Open Scanner
            $('#mobileCameraBtn').on('click', function() {
                // Close search modal
                $('#mobileProductSearchModal').modal('hide');
                
                // Clear search
                $('#mobileSearchInput').val('');
                
                // Open barcode scanner
                if (typeof startBarcodeScanner === 'function') {
                    setTimeout(function() {
                        startBarcodeScanner();
                    }, 300);
                } else {
                    alert('Barcode scanner not available. Please refresh the page.');
                }
            });
            
            // Close modal handler
            $('#closeMobileSearch').on('click', function() {
                $('#mobileSearchInput').val('');
                $('#mobileSearchResults').html(
                    '<div class="mobile-search-empty">' +
                    '<i class="fas fa-search"></i>' +
                    '<p>Type to search for products</p>' +
                    '</div>'
                );
            });
            
            // Handle barcode scan result from scanner
            $(document).on('barcodeScanned', function(e, barcode) {
                if ($('#mobileProductSearchModal').hasClass('show')) {
                    $('#mobileSearchInput').val(barcode);
                    $('#mobileSearchInput').trigger('input');
                }
            });
            
            // Quick Actions Button - Desktop & Mobile
            $('#btnQuickActions, #mobileQuickActionsBtn').on('click', function() {
                $('#quickActionsModal').modal('show');
            });
            
            // Header Quick Action Buttons - Direct triggers
            $('#btnHoldBillHeader').on('click', function() {
                $('#btnHoldBill').trigger('click');
            });
            
            $('#btnViewHoldBillsHeader').on('click', function() {
                $('#btnViewHoldBills').trigger('click');
            });
            
            $('#clearCartHeader').on('click', function() {
                MsgBox.confirm(t('confirmClearCart') || 'Are you sure you want to clear the cart?', {
                    type: 'warning',
                    confirmText: 'Yes, Clear',
                    cancelText: 'Cancel',
                    confirmStyle: 'danger'
                }).then(function(confirmed) {
                    if (confirmed && typeof clearCart === 'function') {
                        clearCart();
                    }
                });
            });
            
            $('#newSaleHeader').on('click', function() {
                location.reload();
            });
            
            $('#btnGSTDetailsHeader').on('click', function() {
                if (typeof showGSTDetailsModal === 'function') {
                    showGSTDetailsModal();
                } else {
                    $('#gstDetailsModal').modal('show');
                }
            });
            
            $('#btnShippingDetailsHeader').on('click', function() {
                if (typeof openShippingModal === 'function') {
                    openShippingModal();
                } else {
                    $('#shippingModal').modal('show');
                }
            });
            
            $('#btnPreviousHeader').on('click', function() {
                $('#btnPrevious').trigger('click');
            });
            
            $('#btnNextHeader').on('click', function() {
                $('#btnNext').trigger('click');
            });
            
            $('#btnDeleteBillHeader').on('click', function() {
                // The delete-bill.js handles the confirmation, just trigger the modal open
                // The click handler is already in delete-bill.js
            });
            
            $('#btnExpensesHeader').on('click', function() {
                $('#expensesModal').modal('show');
            });
            
            $('#btnLoyaltySettingsHeader').on('click', function() {
                $('#loyaltySettingsModal').modal('show');
            });
            
            // Quick Action Buttons Click Handlers - Directly trigger modals/functions
            $('#btnHoldBillModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    // Trigger the hold bill event
                    $('#btnHoldBill').trigger('click');
                }, 300);
            });
            
            $('#btnViewHoldBillsModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    $('#btnViewHoldBills').trigger('click');
                }, 300);
            });
            
            $('#clearCartModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    MsgBox.confirm(t('confirmClearCart') || 'Are you sure you want to clear the cart?', {
                        type: 'warning',
                        confirmText: 'Yes, Clear',
                        cancelText: 'Cancel',
                        confirmStyle: 'danger'
                    }).then(function(confirmed) {
                        if (confirmed && typeof clearCart === 'function') {
                            clearCart();
                        }
                    });
                }, 300);
            });
            
            $('#newSaleModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    MsgBox.confirm(t('confirmNewSale') || 'Start a new sale? This will clear current cart.', {
                        type: 'confirm',
                        confirmText: 'Yes, New Sale',
                        cancelText: 'Cancel'
                    }).then(function(confirmed) {
                        if (confirmed) {
                            location.reload();
                        }
                    });
                }, 300);
            });
            
            $('#btnExpensesModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    $('#expensesModal').modal('show');
                }, 300);
            });
            
            $('#btnRegisterPaymentModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    // Get selected customer
                    const selectedCustomerId = $('#customerSelect').val();
                    const selectedCustomerName = $('#customerSelect option:selected').data('name');
                    
                    if (selectedCustomerId) {
                        // Trigger the main register payment button
                        $('#btnRegisterPayment').trigger('click');
                    } else {
                        MsgBox.warning('Please select a customer first.');
                    }
                }, 300);
            });
            
            $('#btnGSTDetailsModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    if (typeof showGSTDetailsModal === 'function') {
                        showGSTDetailsModal();
                    } else {
                        $('#gstDetailsModal').modal('show');
                    }
                }, 300);
            });
            
            $('#btnShippingDetailsModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    if (typeof openShippingModal === 'function') {
                        openShippingModal();
                    } else {
                        $('#shippingModal').modal('show');
                    }
                }, 300);
            });
            
            $('#btnPreviousModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    // Navigate to previous bill logic
                    var currentInvoice = $('#invoiceNumber').val();
                    // Trigger previous button if it exists in sales.js
                    if ($('#btnPrevious').length) {
                        $('#btnPrevious').trigger('click');
                    }
                }, 300);
            });
            
            $('#btnNextModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    // Navigate to next bill logic
                    var currentInvoice = $('#invoiceNumber').val();
                    // Trigger next button if it exists in sales.js
                    if ($('#btnNext').length) {
                        $('#btnNext').trigger('click');
                    }
                }, 300);
            });
            
            $('#btnLoyaltySettingsModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                setTimeout(function() { 
                    $('#loyaltySettingsModal').modal('show');
                }, 300);
            });
            
            $('#btnDeleteBillModal').on('click', function() {
                $('#quickActionsModal').modal('hide');
                // The delete-bill.js will handle opening the modal
            });
            
            // Mobile Quick Edit - Discount Type Change
            $('input[name="mobileDiscType"]').on('change', function() {
                updateMobileEditPreview();
            });
            
            // Quantity Suggestion Buttons
            $('.qty-btn').on('click', function() {
                var qty = $(this).data('qty');
                $('#mobileEditQty').val(qty);
                
                // Highlight active button
                $('.qty-btn').removeClass('active');
                $(this).addClass('active');
                
                // Update preview
                updateMobileEditPreview();
            });
            
            // Remove active class when manually changing quantity
            $('#mobileEditQty').on('input', function() {
                $('.qty-btn').removeClass('active');
                updateMobileEditPreview();
            });
            
            // Mobile Quick Edit - Update preview on input
            $('#mobileEditRate, #mobileEditQty, #mobileEditDiscount').on('input', function() {
                updateMobileEditPreview();
            });
            
            // Mobile Quick Edit - Save Changes
            $('#btnMobileSaveEdit').on('click', function() {
                var index = parseInt($('#mobileEditIndex').val());
                var rate = parseFloat($('#mobileEditRate').val()) || 0;
                var qty = parseFloat($('#mobileEditQty').val()) || 0;
                var discount = parseFloat($('#mobileEditDiscount').val()) || 0;
                var discountType = $('input[name="mobileDiscType"]:checked').val();
                
                // Validate
                if (rate <= 0) {
                    MsgBox.warning('Please enter a valid rate');
                    return;
                }
                if (qty <= 0) {
                    MsgBox.warning('Please enter a valid quantity');
                    return;
                }
                
                // Check if this is a new item (index = -1) or editing existing
                if (index === -1) {
                    // Adding new item from search
                    if (window.tempMobileProduct) {
                        var product = window.tempMobileProduct;
                        
                        // Check if cart exists, if not initialize
                        if (typeof cart === 'undefined') {
                            window.cart = [];
                        }
                        
                        // Create new cart item
                        var newItem = {
                            productId: product.id,
                            productCode: product.code,
                            productName: product.name,
                            rate: rate,
                            quantity: qty,
                            discount: discount,
                            discountType: discountType,
                            amount: rate * qty,
                            taxRate: 0 // Will be calculated by main system
                        };
                        
                        // Add to cart
                        cart.push(newItem);
                        
                        // Clear temp data
                        window.tempMobileProduct = null;
                        
                        // Update display
                        if (typeof updateDisplay === 'function') {
                            updateDisplay();
                        }
                        
                        // Close modal
                        $('#mobileQuickEditModal').modal('hide');
                        
                        // Clear search and reopen search modal for next product
                        setTimeout(function() {
                            $('#mobileSearchInput').val('');
                            $('#mobileSearchResults').html(
                                '<div class="mobile-search-empty">' +
                                '<i class="fas fa-search"></i>' +
                                '<p>Type to search for products</p>' +
                                '</div>'
                            );
                            $('#mobileProductSearchModal').modal('show');
                            setTimeout(function() {
                                $('#mobileSearchInput').focus();
                            }, 300);
                        }, 300);
                    }
                } else {
                    // Editing existing item
                    if (typeof cart === 'undefined' || !cart[index]) return;
                    
                    // Update cart item
                    cart[index].rate = rate;
                    cart[index].quantity = qty;
                    cart[index].discount = discount;
                    cart[index].discountType = discountType;
                    cart[index].amount = rate * qty;
                    
                    // Update display
                    if (typeof updateDisplay === 'function') {
                        updateDisplay();
                    }
                    
                    // Close modal
                    $('#mobileQuickEditModal').modal('hide');
                }
            });
            
            // Mobile Quick Edit - Delete Item
            $('#btnMobileDeleteItem').on('click', function() {
                var index = parseInt($('#mobileEditIndex').val());
                
                // If index is -1, it's a new item, just close modal
                if (index === -1) {
                    $('#mobileQuickEditModal').modal('hide');
                    window.tempMobileProduct = null;
                    return;
                }
                
                if (typeof cart === 'undefined' || !cart[index]) return;
                
                cart.splice(index, 1);
                
                // Update display
                if (typeof updateDisplay === 'function') {
                    updateDisplay();
                }
                
                // Close modal
                $('#mobileQuickEditModal').modal('hide');
            });
            
            // Start observing cart items for changes
            var cartItemsElement = document.getElementById('cartItems');
            if (cartItemsElement) {
                cartItemsObserver.observe(cartItemsElement, { 
                    childList: true, 
                    subtree: true,
                    characterData: true 
                });
            }
            
            // Start observing grandTotal for changes
            var grandTotalElement = document.getElementById('grandTotal');
            if (grandTotalElement) {
                grandTotalObserver.observe(grandTotalElement, { 
                    childList: true, 
                    characterData: true, 
                    subtree: true 
                });
            }
            
            // Add manual update triggers for common cart operations
            $(document).on('cartUpdated', function() {
                syncCartToMobileCards();
                updateCartGrandTotal();
            });
            
            // Listen for any input changes in cart table
            $(document).on('input change', '.cart-rate-input, .cart-qty-input', function() {
                setTimeout(function() {
                    syncCartToMobileCards();
                    updateCartGrandTotal();
                }, 100);
            });
            
            // Initial sync and update (run multiple times to ensure it works)
            setTimeout(function() {
                syncCartToMobileCards();
                updateCartGrandTotal();
            }, 500);
            
            setTimeout(function() {
                syncCartToMobileCards();
                updateCartGrandTotal();
            }, 1500);
            
            setTimeout(function() {
                syncCartToMobileCards();
                updateCartGrandTotal();
            }, 3000);
            
            // Handle price type dropdown selection
            $('.dropdown-menu a[data-price-type]').on('click', function(e) {
                e.preventDefault();
                var priceType = $(this).data('price-type');
                var priceLabel = $(this).find('span').text();
                
                // Update hidden field
                $('#selectedPriceType').val(priceType);
                
                // Update dropdown button label
                $('#selectedPriceLabel').text(priceLabel);
                
                // Update active state
                $('.dropdown-menu a[data-price-type]').removeClass('active');
                $(this).addClass('active');
                
                // If product is already loaded, update the price
                var productId = $('#productId').val();
                if (productId) {
                    var prices = $('#availablePrices').val();
                    if (prices) {
                        try {
                            var pricesObj = JSON.parse(prices);
                            if (pricesObj[priceType]) {
                                $('#rate').val(parseFloat(pricesObj[priceType]).toFixed(2));
                            }
                        } catch(e) {
                            console.error('Error parsing prices:', e);
                        }
                    }
                }
            });
            
            // Mobile Details Toggle Functionality
            $('#mobileDetailsToggle').on('click', function() {
                var content = $('#mobileTotalsContent');
                var button = $(this);
                
                if (content.hasClass('expanded')) {
                    // Collapse
                    content.removeClass('expanded');
                    button.removeClass('active');
                    button.find('span').attr('data-translate', 'showDetails').text(t('showDetails'));
                } else {
                    // Expand
                    content.addClass('expanded');
                    button.addClass('active');
                    button.find('span').attr('data-translate', 'hideDetails').text(t('hideDetails'));
                }
            });
            
            // Sync Mobile and Desktop Input Fields
            // Sync rate fields
            $('#rate').on('input change', function() {
                $('#rateMobile').val($(this).val());
                if (typeof calculateCurrentItemTotal === 'function') {
                    calculateCurrentItemTotal();
                }
            });
            $('#rateMobile').on('input change', function() {
                $('#rate').val($(this).val());
                if (typeof calculateCurrentItemTotal === 'function') {
                    calculateCurrentItemTotal();
                }
            });
            
            // Sync quantity fields
            $('#quantity').on('input change', function() {
                $('#quantityMobile').val($(this).val());
                if (typeof calculateCurrentItemTotal === 'function') {
                    calculateCurrentItemTotal();
                }
            });
            $('#quantityMobile').on('input change', function() {
                $('#quantity').val($(this).val());
                if (typeof calculateCurrentItemTotal === 'function') {
                    calculateCurrentItemTotal();
                }
            });
            
            // Mobile Add to Cart button
            $('#addToCartMobile').on('click', function() {
                $('#addToCart').click();
            });
            
            // Sync Enter key on mobile rate to move to quantity
            $('#rateMobile').on('keydown', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    $('#quantityMobile').focus().select();
                }
            });
            
            // Sync Enter key on mobile quantity to add to cart
            $('#quantityMobile').on('keydown', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    $('#addToCartMobile').click();
                }
            });
        });
    </script>
</body>
</html>
