<!--
Web Order System Documentation
============================

Overview
--------
This web-based order system is designed for retail operations, providing a user-friendly interface for processing sales and returns. It features a responsive design that works on both desktop and mobile devices, with an intuitive two-panel layout on desktop that transforms into a tabbed interface on mobile devices.

Key Features
-----------
1. Responsive Design
   - Desktop: Side-by-side items and basket panels
   - Mobile: Tab-based navigation between items and basket
   - Adaptive banner for company logo
   - Full-height utilization in all screen sizes

2. Item Management
   - Real-time search filtering
   - Image thumbnails for visual identification
   - Automatic item selection when search yields single result
   - Price tiers (P1, P2, P3) for flexible pricing
   - Barcode support for quick item lookup

3. Basket Features
   - Add items with customizable quantities and prices
   - Support for negative quantities (returns)
   - Item consolidation option (combine same items)
   - Running total with color coding for returns
   - Audio feedback (beep) on basket updates

4. User Interaction Methods
   Desktop:
   - F5: Edit selected/last basket item
   - Delete key: Remove selected basket item
   - Double-click basket item: Edit quantity/price
   - Long-press basket item: Delete item
   
   Mobile:
   - Tab switching for items/basket views
   - Touch-based double-tap and long-press support
   - Full screen modal dialogs

5. Visual Feedback
   - Red highlighting for negative quantities/totals
   - Selected item highlighting
   - Large product images in edit modal
   - Confirmation dialogs for deletions

Operating Instructions
--------------------
1. Finding Items:
   - Type in search box to filter items
   - Items can be filtered by barcode, description, or variants
   - Single match auto-triggers quantity/price modal

2. Adding Items:
   - Double-click item or use single-item search
   - Select price tier (P1/P2/P3)
   - Enter quantity (negative for returns)
   - Confirm to add to basket

3. Editing Basket Items:
   - Double-click basket item
   - Press F5 key for selected/last item
   - Modify quantity/price in modal
   - Negative quantities for returns

4. Removing Basket Items:
   - Long-press item in basket
   - Select item and press Delete key
   - Confirm deletion in modal

5. Mobile-Specific:
   - Use tabs to switch between items/basket
   - All desktop functions available via touch
   - Optimized layout for smaller screens

Technical Details
---------------
1. Data Structure:
   - Items include: ID, Barcode, Description, Variants, P1/P2/P3 prices, Image
   - Basket entries track: Item details, selected price, quantity
   - Images stored as filenames, served from configurable base URL

2. Features:
   - Lazy loading of images
   - Error handling for missing images
   - Responsive image sizing
   - Audio feedback system
   - Mobile-first responsive design

3. Dependencies:
   - Bootstrap 5.1.3 for UI components
   - jQuery 3.6.0 for DOM manipulation
   - Bootstrap Icons for UI elements

4. Browser Support:
   - Modern browsers (Chrome, Firefox, Safari, Edge)
   - Mobile browsers with touch support
   - Requires JavaScript enabled

Setup Requirements
----------------
1. Server:
   - Web server with image hosting capability
   - Configure IMAGE_BASE_URL for image serving
   - Audio file (beep.mp3/wav) for feedback

2. Images:
   - Product images in specified directory
   - Placeholder image for missing products
   - Company logo for banner

3. Configuration:
   - Update IMAGE_BASE_URL constant
   - Configure item data source
   - Set up audio feedback file

Maintenance Notes
---------------
1. Images:
   - Keep consistent image sizes
   - Use compressed images for performance
   - Maintain placeholder image

2. Data:
   - Regular updates to item database
   - Maintain price tiers
   - Keep barcode database current

3. Performance:
   - Monitor image loading
   - Optimize search performance
   - Maintain audio feedback system
-->

<!DOCTYPE html>
<html>
<head>
    <title>Web Order System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <style>
        /* Banner Styles */
        .banner-container {
            padding: 10px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        .banner-image {
            max-width: 100%;
            height: auto;
            object-fit: contain;
        }

        /* Layout and Container Styles */
        .search-container { 
            margin-bottom: 20px; 
        }
        .table-container { 
            height: calc(100vh - 250px); /* Base height for items table */
            overflow-y: auto; 
        }
        @media (max-width: 768px) {
            .table-container {
                height: calc(100vh - 200px);
            }
            #itemsPanel, #basketPanel {
                display: none;
            }
            #itemsPanel.active, #basketPanel.active {
                display: block;
            }
        }

        /* Modal and Backdrop Styles */
        .modal-backdrop.show {
            opacity: 0.7;
        }
        .modal-disabled {
            pointer-events: none;
            user-select: none;
        }
        .modal {
            z-index: 1050;
        }
        .modal-backdrop {
            z-index: 1040;
        }

        /* Table Styles */
        #itemsTable tbody tr:hover { 
            cursor: pointer; 
            background-color: rgba(0,123,255,0.1); 
        }
        #itemsTable tbody tr.table-primary { 
            background-color: rgba(0,123,255,0.2); 
        }

        /* Image Styles */
        .item-thumbnail {
            height: 80px;
            width: 80px;
            object-fit: contain;
            margin-right: 10px;
            vertical-align: middle;
        }
        
        .item-modal-image {
            max-height: 200px;
            width: auto;
            object-fit: contain;
            margin-bottom: 0.5rem;
        }

        /* Add these styles */
        .basket-help {
            margin-bottom: 0.5rem;
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }
        
        .basket-help ul {
            padding-left: 1.5rem;
            margin-top: 0.25rem;
        }

        /* Modern UI Enhancements */
        .table {
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .table thead th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
            padding: 12px;
        }

        .table tbody td {
            padding: 12px;
            vertical-align: middle;
        }

        .search-container input {
            border-radius: 4px;
            padding: 10px 15px;
            border: 1px solid #dee2e6;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
            transition: all 0.3s ease;
        }

        .search-container input:focus {
            background-color: #ffffd9;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.15);
            border-color: #80bdff;
        }

        .btn {
            border-radius: 4px;
            padding: 0.375rem 0.75rem;
        }

        .card {
            border-radius: 4px;
        }

        .modal-content {
            border-radius: 6px;
        }

        .modal-header {
            padding: 0.5rem 1rem;
        }

        .modal-body {
            padding: 0.5rem 1rem;
        }

        .modal-footer {
            padding: 0.5rem 1rem;
        }

        .alert {
            padding: 0.5rem;
            margin-bottom: 0.5rem;
        }

        /* Mobile Tab Styles */
        .btn-group {
            border-radius: 4px;
        }

        .btn-group .btn {
            border-radius: 0;
            padding: 12px 24px;
        }

        /* Scrollbar Styling */
        .table-container::-webkit-scrollbar {
            width: 8px;
        }

        .table-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .table-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .table-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* Animation Effects */
        .modal.fade .modal-dialog {
            transform: scale(0.95);
            transition: transform 0.2s ease-out;
        }

        .modal.show .modal-dialog {
            transform: scale(1);
        }

        /* Responsive Adjustments */
        @media (max-width: 768px) {
            .btn {
                width: 100%;
                margin-bottom: 0.5rem;
            }
            
            .btn-group .btn {
                margin-bottom: 0;
            }

            .modal-dialog {
                margin: 0.5rem;
            }
        }

        /* Add bottom margin to the basket table container */
        #basketPanel .table-container {
            height: calc(100vh - 370px); /* Increased space for bottom elements */
            margin-bottom: 0.5rem;
        }

        /* Ensure buttons stay at bottom with minimal spacing */
        .button-bar {
            margin-top: 0.5rem;
            padding-bottom: 0;
            position: relative;
        }

        /* Make total card more compact */
        .card {
            margin-bottom: 0.5rem;
        }

        .card-body {
            padding: 0.5rem;
        }

        /* Add styles for change display modal */
        #changeDisplayModal .modal-body {
            background-color: #f8f9fa;
        }

        #changeDisplayModal .display-4 {
            font-size: 3.5rem;
            color: #28a745;
        }

        #changeDisplayModal h2 {
            color: #666;
            font-size: 1.5rem;
        }

        /* Add CSS for table images */
        #itemsTable img {
            transition: transform 0.2s;
        }
        
        #itemsTable img:hover {
            transform: scale(2);
            cursor: pointer;
            z-index: 1000;
        }
        
        /* Much larger image column */
        #itemsTable th:first-child,
        #itemsTable td:first-child {
            width: 150px;
            min-width: 150px;
            max-width: 150px;
            padding: 5px;
        }

        #itemsTable td:first-child img {
            max-height: 120px;
            width: auto;
            display: block;
            margin: 0 auto;
        }

        /* Description column width */
        #itemsTable th:nth-child(2),
        #itemsTable td:nth-child(2) {
            min-width: 200px;
            padding-left: 15px;
        }

        /* Price columns width */
        #itemsTable th:nth-child(n+3),
        #itemsTable td:nth-child(n+3) {
            width: 80px;
            min-width: 80px;
            text-align: right;
            padding-right: 15px;
        }

        /* Ensure table fits container */
        .table-container {
            overflow-x: auto;
        }

        /* Center images in cells */
        #itemsTable td:first-child {
            text-align: center;
            vertical-align: middle;
        }
    </style>
</head>
<body>
    <!-- Add this right after the body tag, before the main container -->
    <div class="container-fluid mb-3">
        <div class="row">
            <div class="col-12">
                <div class="banner-container text-center">
                    <!-- Placeholder for logo -->
                    <img src="logo.jpg" alt="Company Logo" class="img-fluid banner-image" style="max-height: 100px;">
                    <div class="text-end">
                        <span class="badge bg-secondary">Invoice #: <span id="currentInvoice">0001</span></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add this audio element to your HTML, right after the body tag -->
    <audio id="beepSound" preload="auto">
        <source src="beep.mp3" type="audio/mpeg">
        <!-- Fallback beep in case MP3 isn't supported -->
        <source src="beep.wav" type="audio/wav">
    </audio>

    <!-- Main Container -->
    <div class="container-fluid mt-3">
        <!-- Mobile Tabs - Only visible on small screens -->
        <div class="d-md-none mb-3">
            <div class="btn-group w-100" role="group">
                <button type="button" class="btn btn-primary" id="itemsTab">Items</button>
                <button type="button" class="btn btn-outline-primary" id="basketTab">Basket</button>
            </div>
        </div>

        <div class="row">
            <!-- Items Panel -->
            <div class="col-12 col-md-6" id="itemsPanel">
                <div class="search-container">
                    <input type="text" id="searchInput" class="form-control" placeholder="Search items..." />
                </div>
                
                <div class="table-container">
                    <table id="itemsTable" class="table table-striped">
                        <thead>
                            <tr>
                                <th>Image</th>
                                <th>Description</th>
                                <th>P1</th>
                                <th>P2</th>
                                <th>P3</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Basket Panel -->
            <div class="col-12 col-md-6" id="basketPanel">
                <div class="table-container">
                    <table id="basketTable" class="table table-striped">
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th>Price</th>
                                <th>Quantity</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
                
                <!-- Add this right after the basket table, before the grand total -->
                <div class="basket-help text-muted small mb-2">
                    <i class="bi bi-info-circle"></i> Tips:
                    <ul class="mb-0">
                        <li>Double-click an item to edit quantity/price | Long-press an item to delete it </li>                        
                    </ul>
                </div>

                <div class="mt-3">
                    <div class="card bg-light">
                        <div class="card-body">
                            <h3 class="card-title text-end mb-0">
                                Total: <span id="grandTotal">0.00</span>
                            </h3>
                        </div>
                    </div>
                </div>

                <div class="button-bar">
                    <button type="button" class="btn btn-primary" id="checkoutBtn">Checkout (Ctrl+Enter)</button>
                    <button type="button" class="btn btn-danger" id="clearBtn">Clear Basket</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Quantity Modal -->
    <div class="modal fade" id="quantityModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h5 class="modal-title">Select Price and Quantity</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body py-2">
                    <div class="mb-2 text-center">
                        <img id="modalItemImage" 
                             class="img-fluid item-modal-image" 
                             alt=""
                             style="max-width: 100%; height: auto;">
                    </div>
                    <div class="mb-2">
                        <div class="alert alert-info py-2">
                            <strong>Item:</strong> <span id="modalItemDescription"></span>
                        </div>
                    </div>
                    <div class="mb-2">
                        <label class="form-label mb-1">Enter Quantity (negative for returns):</label>
                        <input type="number" 
                               id="quantityInput" 
                               class="form-control" 
                               value="1" 
                               step="any" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label mb-1">Select Price:</label>
                        <div class="btn-group w-100" role="group">
                            <button type="button" class="btn btn-outline-primary price-select" data-price-type="P1">P1</button>
                            <button type="button" class="btn btn-outline-primary price-select" data-price-type="P2">P2</button>
                            <button type="button" class="btn btn-outline-primary price-select" data-price-type="P3">P3</button>
                        </div>
                    </div>
                    <div class="selected-price-info alert alert-info py-2 d-none">
                        Selected Price: <span id="selectedPriceValue">0.00</span>
                    </div>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="addToBasketBtn" disabled>Add to Basket</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add the delete confirmation modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Delete this item?</p>
                    <div class="alert alert-info">
                        <strong id="deleteItemDesc"></strong>
                        <br>
                        Quantity: <span id="deleteItemQty"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Checkout Modal -->
    <div class="modal fade" id="checkoutModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h5 class="modal-title">Checkout - Invoice #<span id="modalInvoice">0001</span></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group mb-2">
                                <label class="form-label">Total Bill</label>
                                <input type="text" class="form-control" id="totalBill" readonly>
                            </div>
                            <div class="form-group mb-2">
                                <label class="form-label">Tendered Amount</label>
                                <input type="number" class="form-control" id="tenderedAmount" step="any">
                            </div>
                            <div class="form-group mb-2">
                                <label class="form-label">Change</label>
                                <input type="text" class="form-control" id="changeAmount" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-2">
                                <label class="form-label">Customer ID</label>
                                <input type="text" class="form-control" id="customerID">
                            </div>
                            <div class="form-group mb-2">
                                <label class="form-label">Payment Method</label>
                                <div class="btn-group w-100" role="group">
                                    <button type="button" class="btn btn-outline-primary payment-select active" data-payment="cash">Cash (F1)</button>
                                    <button type="button" class="btn btn-outline-primary payment-select" data-payment="card">Card (F2)</button>
                                    <button type="button" class="btn btn-outline-primary payment-select" data-payment="others">Others (F3)</button>
                                </div>
                            </div>
                            <div id="paymentDetails" class="d-none">
                                <div class="form-group mb-2">
                                    <label class="form-label">Payment Details</label>
                                    <input type="text" class="form-control" id="paymentReference">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group mb-2">
                        <label class="form-label">Transaction Notes</label>
                        <textarea class="form-control" id="transactionNotes" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="saveTransaction">Save Transaction (Enter)</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add this new modal for JSON display (temporary) -->
    <div class="modal fade" id="jsonDisplayModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title">Transaction JSON (Temporary Display)</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <pre id="jsonDisplay" style="white-space: pre-wrap; max-height: 70vh; overflow-y: auto;"></pre>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add this new modal for displaying change -->
    <div class="modal fade" id="changeDisplayModal" tabindex="-1">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header bg-success text-white py-2">
                    <h5 class="modal-title">Change</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center py-4">
                    <h2 class="mb-2">Change Due:</h2>
                    <h1 class="display-4 fw-bold"><span id="changeDisplayAmount">0.00</span></h1>
                </div>
            </div>
        </div>
    </div>

    <!-- Add receipt display modal -->
    <div class="modal fade" id="receiptDisplayModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Receipt Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <pre id="receiptDisplay" style="font-family: monospace; white-space: pre-wrap;"></pre>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        /**
         * Mock Inventory Data
         * This simulates the data that would normally come from MySQL database
         * When converting to ASP.NET, this will be replaced with actual database calls
         */
        const mockInventoryData = [
            {
                ItemID: 1,
                Barcode: "4800888169129",
                Description: "Coca Cola",
                Variants: "1.5L Bottle",
                P1: 65.00,
                P2: 62.00,
                P3: 60.00,
                StoreName: "Athrun",
                Picture: "img00 (1).jpeg"
            },
            {
                ItemID: 2,
                Barcode: "4800016125299",
                Description: "Milo",
                Variants: "1kg Pack",
                P1: 220.00,
                P2: 215.00,
                P3: 210.00,
                StoreName: "Athrun",
                Picture: "img00 (2).jpeg"
            },
            {
                ItemID: 3,
                Barcode: "4800361415599",
                Description: "Lucky Me Pancit Canton",
                Variants: "Original 80g",
                P1: 15.00,
                P2: 14.50,
                P3: 14.00,
                StoreName: "Athrun",
                Picture: "img00 (3).jpeg"
            },
            {
                ItemID: 4,
                Barcode: "4800016122298",
                Description: "Nescafe Classic",
                Variants: "200g Jar",
                P1: 185.00,
                P2: 180.00,
                P3: 175.00,
                StoreName: "Athrun",
                Picture: "img00 (4).jpeg"
            },
            {
                ItemID: 5,
                Barcode: "4800361367898",
                Description: "Palmolive Shampoo",
                Variants: "400ml Bottle",
                P1: 159.00,
                P2: 155.00,
                P3: 150.00,
                StoreName: "Athrun",
                Picture: "img00 (5).jpeg"
            },
            {
                ItemID: 6,
                Barcode: "4800024577398",
                Description: "Safeguard Soap",
                Variants: "135g Bar",
                P1: 45.00,
                P2: 43.00,
                P3: 41.00,
                StoreName: "Athrun",
                Picture: "img00 (6).jpeg"
            },
            {
                ItemID: 7,
                Barcode: "4800361412598",
                Description: "Great Taste Coffee",
                Variants: "50 sachets/box",
                P1: 150.00,
                P2: 145.00,
                P3: 140.00,
                StoreName: "Athrun",
                Picture: "img00 (7).jpeg"
            },
            {
                ItemID: 8,
                Barcode: "4800016129297",
                Description: "Bear Brand Milk",
                Variants: "320g Pack",
                P1: 95.00,
                P2: 92.00,
                P3: 90.00,
                StoreName: "Athrun",
                Picture: "img00 (8).jpeg"
            },
            {
                ItemID: 9,
                Barcode: "4800361419597",
                Description: "Tide Powder",
                Variants: "1kg Pack",
                P1: 120.00,
                P2: 116.00,
                P3: 112.00,
                StoreName: "Athrun",
                Picture: "img00 (9).jpeg"
            },
            {
                ItemID: 10,
                Barcode: "4800024571396",
                Description: "Head & Shoulders",
                Variants: "400ml Bottle",
                P1: 200.00,
                P2: 195.00,
                P3: 190.00,
                StoreName: "Athrun",
                Picture: "img00 (10).jpeg"
            },
            {
                ItemID: 11,
                Barcode: "4800888165127",
                Description: "Sprite",
                Variants: "1.5L Bottle",
                P1: 65.00,
                P2: 62.00,
                P3: 60.00,
                StoreName: "Athrun",
                Picture: "img00 (11).jpeg"
            },
            {
                ItemID: 12,
                Barcode: "4800016127295",
                Description: "Maggi Magic Sarap",
                Variants: "100g Pack",
                P1: 25.00,
                P2: 23.50,
                P3: 22.00,
                StoreName: "Athrun",
                Picture: "img00 (12).jpeg"
            },
            {
                ItemID: 13,
                Barcode: "4800361413595",
                Description: "Century Tuna the best in the Philipines 0002",
                Variants: "180g Can",
                P1: 45.00,
                P2: 43.00,
                P3: 41.00,
                StoreName: "Athrun",
                Picture: "img00 (13).jpeg"
            },
            {
                ItemID: 14,
                Barcode: "4800016124296",
                Description: "Piattos",
                Variants: "85g Pack",
                P1: 35.00,
                P2: 33.00,
                P3: 31.00,
                StoreName: "Athrun",
                Picture: "img00 (14).jpeg"
            },
            {
                ItemID: 15,
                Barcode: "4800361416596",
                Description: "Colgate Toothpaste",
                Variants: "150g Tube",
                P1: 75.00,
                P2: 72.00,
                P3: 70.00,
                StoreName: "Athrun",
                Picture: "img00 (15).jpeg"
            },         
            {
                ItemID: 16,
                Barcode: "4800024575394",
                Description: "Tang Juice Powder",
                Variants: "25g Sachet",
                P1: 15.00,
                P2: 14.00,
                P3: 13.00,
                StoreName: "Athrun",
                Picture: "img00 (16).jpeg"
            },
            {
                ItemID: 17,
                Barcode: "4800361411591",
                Description: "Dove Soap",
                Variants: "135g Bar",
                P1: 55.00,
                P2: 53.00,
                P3: 51.00,
                StoreName: "Athrun",
                Picture: "img00 (17).jpeg"
            },
            {
                ItemID: 18,
                Barcode: "4800016128290",
                Description: "Knorr Cubes",
                Variants: "60g Pack",
                P1: 35.00,
                P2: 33.00,
                P3: 31.00,
                StoreName: "Athrun",
                Picture: "img00 (18).jpeg"
            },
            {
                ItemID: 19,
                Barcode: "4800361418590",
                Description: "Del Monte Ketchup",
                Variants: "320g Bottle",
                P1: 45.00,
                P2: 43.00,
                P3: 41.00,
                StoreName: "Athrun",
                Picture: "img00 (19).jpeg"
            },
            {
                ItemID: 20,
                Barcode: "4800024572393",
                Description: "Oreo Cookies",
                Variants: "137g Pack",
                P1: 40.00,
                P2: 38.00,
                P3: 36.00,
                StoreName: "Athrun",
                Picture: "img00 (20).jpeg"
            },
            {
                ItemID: 21,
                Barcode: "4800888167121",
                Description: "Royal Tru Orange",
                Variants: "1.5L Bottle",
                P1: 65.00,
                P2: 62.00,
                P3: 60.00,
                StoreName: "Athrun",
                Picture: "img00 (21).jpeg"
            },
            {
                ItemID: 22,
                Barcode: "4800016126292",
                Description: "Cream Silk Conditioner",
                Variants: "340ml Bottle",
                P1: 180.00,
                P2: 175.00,
                P3: 170.00,
                StoreName: "Athrun",
                Picture: "img00 (22).jpeg"
            },
            {
                ItemID: 23,
                Barcode: "4800361414592",
                Description: "Argentina Corned Beef",
                Variants: "260g Can",
                P1: 95.00,
                P2: 92.00,
                P3: 90.00,
                StoreName: "Athrun",
                Picture: "img00 (23).jpeg"
            },
            {
                ItemID: 24,
                Barcode: "4800016123291",
                Description: "Chippy",
                Variants: "110g Pack",
                P1: 30.00,
                P2: 28.00,
                P3: 26.00,
                StoreName: "Athrun",
                Picture: "img00 (24).jpeg"
            },
            {
                ItemID: 25,
                Barcode: "4800361417593",
                Description: "Joy Dishwashing Liquid",
                Variants: "500ml Bottle",
                P1: 85.00,
                P2: 82.00,
                P3: 80.00,
                StoreName: "Athrun",
                Picture: "img00 (25).jpeg"
            },
            {
                ItemID: 26,
                Barcode: "4800024576391",
                Description: "Silver Swan Soy Sauce",
                Variants: "385ml Bottle",
                P1: 40.00,
                P2: 38.00,
                P3: 36.00,
                StoreName: "Athrun",
                Picture: "img00 (26).jpeg"
            },
            {
                ItemID: 27,
                Barcode: "4800361410594",
                Description: "Datu Puti Vinegar",
                Variants: "385ml Bottle",
                P1: 35.00,
                P2: 33.00,
                P3: 31.00,
                StoreName: "Athrun",
                Picture: "img00 (27).jpeg"
            },
            {
                ItemID: 28,
                Barcode: "4800016120294",
                Description: "Nestea Iced Tea",
                Variants: "450g Pack",
                P1: 120.00,
                P2: 116.00,
                P3: 112.00,
                StoreName: "Athrun",
                Picture: "img00 (28).jpeg"
            },
            {
                ItemID: 29,
                Barcode: "4800361420593",
                Description: "555 Sardines",
                Variants: "155g Can",
                P1: 25.00,
                P2: 23.50,
                P3: 22.00,
                StoreName: "Athrun",
                Picture: "img00 (29).jpeg"
            },
            {
                ItemID: 30,
                Barcode: "4800024570392",
                Description: "Surf Powder",
                Variants: "1kg Pack",
                P1: 110.00,
                P2: 106.00,
                P3: 102.00,
                StoreName: "Athrun",
                Picture: "img00 (30).jpeg"
            }
        ];

        // Global Variables
        let consolidate = false;
        let inventoryData = mockInventoryData; // In ASP.NET, this will be loaded from database
        let basket = [];
        let selectedPrice = null;
        let selectedPriceType = null;
        let isEditing = false;
        let editingIndex = -1;
        let currentTableSelection = -1;
        let selectedBasketIndex = -1;
        let searchTimer = null;
        let currentInvoice = 1;
        let cashierId = "CASHIER001"; // This should be set during login

        // Add constant for image base URL
        const IMAGE_BASE_URL = ""; // Update this with your actual image server URL

        // Add variables for long press handling
        let pressTimer;
        let deleteIndex = -1;

        $(document).ready(function() {
            // Add this line to focus search box on startup
            $('#searchInput').focus();

            // Initial table load
            refreshItemsTable();

            // Replace the existing search input handler with this updated version
            $('#searchInput').on('input', function() {
                currentTableSelection = -1;
                
                // Clear any existing timer
                if (searchTimer) {
                    clearTimeout(searchTimer);
                }
                
                // Set a new timer
                searchTimer = setTimeout(() => {
                    refreshItemsTable();
                    
                    // Check if there's exactly one filtered item
                    const searchTerms = $('#searchInput').val().toLowerCase().split(' ').filter(term => term.length > 0);
                    const filteredItems = inventoryData.filter(item => {
                        if (searchTerms.length === 0) {
                            return true;
                        }

                        const searchableText = (
                            item.Barcode.toLowerCase() + ' ' +
                            item.Description.toLowerCase() + ' ' +
                            item.Variants.toLowerCase()
                        );

                        return searchTerms.every(term => searchableText.includes(term));
                    });

                    // If exactly one item matches, show the quantity modal
                    if (filteredItems.length === 1) {
                        const item = filteredItems[0];
                        
                        // Show item modal
                        selectedPrice = null;
                        selectedPriceType = null;
                        isEditing = false;
                        editingIndex = -1;
                        
                        $('.price-select').removeClass('active');
                        $('.selected-price-info').addClass('d-none');
                        $('#addToBasketBtn').prop('disabled', true);
                        $('#quantityInput').val(1);
                        
                        $('#modalItemDescription').text(`${item.Description} - ${item.Variants}`);
                        
                        $('.price-select').each(function() {
                            const priceType = $(this).data('price-type');
                            $(this).text(`${priceType}: ${item[priceType]}`);
                        });
                        
                        // Update modal image
                        const modalImg = $('#modalItemImage');
                        const newSrc = `${IMAGE_BASE_URL}${item.Picture}`;
                        
                        if (modalImg.attr('src') !== newSrc) {
                            modalImg.attr('src', newSrc)
                                   .attr('alt', item.Description)
                                   .one('error', function() {
                                       if (!this.hasAttribute('data-error-handled')) {
                                           this.src = 'placeholder.jpg';
                                           this.setAttribute('data-error-handled', 'true');
                                       }
                                   });
                        }
                        
                        $('#quantityModal').data('selected-item', item).modal('show');
                        
                        // Auto-select P1 price
                        $('.price-select[data-price-type="P1"]').click();
                    }
                    
                    searchTimer = null;
                }, 1500); // 1500ms = 1.5 second delay
            });

            // Keep the existing keypress handler to prevent form submission
            $('#searchInput').on('keypress', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    if (searchTimer) {
                        clearTimeout(searchTimer);
                        refreshItemsTable();
                        searchTimer = null;
                    }
                    return false;
                }
            });

            // Update the arrow key handler to clear timer and force refresh
            $('#searchInput').on('keydown', function(e) {
                const rows = $('#itemsTable tbody tr');
                
                switch(e.which) {
                    case 13: // Enter
                        e.preventDefault();
                        if (searchTimer) {
                            clearTimeout(searchTimer);
                            refreshItemsTable();
                            searchTimer = null;
                        }
                        if (currentTableSelection >= 0 && currentTableSelection < rows.length) {
                            $(rows[currentTableSelection]).dblclick();
                        }
                        break;
                        
                    case 40: // Arrow down
                        e.preventDefault();
                        if (searchTimer) {
                            clearTimeout(searchTimer);
                            refreshItemsTable();
                            searchTimer = null;
                        }
                        if (currentTableSelection < rows.length - 1) {
                            currentTableSelection++;
                        } else {
                            currentTableSelection = 0;
                        }
                        highlightSelectedRow();
                        break;
                        
                    case 38: // Arrow up
                        e.preventDefault();
                        if (searchTimer) {
                            clearTimeout(searchTimer);
                            refreshItemsTable();
                            searchTimer = null;
                        }
                        if (currentTableSelection > 0) {
                            currentTableSelection--;
                        } else {
                            currentTableSelection = rows.length - 1;
                        }
                        highlightSelectedRow();
                        break;
                }
            });

            // Price selection handling
            $('.price-select').click(function() {
                const priceType = $(this).data('price-type');
                const item = $('#quantityModal').data('selected-item');
                selectedPrice = item[priceType];
                selectedPriceType = priceType;
                
                $('.price-select').removeClass('active');
                $(this).addClass('active');
                $('.selected-price-info').removeClass('d-none');
                $('#selectedPriceValue').text(selectedPrice);
                $('#addToBasketBtn').prop('disabled', false);
            });

            // Update items table double click handler
            $('#itemsTable tbody').on('dblclick', 'tr', function(e) {
                e.preventDefault(); // Prevent default behavior
                
                // Store current scroll position
                const scrollPosition = $('#itemsTable').closest('.table-container').scrollTop();
                
                // Get the correct item using data index
                const searchTerms = $('#searchInput').val().toLowerCase().split(' ').filter(term => term.length > 0);
                const filteredItems = inventoryData.filter(item => {
                    if (searchTerms.length === 0) {
                        return true;
                    }

                    const searchableText = (
                        item.Barcode.toLowerCase() + ' ' +
                        item.Description.toLowerCase() + ' ' +
                        item.Variants.toLowerCase()
                    );

                    return searchTerms.every(term => searchableText.includes(term));
                });
                
                const item = filteredItems[$(this).data('index')];
                
                // Show item modal
                selectedPrice = null;
                selectedPriceType = null;
                isEditing = false;
                editingIndex = -1;
                
                $('.price-select').removeClass('active');
                $('.selected-price-info').addClass('d-none');
                $('#addToBasketBtn').prop('disabled', true);
                $('#quantityInput').val(1);
                
                $('#modalItemDescription').text(`${item.Description} - ${item.Variants}`);
                
                $('.price-select').each(function() {
                    const priceType = $(this).data('price-type');
                    $(this).text(`${priceType}: ${item[priceType]}`);
                });
                
                // Update modal image
                const modalImg = $('#modalItemImage');
                const newSrc = `${IMAGE_BASE_URL}${item.Picture}`;
                
                if (modalImg.attr('src') !== newSrc) {
                    modalImg.attr('src', newSrc)
                           .attr('alt', item.Description)
                           .one('error', function() {
                               if (!this.hasAttribute('data-error-handled')) {
                                   this.src = 'placeholder.jpg';
                                   this.setAttribute('data-error-handled', 'true');
                               }
                           });
                }
                
                $('#quantityModal').data('selected-item', item).modal('show');
                
                // Auto-select P1 price
                $('.price-select[data-price-type="P1"]').click();
                
                // Restore scroll position after a short delay
                setTimeout(() => {
                    $('#itemsTable').closest('.table-container').scrollTop(scrollPosition);
                }, 0);
            });

            // Edit basket item
            $('#basketTable').on('click', '.edit-item', function() {
                const index = $(this).data('index');
                const item = basket[index];
                isEditing = true;
                editingIndex = index;

                selectedPrice = null;
                selectedPriceType = null;
                $('.price-select').removeClass('active');
                $('.selected-price-info').addClass('d-none');
                $('#addToBasketBtn').prop('disabled', true);
                
                $('#modalItemDescription').text(`${item.Description} - ${item.Variants}`);
                
                $('.price-select').each(function() {
                    const priceType = $(this).data('price-type');
                    $(this).text(`${priceType}: ${item[priceType]}`);
                });

                $('#quantityInput').val(item.Quantity);
                $('#quantityModal').data('selected-item', item).modal('show');

                $(`.price-select[data-price-type="${item.PriceType}"]`).click();
            });

            // Add to basket
            $('#addToBasketBtn').click(function() {
                const item = $('#quantityModal').data('selected-item');
                const quantity = parseFloat($('#quantityInput').val());
                
                if (selectedPrice !== null) {
                    const basketItem = {
                        ItemID: item.ItemID,
                        Barcode: item.Barcode,
                        Description: item.Description,
                        Variants: item.Variants,
                        Price: selectedPrice,
                        PriceType: selectedPriceType,
                        Quantity: quantity
                    };

                    if (isEditing && editingIndex >= 0) {
                        basket[editingIndex] = basketItem;
                    } else if (consolidate) {
                        const existingIndex = basket.findIndex(i => 
                            i.ItemID === item.ItemID && 
                            i.Price === selectedPrice && 
                            i.PriceType === selectedPriceType
                        );
                        
                        if (existingIndex >= 0) {
                            basket[existingIndex].Quantity += quantity;
                        } else {
                            basket.push(basketItem);
                        }
                    } else {
                        basket.push(basketItem);
                    }

                    refreshBasketTable();
                    $('#quantityModal').modal('hide');
                    $('#searchInput').val('');
                    
                    currentTableSelection = -1;
                    highlightSelectedRow();
                    
                    refreshItemsTable();
                    $('#searchInput').focus();
                }
            });

            // Clear basket
            $('#clearBtn').click(function() {
                basket = [];
                refreshBasketTable();
            });

            // Modal events
            $('#quantityModal').on('show.bs.modal', function () {
                $('body > *:not(.modal)').attr('aria-hidden', 'true')
                                        .prop('disabled', true)
                                        .addClass('modal-disabled');
            });

            $('#quantityModal').on('shown.bs.modal', function() {
                $('#quantityInput').focus().select();
            });

            $('#quantityModal').on('hidden.bs.modal', function () {
                $('body > *:not(.modal)').removeAttr('aria-hidden')
                                        .prop('disabled', false)
                                        .removeClass('modal-disabled');
                $('#searchInput').focus();
            });

            // Handle Enter key in modal
            $('#quantityModal').on('keydown', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    e.stopPropagation();
                    $('#addToBasketBtn').click();
                    return;
                }
                
                // Handle F1, F2, F3 keys
                switch (e.which) {
                    case 112: // F1
                        e.preventDefault();
                        $('.price-select[data-price-type="P1"]').click();
                        break;
                    case 113: // F2
                        e.preventDefault();
                        $('.price-select[data-price-type="P2"]').click();
                        break;
                    case 114: // F3
                        e.preventDefault();
                        $('.price-select[data-price-type="P3"]').click();
                        break;
                }
            });

            // Add click handler for basket table rows to track selection
            $('#basketTable').on('click', 'tr', function() {
                const index = $(this).index();
                selectedBasketIndex = index;
                
                // Highlight the selected row
                $('#basketTable tbody tr').removeClass('table-primary');
                $(this).addClass('table-primary');
            });

            // Add global keydown handler for F5
            $(document).on('keydown', function(e) {
                // F5 key
                if (e.which === 116) {
                    e.preventDefault();
                    
                    // Don't do anything if basket is empty
                    if (basket.length === 0) return;
                    
                    // If no item is selected, edit the last item
                    const indexToEdit = selectedBasketIndex >= 0 ? 
                        selectedBasketIndex : 
                        basket.length - 1;
                        
                    const item = basket[indexToEdit];
                    isEditing = true;
                    editingIndex = indexToEdit;

                    selectedPrice = null;
                    selectedPriceType = null;
                    $('.price-select').removeClass('active');
                    $('.selected-price-info').addClass('d-none');
                    $('#addToBasketBtn').prop('disabled', true);
                    
                    $('#modalItemDescription').text(`${item.Description} - ${item.Variants}`);
                    
                    $('.price-select').each(function() {
                        const priceType = $(this).data('price-type');
                        $(this).text(`${priceType}: ${item[priceType]}`);
                    });

                    $('#quantityInput').val(item.Quantity);
                    $('#quantityModal').data('selected-item', item).modal('show');

                    $(`.price-select[data-price-type="${item.PriceType}"]`).click();
                }
            });

            // Add double-click handler for basket entries
            $('#basketTable tbody').on('dblclick', 'tr', function() {
                const index = $(this).index();
                selectedBasketIndex = index;
                
                const basketItem = basket[index];
                const originalItem = inventoryData.find(item => item.ItemID === basketItem.ItemID);
                
                isEditing = true;
                editingIndex = index;

                selectedPrice = null;
                selectedPriceType = null;
                $('.price-select').removeClass('active');
                $('.selected-price-info').addClass('d-none');
                $('#addToBasketBtn').prop('disabled', true);
                
                $('#modalItemDescription').text(`${basketItem.Description} - ${originalItem.Variants}`);
                
                // Update modal image
                $('#modalItemImage').attr('src', `${IMAGE_BASE_URL}${originalItem.Picture}`)
                                   .attr('alt', basketItem.Description)
                                   .one('error', function() {
                                       if (!this.hasAttribute('data-error-handled')) {
                                           this.src = 'placeholder.jpg';
                                           this.setAttribute('data-error-handled', 'true');
                                       }
                                   });
                
                $('.price-select').each(function() {
                    const priceType = $(this).data('price-type');
                    $(this).text(`${priceType}: ${originalItem[priceType]}`);
                });

                $('#quantityInput').val(basketItem.Quantity);
                $('#quantityModal').data('selected-item', originalItem).modal('show');

                $(`.price-select[data-price-type="${basketItem.PriceType}"]`).click();
            });

            // Update the tab switching logic with corrected class handling
            $('#itemsTab').click(function() {
                // Remove all active classes first
                $('#itemsTab, #basketTab').removeClass('btn-primary active').addClass('btn-outline-primary');
                // Add active class to items tab
                $(this).removeClass('btn-outline-primary').addClass('btn-primary active');
                // Show/hide panels
                $('#itemsPanel').addClass('active');
                $('#basketPanel').removeClass('active');
            });

            $('#basketTab').click(function() {
                // Remove all active classes first
                $('#itemsTab, #basketTab').removeClass('btn-primary active').addClass('btn-outline-primary');
                // Add active class to basket tab
                $(this).removeClass('btn-outline-primary').addClass('btn-primary active');
                // Show/hide panels
                $('#basketPanel').addClass('active');
                $('#itemsPanel').removeClass('active');
            });

            // Initialize panels for mobile with corrected classes
            if ($(window).width() <= 768) {
                $('#itemsPanel').addClass('active');
                $('#basketPanel').removeClass('active');
                $('#itemsTab').removeClass('btn-outline-primary').addClass('btn-primary active');
                $('#basketTab').removeClass('btn-primary active').addClass('btn-outline-primary');
            }

            // Add long press handler for basket entries
            $('#basketTable tbody').on('mousedown touchstart', 'tr', function(e) {
                const $row = $(this);
                const index = $row.index();
                
                pressTimer = setTimeout(function() {
                    showDeleteModal(index);
                }, 800); // 800ms for long press
                
                return false; 
            }).on('mouseup mouseleave touchend', function() {
                clearTimeout(pressTimer);
            });

            // Add delete key handler
            $(document).on('keydown', function(e) {
                if (e.which === 46) { // Delete key
                    e.preventDefault();
                    
                    if (selectedBasketIndex >= 0 && selectedBasketIndex < basket.length) {
                        showDeleteModal(selectedBasketIndex);
                    }
                }
            });

            // Add ESC key handler for search focus
            $(document).on('keydown', function(e) {
                // ESC key
                if (e.which === 27) {
                    // Only focus search if we're not in a modal
                    if (!$('.modal.show').length) {
                        e.preventDefault();
                        $('#searchInput').focus();
                    }
                }
            });

            // Ensure search input maintains yellow background while focused
            $('#searchInput')
                .on('focus', function() {
                    $(this).css('background-color', '#ffffd9');
                })
                .on('blur', function() {
                    $(this).css('background-color', '');
                });

            // Update checkout button click handler
            $('#checkoutBtn').click(function() {
                showCheckoutModal();
            });

            // Update keyboard shortcuts
            $(document).on('keydown', function(e) {
                // Handle change display modal keys
                if ($('#changeDisplayModal').hasClass('show')) {
                    // Enter, Escape, or Space
                    if (e.which === 13 || e.which === 27 || e.which === 32) {
                        e.preventDefault();
                        $('#changeDisplayModal').modal('hide');
                        return; // Stop further processing
                    }
                }
                
                // Handle Ctrl+Enter for checkout
                if (e.ctrlKey && e.which === 13) {
                    e.preventDefault();
                    // Only trigger checkout if no modal is open and basket has items
                    if (!$('.modal.show').length && basket.length > 0) {
                        $('#checkoutBtn').click();
                        return;
                    }
                }
            });

            // Fix real-time change calculation
            $('#tenderedAmount').on('input', function() {
                calculateChange();
            });

            /**
             * Calculates change based on tendered amount
             * Logic:
             * 1. Gets total and tendered amounts
             * 2. Calculates difference
             * 3. Updates change display if positive
             */
            function calculateChange() {
                const total = parseFloat($('#totalBill').val()) || 0;
                const tendered = parseFloat($('#tenderedAmount').val()) || 0;
                const change = tendered - total;
                $('#changeAmount').val(change >= 0 ? change.toFixed(2) : '');
            }

            /**
             * Shows checkout modal with payment options
             * Logic:
             * 1. Checks basket contents
             * 2. Resets payment fields
             * 3. Sets default payment method (cash)
             * 4. Shows modal
             * 5. Focuses on tendered amount
             */
            function showCheckoutModal() {
                if (basket.length === 0) {
                    alert('Cannot proceed to checkout: Basket is empty');
                    return;
                }

                const total = parseFloat($('#grandTotal').text());
                
                $('#modalInvoice').text(String(currentInvoice).padStart(4, '0'));
                $('#totalBill').val(total.toFixed(2));
                $('#tenderedAmount').val('');
                $('#changeAmount').val('');
                $('#customerID').val('');
                $('#paymentReference').val('');
                $('#transactionNotes').val('');
                
                // Reset payment method to cash
                $('.payment-select').removeClass('active');
                $('.payment-select[data-payment="cash"]').addClass('active');
                $('#paymentDetails').addClass('d-none');
                $('#tenderedAmount').prop('disabled', false);
                
                $('#checkoutModal').modal('show');
                
                // Focus on tendered amount after modal is shown
                $('#checkoutModal').on('shown.bs.modal', function() {
                    $('#tenderedAmount').focus();
                    $(this).off('shown.bs.modal');
                });
            }

            // Add Enter key handler for save transaction in checkout modal
            $('#checkoutModal').on('keydown', function(e) {
                if (e.which === 13 && !e.ctrlKey) { // Enter without Ctrl
                    e.preventDefault();
                    if (document.activeElement === $('#tenderedAmount')[0]) {
                        saveTransaction();
                    }
                }
            });

            // Add click handler for save transaction button
            $('#saveTransaction').click(function() {
                saveTransaction();
            });

            // Add keyboard handler for payment method selection in checkout modal
            $('#checkoutModal').on('keydown', function(e) {
                // Handle F1, F2, F3 keys
                switch (e.which) {
                    case 112: // F1
                        e.preventDefault();
                        $('.payment-select[data-payment="cash"]').click();
                        break;
                    case 113: // F2
                        e.preventDefault();
                        $('.payment-select[data-payment="card"]').click();
                        break;
                    case 114: // F3
                        e.preventDefault();
                        $('.payment-select[data-payment="others"]').click();
                        break;
                    case 13: // Enter without Ctrl
                        if (!e.ctrlKey && document.activeElement === $('#tenderedAmount')[0]) {
                            e.preventDefault();
                            saveTransaction();
                        }
                        break;
                }
            });

            // Update payment method click handlers
            $('.payment-select').click(function() {
                $('.payment-select').removeClass('active');
                $(this).addClass('active');
                
                const paymentType = $(this).data('payment');
                
                // Show/hide payment reference field based on payment type
                if (paymentType === 'cash') {
                    $('#paymentDetails').addClass('d-none');
                    $('#tenderedAmount').prop('disabled', false).focus();
                } else {
                    $('#paymentDetails').removeClass('d-none');
                    $('#tenderedAmount').prop('disabled', true);
                    $('#paymentReference').focus();
                }
                
                // Clear fields when switching payment methods
                if (paymentType !== 'cash') {
                    $('#tenderedAmount').val('');
                    $('#changeAmount').val('');
                }
            });
        });

        /**
         * Refreshes the items table with larger images and hidden columns
         * Logic:
         * 1. Stores scroll position
         * 2. Updates table with larger images
         * 3. Includes barcode/variants in search but not display
         * 4. Restores scroll position
         */
        function refreshItemsTable() {
            const container = $('#itemsTable').closest('.table-container');
            const scrollPosition = container.scrollTop();
            
            const searchTerms = $('#searchInput').val().toLowerCase().split(' ').filter(term => term.length > 0);
            const tbody = $('#itemsTable tbody');
            tbody.empty();
            
            const filteredItems = inventoryData.filter(item => {
                if (searchTerms.length === 0) {
                    return true;
                }

                const searchableText = (
                    item.Barcode.toLowerCase() + ' ' +
                    item.Description.toLowerCase() + ' ' +
                    item.Variants.toLowerCase()
                );

                return searchTerms.every(term => searchableText.includes(term));
            });

            filteredItems.forEach((item, index) => {
                const isSelected = index === currentTableSelection ? 'table-primary' : '';
                tbody.append(`
                    <tr class="${isSelected}" data-index="${index}">
                        <td>
                            <img src="${IMAGE_BASE_URL}${item.Picture}" 
                                 alt="${item.Description}"
                                 class="img-thumbnail"
                                 onerror="this.src='placeholder.jpg'">
                        </td>
                        <td>${item.Description}</td>
                        <td>${item.P1}</td>
                        <td>${item.P2}</td>
                        <td>${item.P3}</td>
                    </tr>
                `);
            });

            // Restore scroll position
            setTimeout(() => {
                container.scrollTop(scrollPosition);
            }, 0);
        }

        /**
         * Plays audio feedback when basket is updated
         * Logic:
         * 1. Gets beep audio element
         * 2. Resets audio to start
         * 3. Attempts to play with error handling
         */
        function playBeep() {
            const beep = document.getElementById('beepSound');
            beep.currentTime = 0; // Reset the audio to start
            beep.play().catch(function(error) {
                console.log("Beep playback failed:", error);
            });
        }

        /**
         * Updates the basket table display with simplified description
         * Logic:
         * 1. Clears existing basket table
         * 2. Calculates running total
         * 3. Adds each item without price type in description
         * 4. Updates grand total
         */
        function refreshBasketTable() {
            const tbody = $('#basketTable tbody');
            tbody.empty();
            let grandTotal = 0;

            basket.forEach((item, index) => {
                const total = item.Price * item.Quantity;
                grandTotal += total;
                const isSelected = index === selectedBasketIndex ? 'table-primary' : '';
                const textClass = item.Quantity < 0 ? 'text-danger' : '';
                tbody.append(`
                    <tr class="${isSelected}">
                        <td>${item.Description}</td>
                        <td>${item.Price}</td>
                        <td class="${textClass}">${item.Quantity}</td>
                        <td class="${textClass}">${total.toFixed(2)}</td>
                    </tr>
                `);
            });
            
            // Update grand total display with appropriate color
            const grandTotalElement = $('#grandTotal');
            grandTotalElement.text(grandTotal.toFixed(2));
            grandTotalElement.parent().toggleClass('text-danger', grandTotal < 0);
            
            playBeep();
            
            if (selectedBasketIndex >= basket.length) {
                selectedBasketIndex = basket.length - 1;
            }
        }

        /**
         * Highlights the currently selected row in items table
         * Logic:
         * 1. Removes existing highlights
         * 2. Adds highlight to selected row
         * 3. Scrolls to keep selected row visible
         */
        function highlightSelectedRow() {
            const rows = $('#itemsTable tbody tr');
            rows.removeClass('table-primary');
            if (currentTableSelection >= 0) {
                $(rows[currentTableSelection]).addClass('table-primary');
                
                const selectedRow = $(rows[currentTableSelection]);
                const container = $('.table-container');
                const scrollTop = container.scrollTop();
                const rowTop = selectedRow.position().top;
                const containerHeight = container.height();
                
                if (rowTop < 0 || rowTop > containerHeight) {
                    container.scrollTop(scrollTop + rowTop);
                }
            }
        }

        /**
         * Shows delete confirmation modal for basket items
         * Logic:
         * 1. Validates index
         * 2. Gets item details
         * 3. Updates modal content
         * 4. Shows confirmation modal
         */
        function showDeleteModal(index) {
            if (index >= 0 && index < basket.length) {
                deleteIndex = index;
                const item = basket[index];
                
                $('#deleteItemDesc').text(item.Description);
                $('#deleteItemQty').text(item.Quantity);
                
                const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
                deleteModal.show();
            }
        }

        /**
         * Shows JSON representation of transaction (temporary)
         * Logic:
         * 1. Formats transaction JSON
         * 2. Updates modal content
         * 3. Shows modal
         */
        function showJsonDisplay(transaction) {
            $('#jsonDisplay').text(JSON.stringify(transaction, null, 2));
            $('#jsonDisplayModal').modal('show');
        }

        /**
         * Generates transaction JSON with complete item details
         * Logic:
         * 1. Creates transaction object
         * 2. Includes all basket items with barcodes
         * 3. Adds payment and customer details
         */
        function generateTransactionJSON() {
            const total = parseFloat($('#totalBill').val());
            const tendered = parseFloat($('#tenderedAmount').val()) || 0;
            const paymentMethod = $('.payment-select.active').data('payment');
            
            const transaction = {
                InvoiceNumber: String(currentInvoice).padStart(4, '0'),
                DateTime: new Date().toISOString(),
                CashierID: cashierId,
                CustomerID: $('#customerID').val(),
                Items: basket.map(item => ({
                    ItemID: item.ItemID,
                    Barcode: item.Barcode,
                    Description: item.Description,
                    Variants: item.Variants,
                    Price: item.Price,
                    PriceType: item.PriceType,
                    Quantity: item.Quantity,
                    Total: item.Price * item.Quantity
                })),
                Payment: {
                    Method: paymentMethod,
                    Total: total,
                    Tendered: tendered,
                    Change: paymentMethod === 'cash' ? (tendered - total) : 0,
                    Reference: $('#paymentReference').val()
                },
                Notes: $('#transactionNotes').val()
            };
            
            return transaction;
        }

        /**
         * Saves transaction with complete item details
         * Logic:
         * 1. Validates payment
         * 2. Generates transaction JSON
         * 3. Processes transaction
         * 4. Shows receipt
         */
        function saveTransaction() {
            const total = parseFloat($('#totalBill').val());
            const tendered = parseFloat($('#tenderedAmount').val()) || 0;
            const paymentMethod = $('.payment-select.active').data('payment');
            
            if (paymentMethod === 'cash' && tendered < total) {
                alert('Tendered amount must be greater than or equal to total bill for cash payments');
                return;
            }
            
            const transaction = generateTransactionJSON();
            
            $('#checkoutModal').modal('hide');
            
            // Show JSON display first
            showJsonDisplay(transaction);
            
            // After JSON modal, show receipt
            $('#jsonDisplayModal').on('hidden.bs.modal', function() {
                $(this).off('hidden.bs.modal');
                
                // Show receipt
                $('#receiptDisplay').text(generateReceiptString(transaction));
                $('#receiptDisplayModal').modal('show');
                
                // After receipt modal, show change if needed
                $('#receiptDisplayModal').on('hidden.bs.modal', function() {
                    $(this).off('hidden.bs.modal');
                    
                    if (transaction.Payment.Method === 'cash' && transaction.Payment.Change > 0) {
                        $('#changeDisplayAmount').text(transaction.Payment.Change.toFixed(2));
                        $('#changeDisplayModal').modal('show')
                            .on('hidden.bs.modal', function() {
                                $(this).off('hidden.bs.modal');
                                completeTransaction();
                            });
                    } else {
                        completeTransaction();
                    }
                });
            });
        }

        /**
         * Completes the transaction and resets the system
         * Logic:
         * 1. Increments invoice number
         * 2. Clears basket
         * 3. Updates displays
         * 4. Focuses on search
         */
        function completeTransaction() {
            // Increment invoice number and reset basket
            currentInvoice++;
            $('#currentInvoice').text(String(currentInvoice).padStart(4, '0'));
            basket = [];
            refreshBasketTable();
            // Focus on search input
            $('#searchInput').focus();
        }

        // Update change modal to ensure proper keyboard handling
        $('#changeDisplayModal').modal({
            keyboard: true,
            backdrop: true
        });

        /**
         * Generates formatted receipt string
         * Logic:
         * 1. Sets column widths
         * 2. Formats header
         * 3. Formats items with wrapping
         * 4. Adds totals and notes
         */
        function generateReceiptString(transaction) {
            const WIDTH = 45;
            const QTY_WIDTH = 10;
            const TOTAL_WIDTH = 10;
            const ITEM_WIDTH = WIDTH - QTY_WIDTH - TOTAL_WIDTH - 2; // -2 for separators
            
            // Helper function to pad strings
            function pad(str, width, char = ' ') {
                return str.toString().padStart(width, char);
            }
            
            // Helper function to pad right
            function padRight(str, width, char = ' ') {
                return str.toString().padEnd(width, char);
            }
            
            // Helper function to format number with 2 decimals
            function formatNumber(num) {
                return num.toFixed(2);
            }
            
            // Helper function to wrap text to width
            function wrapText(text, width) {
                const words = text.split(' ');
                const lines = [];
                let currentLine = '';
                
                words.forEach(word => {
                    if ((currentLine + ' ' + word).length <= width) {
                        currentLine += (currentLine ? ' ' : '') + word;
                    } else {
                        if (currentLine) lines.push(currentLine);
                        currentLine = word;
                    }
                });
                if (currentLine) lines.push(currentLine);
                
                return lines;
            }
            
            // Build receipt
            let receipt = [];
            
            // Header
            receipt.push(''.padEnd(WIDTH, '='));
            receipt.push(`Invoice number: ${transaction.InvoiceNumber}`);
            receipt.push(`Date:           ${new Date(transaction.DateTime).toLocaleDateString()}`);
            receipt.push(`Customer ID:    ${transaction.CustomerID || 'N/A'}`);
            receipt.push(''.padEnd(WIDTH, '='));
            
            // Column headers
            receipt.push(`${padRight('QTY', QTY_WIDTH)}|${padRight('ITEM - Price', ITEM_WIDTH)}|${padRight('Total', TOTAL_WIDTH)}`);
            receipt.push(''.padEnd(WIDTH, '-'));
            
            // Items
            transaction.Items.forEach(item => {
                const qty = formatNumber(item.Quantity);
                const total = formatNumber(item.Price * item.Quantity);
                const itemText = `${item.Description} [${item.Barcode}] @ ${formatNumber(item.Price)}`;
                const wrappedText = wrapText(itemText, ITEM_WIDTH);
                
                // First line with quantity and total
                receipt.push(
                    `${padRight(qty, QTY_WIDTH)}|${padRight(wrappedText[0], ITEM_WIDTH)}|${padRight(total, TOTAL_WIDTH)}`
                );
                
                // Continuation lines if any
                for (let i = 1; i < wrappedText.length; i++) {
                    receipt.push(
                        `${padRight('', QTY_WIDTH)}|${padRight(wrappedText[i], ITEM_WIDTH)}|${padRight('', TOTAL_WIDTH)}`
                    );
                }
            });
            
            receipt.push(''.padEnd(WIDTH, '-'));
            
            // Totals
            const payment = transaction.Payment;
            receipt.push(`Total:    ${padRight(formatNumber(payment.Total), WIDTH - 8)}`);
            if (payment.Method === 'cash') {
                receipt.push(`Tendered: ${padRight(formatNumber(payment.Tendered), WIDTH - 9)}`);
                receipt.push(`Change:   ${padRight(formatNumber(payment.Change), WIDTH - 8)}`);
            } else {
                receipt.push(`Payment:  ${padRight(payment.Method.toUpperCase(), WIDTH - 9)}`);
                receipt.push(`Ref:      ${padRight(payment.Reference || 'N/A', WIDTH - 9)}`);
            }
            
            // Notes
            if (transaction.Notes) {
                receipt.push('');
                receipt.push('Notes:');
                receipt.push(transaction.Notes);
            }
            
            return receipt.join('\n');
        }
    </script>
</body>
</html>