<script src="<?= APP_URL ?>/assets/js/html5-qrcode.min.js"></script>
<div class="pos-wrapper" style="margin: -24px; background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%); height: calc(100vh - 64px); display: grid; grid-template-columns: 420px 1fr; gap: 0; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; overflow: hidden; box-shadow: inset 0 0 100px rgba(0, 0, 0, 0.1);">

    <!-- LEFT: Transaction Panel -->
    <div class="pos-left-panel" style="background: linear-gradient(180deg, rgba(255, 255, 255, 0.98) 0%, rgba(249, 250, 251, 0.95) 100%); backdrop-filter: blur(20px); display: flex; flex-direction: column; border-right: 1px solid rgba(255, 255, 255, 0.3); box-shadow: 8px 0 32px rgba(0, 0, 0, 0.15), 4px 0 16px rgba(102, 126, 234, 0.1); position: relative; z-index: 5; height: 100%; overflow: hidden;">

        <!-- Header with Customer -->
        <div class="pos-left-header" style="padding: 12px 16px; border-bottom: 1px solid rgba(0, 0, 0, 0.08); background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));">
            <div style="display: flex; justify-content: flex-end; align-items: center; gap: 12px; margin-bottom: 10px;">
                <a href="<?= APP_URL ?>/logout" style="color: #ef4444; text-decoration: none; font-size: 0.85rem; font-weight: 600; padding: 6px 12px; border-radius: 8px; transition: all 0.2s; background: rgba(239, 68, 68, 0.1);">Logout</a>
                <a href="<?= APP_URL ?>/sales" style="color: #6b7280; text-decoration: none; font-size: 0.85rem; font-weight: 600; padding: 6px 12px; border-radius: 8px; transition: all 0.2s; background: rgba(107, 114, 128, 0.1);">Exit</a>
            </div>

            <div style="display: flex; gap: 8px;">
                <div style="flex: 1; display: flex; gap: 6px;">
                    <select id="pos-customer" style="flex: 1; padding: 6px 10px; border: 2px solid rgba(0, 0, 0, 0.1); border-radius: 10px; font-size: 0.85rem; background: #fff; font-weight: 500; color: #374151; transition: all 0.2s; cursor: pointer;">
                        <option value="">Select Customer</option>
                        <?php foreach ($customers as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= e($c['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" onclick="showAddCustomerModal()" style="padding: 6px 10px; border: 2px solid rgba(34, 197, 94, 0.3); background: rgba(34, 197, 94, 0.1); border-radius: 10px; font-size: 1.1rem; cursor: pointer; transition: all 0.2s; color: #22c55e; font-weight: 700;">+</button>
                </div>
                <div style="width: 120px;">
                    <select id="pos-location" style="width: 100%; padding: 6px 10px; border: 2px solid rgba(0, 0, 0, 0.1); border-radius: 10px; font-size: 0.85rem; background: #fff; font-weight: 500; color: #374151; transition: all 0.2s; cursor: pointer;">
                        <?php foreach ($locations as $loc): ?>
                            <option value="<?= $loc['id'] ?>" <?= ($defaultLocationId ?? '') == $loc['id'] || !empty($loc['is_default']) ? 'selected' : '' ?>><?= e($loc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- Cart Table -->
        <div class="pos-cart-table" style="flex: 1; overflow-y: auto; padding: 0; min-height: 200px; position: relative; z-index: 1;">
            <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">
                <thead style="position: sticky; top: 0; background: rgba(249, 250, 251, 0.95); backdrop-filter: blur(10px); z-index: 10;">
                    <tr style="border-bottom: 2px solid rgba(0, 0, 0, 0.08);">
                        <th style="padding: 14px 16px; text-align: left; font-weight: 700; color: #374151; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em;">Product</th>
                        <th style="padding: 14px 16px; text-align: center; font-weight: 700; color: #374151; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; width: 70px;">Qty</th>
                        <th style="padding: 14px 16px; text-align: right; font-weight: 700; color: #374151; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; width: 90px;">Price</th>
                        <th style="padding: 14px 16px; text-align: right; font-weight: 700; color: #374151; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; width: 90px;">Subtotal</th>
                        <th style="padding: 14px 16px; text-align: center; font-weight: 700; color: #374151; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; width: 50px;"></th>
                    </tr>
                </thead>
                <tbody id="cart-items">
                    <tr>
                        <td colspan="5" style="padding: 60px 20px; text-align: center; color: #9ca3af;">
                            <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px; opacity: 0.4;"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
                            <p style="margin: 0; font-weight: 500; font-size: 0.9rem;">No items in cart</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Summary Section -->
        <div class="pos-summary" style="padding: 8px 12px; background: linear-gradient(135deg, rgba(249, 250, 251, 0.98) 0%, rgba(243, 244, 246, 0.95) 100%); backdrop-filter: blur(10px); border-top: 1px solid rgba(0, 0, 0, 0.08); flex-shrink: 0; box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; font-size: 0.85rem; margin-bottom: 6px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #6b7280; font-weight: 500;">Items:</span>
                    <span id="pos-items-count" style="font-weight: 700; color: #111827; font-size: 1rem;">0</span>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #6b7280; font-weight: 500;">Total:</span>
                    <span id="pos-subtotal" style="font-weight: 700; color: #111827; font-size: 1rem;"><?= $currencySymbol ?? 'GH₵' ?>0.00</span>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
                <span style="color: #6b7280; font-weight: 500;">Discount:</span>
                <input type="number" id="pos-discount-input" value="0" min="0" step="0.01" style="width: 70px; padding: 4px 8px; border: 2px solid rgba(0, 0, 0, 0.1); border-radius: 8px; font-size: 0.85rem; text-align: right; font-weight: 600; color: #374151; background: #fff; transition: all 0.2s;">
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
                <span style="color: #6b7280; font-weight: 500;">Order Tax:</span>
                <input type="number" id="pos-tax-input" value="0" min="0" step="0.01" readonly style="width: 70px; padding: 4px 8px; border: 2px solid rgba(0, 0, 0, 0.05); border-radius: 8px; font-size: 0.85rem; text-align: right; font-weight: 600; color: #9ca3af; background: rgba(249, 250, 251, 0.8);">
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; grid-column: 1/-1;">
                <span style="color: #6b7280; font-weight: 500;">Shipping:</span>
                <input type="number" id="pos-shipping-input" value="0" min="0" step="0.01" style="width: 70px; padding: 4px 8px; border: 2px solid rgba(0, 0, 0, 0.1); border-radius: 8px; font-size: 0.85rem; text-align: right; font-weight: 600; color: #374151; background: #fff; transition: all 0.2s;">
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="pos-actions" style="padding: 8px 12px; background: linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(249, 250, 251, 0.95) 100%); backdrop-filter: blur(20px); border-top: 1px solid rgba(0, 0, 0, 0.08); flex-shrink: 0; box-shadow: 0 -4px 24px rgba(0, 0, 0, 0.08);">
            <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 6px; margin-bottom: 6px;">
                <button id="btn-suspend" class="pos-action-btn" style="padding: 8px; border: 2px solid rgba(59, 130, 246, 0.3); background: rgba(59, 130, 246, 0.1); border-radius: 10px; font-size: 0.8rem; font-weight: 600; cursor: pointer; transition: all 0.2s; color: #3b82f6;">Suspend</button>
                <button id="btn-multiple" class="pos-action-btn" style="padding: 8px; border: 2px solid rgba(168, 85, 247, 0.3); background: rgba(168, 85, 247, 0.1); border-radius: 10px; font-size: 0.85rem; font-weight: 700; color: #a855f7; cursor: pointer; transition: all 0.2s;">Multiple Pay</button>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 6px;">
                <button id="clear-cart" class="pos-action-btn danger" style="padding: 8px; border: 2px solid rgba(239, 68, 68, 0.3); background: rgba(239, 68, 68, 0.1); color: #ef4444; border-radius: 10px; font-size: 0.8rem; font-weight: 600; cursor: pointer; transition: all 0.2s;">Cancel</button>
                <button id="btn-checkout" class="pos-action-btn primary" disabled style="padding: 10px; border: none; background: linear-gradient(135deg, #22c55e, #16a34a); color: #fff; border-radius: 10px; font-size: 0.95rem; font-weight: 700; cursor: pointer; transition: all 0.2s; box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);">Cash</button>
            </div>
        </div>
    </div>
</div>

<!-- RIGHT: Product Selection -->
<div class="pos-right-panel" style="display: flex; flex-direction: column; padding: 0; background: linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.2) 100%); backdrop-filter: blur(10px); height: 100%; overflow: hidden; box-shadow: inset 0 0 60px rgba(0, 0, 0, 0.05);">

    <!-- Top Bar -->
    <div class="pos-bottom-bar" style="position: sticky; top: 0; z-index: 10; width: 100%; padding: 20px 28px; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(20px); border-bottom: 1px solid rgba(255, 255, 255, 0.3); display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);">
        <div style="display: flex; align-items: center; gap: 12px;">
            <span style="font-size: 0.9rem; color: #6b7280; font-weight: 600;">Total Payable:</span>
            <span id="pos-total-payable" style="font-size: 1.5rem; font-weight: 800; background: linear-gradient(135deg, #22c55e, #16a34a); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;"><?= $currencySymbol ?? 'GH₵' ?>0.00</span>
        </div>
            <div style="display: flex; gap: 8px;">
                <button class="pos-suspended-btn" style="padding: 6px 10px; border: 2px solid rgba(59, 130, 246, 0.3); background: rgba(59, 130, 246, 0.1); border-radius: 10px; font-size: 0.75rem; font-weight: 600; cursor: pointer; transition: all 0.2s; color: #3b82f6;">Suspended Orders</button>
                <button class="pos-recent-btn" style="padding: 6px 10px; border: 2px solid rgba(168, 85, 247, 0.3); background: rgba(168, 85, 247, 0.1); border-radius: 10px; font-size: 0.75rem; font-weight: 600; cursor: pointer; transition: all 0.2s; color: #a855f7;">Recent Transactions</button>
            </div>
        </div>

        <!-- Search Bar -->
        <div style="margin-bottom: 20px; padding: 20px 28px 0;">
            <div style="display: flex; align-items: center; gap: 12px;">
                <div style="position: relative; flex: 1;">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: #9ca3af;"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                    <input type="text" id="pos-search" placeholder="Search products by name, SKU, or barcode..." style="width: 100%; padding: 14px 16px 14px 48px; border: 2px solid rgba(0, 0, 0, 0.1); border-radius: 12px; font-size: 0.95rem; outline: none; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); font-weight: 500; color: #374151; transition: all 0.2s;" autofocus>
                </div>
                <button type="button" id="scan-button" style="padding: 14px 24px; border: none; background: #22c55e; border-radius: 12px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 0.9rem; font-weight: 700; color: #fff; white-space: nowrap; transition: all 0.2s; box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
                    Scan Items
                </button>

            </div>
        </div>

        <!-- Category & Brand Filters -->
        <div style="display: flex; gap: 12px; margin-bottom: 20px; padding: 0 28px;">
            <select id="pos-category" style="flex: 1; padding: 12px 16px; border: 2px solid rgba(0, 0, 0, 0.1); border-radius: 10px; font-size: 0.85rem; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); font-weight: 500; color: #374151; cursor: pointer; transition: all 0.2s;">
                <option value="">All Categories</option>
                <?php
                $categories = \Category::active();
                foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>"><?= e($cat['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <select id="pos-brand" style="flex: 1; padding: 12px 16px; border: 2px solid rgba(0, 0, 0, 0.1); border-radius: 10px; font-size: 0.85rem; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); font-weight: 500; color: #374151; cursor: pointer; transition: all 0.2s;">
                <option value="">All Brands</option>
                <?php
                $brands = \Brand::active();
                foreach ($brands as $brand): ?>
                    <option value="<?= $brand['id'] ?>"><?= e($brand['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Product Grid -->
        <div id="pos-results" class="product-grid" style="flex: 1; overflow-y: auto; display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; padding: 0 28px 28px; min-height: 0;">
            <div class="empty-state" style="grid-column: 1/-1; text-align: center; padding: 80px 20px; color: #9ca3af;">
                <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 16px; opacity: 0.3;"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path></svg>
                <p style="margin: 0; font-size: 0.9rem;">Loading products...</p>
            </div>
        </div>
    </div>
</div>

<!-- Add Customer Modal -->
<div class="modal-overlay" id="addCustomerModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 99999 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 400px; max-width: 90%; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Add New Customer</h3>
            <button class="modal-close" onclick="hideAddCustomerModal()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <form id="addCustomerForm" onsubmit="addCustomer(event)">
            <div class="modal-body" style="padding: 16px;">
                <div class="form-group" style="margin-bottom: 12px;">
                    <label class="form-label" style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">Name *</label>
                    <input type="text" name="name" class="form-input" required style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9rem;">
                </div>
                <div class="form-group" style="margin-bottom: 12px;">
                    <label class="form-label" style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">Phone</label>
                    <input type="text" name="phone" class="form-input" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9rem;">
                </div>
                <div class="form-group" style="margin-bottom: 12px;">
                    <label class="form-label" style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">Email</label>
                    <input type="email" name="email" class="form-input" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9rem;">
                </div>
                <div class="form-group" style="margin-bottom: 12px;">
                    <label class="form-label" style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">Address</label>
                    <textarea name="address" class="form-input" rows="2" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9rem;"></textarea>
                </div>
            </div>
            <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: flex-end; gap: 8px;">
                <button type="button" class="btn btn-ghost" onclick="hideAddCustomerModal()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer;">Cancel</button>
                <button type="submit" class="btn btn-primary" style="padding: 8px 16px; border: none; background: #28a745; color: #fff; border-radius: 6px; cursor: pointer;">Add Customer</button>
            </div>
        </form>
    </div>
</div>

<!-- Cash Payment Modal -->
<div class="modal-overlay" id="cashPaymentModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); align-items: center; justify-content: center; z-index: 99999; pointer-events: none;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 400px; max-width: 90%; box-shadow: 0 4px 12px rgba(0,0,0,0.15); pointer-events: auto;">
        <div class="modal-header" style="padding: 12px 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1rem; font-weight: 700;">Cash Payment</h3>
            <button class="modal-close" onclick="hideCashPaymentModal()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>

        <div class="modal-body" style="padding: 16px;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;">
                <div style="padding: 10px; background: #f9f9f9; border-radius: 6px;">
                    <div style="font-size: 0.75rem; color: #666; margin-bottom: 4px;">Total Payable</div>
                    <div id="modal-total-payable" style="font-size: 1.2rem; font-weight: 700; color: #28a745;"><?= $currencySymbol ?? 'GH₵' ?>0.00</div>
                </div>
                <div style="padding: 10px; background: #e8f5e9; border-radius: 6px; border: 1px solid #c8e6c9;">
                    <div style="font-size: 0.75rem; color: #2e7d32; margin-bottom: 4px; font-weight: 600;">Change Due</div>
                    <div id="change-due" style="font-size: 1.2rem; font-weight: 700; color: #2e7d32;"><?= $currencySymbol ?? 'GH₵' ?>0.00</div>
                </div>
            </div>
            
            <div class="form-group" style="margin-bottom: 12px;">
                <label class="form-label" style="display: block; margin-bottom: 6px; font-size: 0.85rem; font-weight: 600;">Amount Received</label>
                <input type="number" id="amount-received" class="form-input" step="0.01" min="0" placeholder="0.00" style="width: 100%; padding: 10px 12px; border: 2px solid #ddd; border-radius: 6px; font-size: 1rem; text-align: right; font-weight: 600;" oninput="calculateChange()">
            </div>

            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 12px;">
                <button type="button" onclick="setQuickAmount(10)" style="padding: 6px; border: 1px solid #ddd; background: #fff; border-radius: 4px; font-size: 0.8rem; cursor: pointer;">+10</button>
                <button type="button" onclick="setQuickAmount(20)" style="padding: 6px; border: 1px solid #ddd; background: #fff; border-radius: 4px; font-size: 0.8rem; cursor: pointer;">+20</button>
                <button type="button" onclick="setQuickAmount(50)" style="padding: 6px; border: 1px solid #ddd; background: #fff; border-radius: 4px; font-size: 0.8rem; cursor: pointer;">+50</button>
                <button type="button" onclick="setQuickAmount(100)" style="padding: 6px; border: 1px solid #ddd; background: #fff; border-radius: 4px; font-size: 0.8rem; cursor: pointer;">+100</button>
                <button type="button" onclick="setExactAmount()" style="padding: 6px; border: 1px solid #28a745; background: #28a745; color: #fff; border-radius: 4px; font-size: 0.8rem; cursor: pointer; grid-column: span 2;">Exact</button>
                <button type="button" onclick="clearAmountReceived()" style="padding: 6px; border: 1px solid #dc3545; background: #fff; color: #dc3545; border-radius: 4px; font-size: 0.8rem; cursor: pointer; grid-column: span 2;">Clear</button>
            </div>
        </div>
        <div class="modal-footer" style="padding: 12px 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: flex-end; gap: 8px;">
            <button type="button" class="btn btn-ghost" onclick="hideCashPaymentModal()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.85rem;">Cancel</button>
            <button type="button" id="btn-confirm-payment" class="btn btn-primary" onclick="confirmCashPayment()" disabled style="padding: 8px 20px; border: none; background: #28a745; color: #fff; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 600; opacity: 0.5;">Complete Payment</button>
        </div>
    </div>
</div>

<!-- Barcode Scanner Modal -->
<div class="modal-overlay" id="barcodeScannerModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 99999 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 500px; max-width: 95%; max-height: 90vh; box-shadow: 0 4px 12px rgba(0,0,0,0.15); display: flex; flex-direction: column;">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Scan Barcode</h3>
            <button class="modal-close" onclick="closeBarcodeScanner()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <div class="modal-body" style="padding: 16px; flex: 1; overflow-y: auto; display: flex; flex-direction: column; align-items: center;">
            <div id="scanner-container" style="width: 100%; height: 300px; background: #000; border-radius: 8px; overflow: hidden; position: relative;"></div>
            <div id="scanner-status" style="margin-top: 12px; font-size: 0.9rem; color: #666;">Initializing camera...</div>
            <div id="scanned-result" style="margin-top: 8px; font-size: 1rem; font-weight: 600; color: #28a745; display: none;"></div>
        </div>
        <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <button type="button" onclick="closeBarcodeScanner()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Cancel</button>
            <button type="button" id="btn-manual-barcode" onclick="showManualBarcodeInput()" style="padding: 8px 16px; border: 1px solid #007bff; background: #fff; color: #007bff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Enter Manually</button>
        </div>
    </div>
</div>

<!-- Manual Barcode Input Modal -->
<div class="modal-overlay" id="manualBarcodeModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 100000 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 400px; max-width: 90%; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Enter Barcode</h3>
            <button class="modal-close" onclick="hideManualBarcodeInput()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <div class="modal-body" style="padding: 16px;">
            <div class="form-group" style="margin-bottom: 12px;">
                <label class="form-label" style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">Barcode / SKU</label>
                <input type="text" id="manual-barcode-input" class="form-control" placeholder="Enter barcode or SKU..." style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9rem;" autofocus>
            </div>
        </div>
        <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: flex-end; gap: 8px;">
            <button type="button" onclick="hideManualBarcodeInput()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Cancel</button>
            <button type="button" onclick="submitManualBarcode()" style="padding: 8px 16px; border: none; background: #28a745; color: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Add Product</button>
        </div>
    </div>
</div>

<!-- Multiple Payment Modal -->
<div class="modal-overlay" id="multiplePaymentModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 99999 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 500px; max-width: 95%; max-height: 90vh; box-shadow: 0 4px 12px rgba(0,0,0,0.15); display: flex; flex-direction: column;">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Split Payment</h3>
            <button class="modal-close" onclick="hideMultiplePaymentModal()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <div class="modal-body" style="padding: 16px; flex: 1; overflow-y: auto;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px;">
                <div style="padding: 12px; background: #f9f9f9; border-radius: 6px;">
                    <div style="font-size: 0.75rem; color: #666; margin-bottom: 4px;">Total Payable</div>
                    <div id="multiple-total-payable" style="font-size: 1.4rem; font-weight: 700; color: #28a745;"><?= $currencySymbol ?? 'GH₵' ?>0.00</div>
                </div>
                <div style="padding: 12px; background: #e8f5e9; border-radius: 6px; border: 1px solid #c8e6c9;">
                    <div style="font-size: 0.75rem; color: #2e7d32; margin-bottom: 4px; font-weight: 600;">Remaining</div>
                    <div id="multiple-remaining" style="font-size: 1.4rem; font-weight: 700; color: #dc3545;"><?= $currencySymbol ?? 'GH₵' ?>0.00</div>
                </div>
            </div>

            <div id="payment-methods-container" style="margin-bottom: 12px;">
                <!-- Payment method rows will be added here -->
            </div>

            <button type="button" onclick="addPaymentMethodRow()" style="width: 100%; padding: 8px; border: 1px dashed #007bff; background: #f0f8ff; border-radius: 6px; cursor: pointer; font-size: 0.85rem; color: #007bff; display: flex; align-items: center; justify-content: center; gap: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="12" y1="5" x2="12" y2="19"></line>
                    <line x1="5" y1="12" x2="19" y2="12"></line>
                </svg>
                Add Payment Method
            </button>
        </div>
        <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: flex-end; gap: 8px;">
            <button type="button" onclick="hideMultiplePaymentModal()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.85rem;">Cancel</button>
            <button type="button" id="btn-confirm-multiple-payment" disabled style="padding: 8px 20px; border: none; background: #28a745; color: #fff; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 600; opacity: 0.5;">Complete Payment</button>
        </div>
    </div>
</div>

<!-- Suspended Orders Modal -->
<div class="modal-overlay" id="suspendedOrdersModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 99999 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 500px; max-width: 95%; max-height: 90vh; box-shadow: 0 4px 12px rgba(0,0,0,0.15); display: flex; flex-direction: column;">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Suspended Orders</h3>
            <button class="modal-close" onclick="hideSuspendedOrdersModal()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <div class="modal-body" style="padding: 16px; flex: 1; overflow-y: auto;">
            <div id="suspended-orders-list" style="display: flex; flex-direction: column; gap: 8px;">
                <!-- Suspended orders will be loaded here -->
            </div>
            <div id="no-suspended-orders" style="text-align: center; padding: 40px; color: #999; display: none;">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px; opacity: 0.3;"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                <p style="margin: 0;">No suspended orders</p>
            </div>
        </div>
        <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: flex-end;">
            <button type="button" onclick="hideSuspendedOrdersModal()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Close</button>
        </div>
    </div>
</div>

<!-- Recent Transactions Modal -->
<div class="modal-overlay" id="recentTransactionsModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 99999 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 500px; max-width: 95%; max-height: 90vh; box-shadow: 0 4px 12px rgba(0,0,0,0.15); display: flex; flex-direction: column;">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Recent Transactions</h3>
            <button class="modal-close" onclick="hideRecentTransactionsModal()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <div class="modal-body" style="padding: 16px; flex: 1; overflow-y: auto;">
            <div id="recent-transactions-list" style="display: flex; flex-direction: column; gap: 8px;">
                <!-- Recent transactions will be loaded here -->
            </div>
            <div id="no-recent-transactions" style="text-align: center; padding: 40px; color: #999; display: none;">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px; opacity: 0.3;"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                <p style="margin: 0;">No recent transactions</p>
            </div>
        </div>
        <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: flex-end;">
            <button type="button" onclick="hideRecentTransactionsModal()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Close</button>
        </div>
    </div>
</div>

<style>
.modal-overlay button:hover {
    opacity: 0.8;
}

.modal-overlay button:disabled {
    opacity: 0.5 !important;
    cursor: not-allowed;
}

.modal {
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

.modal-header {
    padding: 24px 28px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.03), rgba(118, 75, 162, 0.03));
}

.modal-title {
    margin: 0;
    font-size: 1.25rem;
    font-weight: 700;
    color: #111827;
}

.modal-close {
    background: rgba(239, 68, 68, 0.1);
    border: none;
    cursor: pointer;
    padding: 8px;
    border-radius: 8px;
    color: #ef4444;
    transition: all 0.2s;
}

.modal-close:hover {
    background: rgba(239, 68, 68, 0.2);
    transform: rotate(90deg);
}

.modal-body {
    padding: 24px 28px;
    flex: 1;
    overflow-y: auto;
}

.modal-footer {
    padding: 20px 28px;
    border-top: 1px solid rgba(0, 0, 0, 0.08);
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background: rgba(249, 250, 251, 0.5);
}

.modal-footer button {
    padding: 10px 20px;
    border: 2px solid rgba(0, 0, 0, 0.1);
    background: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
    cursor: pointer;
    font-size: 0.9rem;
    font-weight: 600;
    color: #374151;
    transition: all 0.2s;
}

.modal-footer button:hover {
    background: rgba(249, 250, 251, 0.8);
    transform: translateY(-1px);
}

.modal-footer button.primary {
    background: linear-gradient(135deg, #22c55e, #16a34a);
    color: #fff;
    border: none;
}

.modal-footer button.primary:hover {
    background: linear-gradient(135deg, #16a34a, #15803d);
    box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);
}

.product-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    align-items: start;
}

.product-card {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(249, 250, 251, 0.95) 100%);
    backdrop-filter: blur(10px);
    border: 2px solid rgba(255, 255, 255, 0.4);
    border-radius: 16px;
    padding: 8px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    display: flex;
    flex-direction: column;
    gap: 4px;
    position: relative;
    z-index: 1;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
}
.product-card:hover {
    transform: translateY(-4px) scale(1.02);
    box-shadow: 0 16px 32px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.08);
    border-color: rgba(34, 197, 94, 0.5);
    background: linear-gradient(135deg, rgba(255, 255, 255, 1) 0%, rgba(249, 250, 251, 0.98) 100%);
}

/* Out of Stock Polish */
.product-card.out-of-stock {
    filter: grayscale(1) blur(1px);
    opacity: 0.4;
    cursor: not-allowed;
    position: relative;
    overflow: hidden;
    pointer-events: none;
    background: rgba(239, 68, 68, 0.05);
    border-color: rgba(239, 68, 68, 0.2);
}

.product-card.out-of-stock::after {
    content: 'OUT OF STOCK';
    position: absolute;
    inset: 0;
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 0.8rem;
    letter-spacing: 0.05em;
    z-index: 20;
    text-align: center;
    backdrop-filter: blur(2px);
}

.product-image {
    width: 100%;
    height: 80px;
    object-fit: contain;
    background: linear-gradient(135deg, rgba(249, 250, 251, 0.5), rgba(243, 244, 246, 0.5));
    border-radius: 12px;
    padding: 12px;
    margin-bottom: 8px;
}

.product-name {
    font-size: 0.85rem;
    font-weight: 700;
    color: #1f2937;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.product-sku {
    font-size: 0.75rem;
    color: #9ca3af;
    font-weight: 500;
}

.product-price-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: auto;
    padding-top: 8px;
}

.product-price {
    font-size: 0.95rem;
    font-weight: 800;
    background: linear-gradient(135deg, #22c55e, #16a34a);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.product-stock {
    font-size: 0.7rem;
    color: #6b7280;
    background: rgba(249, 250, 251, 0.8);
    padding: 4px 10px;
    border-radius: 20px;
    font-weight: 600;
}

.product-stock.low {
    background: rgba(251, 191, 36, 0.15);
    color: #d97706;
}

.pos-action-btn:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: translateY(-1px);
}

.pos-action-btn.primary:hover {
    background: linear-gradient(135deg, #16a34a, #15803d);
    box-shadow: 0 6px 16px rgba(34, 197, 94, 0.4);
}

.pos-action-btn.danger:hover {
    background: rgba(239, 68, 68, 0.2) !important;
    transform: translateY(-1px);
}

.pos-recent-btn:hover {
    background: rgba(168, 85, 247, 0.2);
    transform: translateY(-1px);
}

.pos-suspended-btn:hover {
    background: rgba(59, 130, 246, 0.2);
    transform: translateY(-1px);
}

.cart-table-row {
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    transition: all 0.2s;
}
.cart-table-row:hover {
    background: rgba(249, 250, 251, 0.5);
}

.qty-input {
    width: 60px;
    padding: 6px 8px;
    border: 2px solid rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    text-align: center;
    font-size: 0.85rem;
    font-weight: 600;
    color: #374151;
    background: rgba(255, 255, 255, 0.95);
    transition: all 0.2s;
}

.qty-input:focus {
    outline: none;
    border-color: rgba(34, 197, 94, 0.5);
    box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);
}

.btn-remove-item {
    border: none;
    background: rgba(239, 68, 68, 0.1);
    color: #ef4444;
    cursor: pointer;
    font-size: 1.1rem;
    padding: 6px;
    border-radius: 6px;
    transition: all 0.2s;
}

.btn-remove-item:hover {
    background: rgba(239, 68, 68, 0.2);
    transform: scale(1.1);
}

.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: #fff;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* Responsive styles for small screens */
@media (max-width: 1024px) {
    /* Add any other small screen styles here, removed cart-table height constraints */
}
</style>

<script>
const CONFIG = {
    url: '<?= APP_URL ?>',
    currency: '<?= $currencySymbol ?? "GH₵" ?>',
    taxRate: <?= $defaultTaxRate ?? 0 ?>,
    taxEnabled: <?= $taxEnabled ?? 0 ?>,
    allowOverselling: <?= isOversellingAllowed() ? 'true' : 'false' ?>
};

// Barcode Scanner Functions
let html5QrCode = null;
let isScanning = false;

function openBarcodeScanner() {
    console.log('openBarcodeScanner called');
    const modal = document.getElementById('barcodeScannerModal');
    if (modal) {
        modal.classList.add('show');
        document.getElementById('scanned-result').style.display = 'none';
        console.log('Starting scanner...');
        startCamera();
    } else {
        console.error('Scanner modal not found');
        alert('Scanner modal not found');
    }
}

function closeBarcodeScanner() {
    console.log('closeBarcodeScanner called');
    if (html5QrCode && isScanning) {
        html5QrCode.stop().then(() => {
            isScanning = false;
            document.getElementById('barcodeScannerModal').classList.remove('show');
        }).catch(err => {
            console.error('Failed to stop scanner:', err);
            document.getElementById('barcodeScannerModal').classList.remove('show');
        });
    } else {
        document.getElementById('barcodeScannerModal').classList.remove('show');
    }
}

function showManualBarcodeInput() {
    closeBarcodeScanner();
    const modal = document.getElementById('manualBarcodeModal');
    modal.classList.add('show');
    setTimeout(() => document.getElementById('manual-barcode-input').focus(), 100);
}

function hideManualBarcodeInput() {
    const modal = document.getElementById('manualBarcodeModal');
    modal.classList.remove('show');
    document.getElementById('manual-barcode-input').value = '';
}

function submitManualBarcode() {
    const barcode = document.getElementById('manual-barcode-input').value.trim();
    if (barcode) {
        handleScannedBarcode(barcode);
        hideManualBarcodeInput();
    }
}

async function startCamera() {
    console.log('startCamera called, isScanning:', isScanning);
    if (isScanning) return;

    function checkLibrary(retryCount = 0) {
        console.log('Checking for Html5Qrcode, attempt:', retryCount + 1);
        if (typeof Html5Qrcode !== 'undefined') {
            console.log('Html5Qrcode is available, starting scanner');
            html5QrCode = new Html5Qrcode("scanner-container");

            console.log('Html5QrcodeSupportedFormats available:', typeof Html5QrcodeSupportedFormats !== 'undefined');

            const config = {
                fps: 10,
                qrbox: { width: 250, height: 150 },
                aspectRatio: 1.777,
                disableFlip: false,
                experimentalFeatures: {
                    useBarCodeDetectorIfSupported: true
                }
            };

            if (typeof Html5QrcodeSupportedFormats !== 'undefined') {
                config.formatsToSupport = [
                    Html5QrcodeSupportedFormats.CODE_128,
                    Html5QrcodeSupportedFormats.EAN_13,
                    Html5QrcodeSupportedFormats.EAN_8,
                    Html5QrcodeSupportedFormats.CODE_39,
                    Html5QrcodeSupportedFormats.UPC_A,
                    Html5QrcodeSupportedFormats.UPC_E
                ];
                console.log('Barcode formats enabled');
            } else {
                console.log('Html5QrcodeSupportedFormats not available, using default formats');
            }

            console.log('Scanner config:', config);

            const startCameraWithConfig = () => {
                Html5Qrcode.getCameras().then(devices => {
                    if (devices && devices.length > 0) {
                        console.log('Available cameras:', devices);
                        const rearCamera = devices.find(device =>
                            device.label && device.label.toLowerCase().includes('back') ||
                            device.label && device.label.toLowerCase().includes('rear') ||
                            device.label && device.label.toLowerCase().includes('environment')
                        );

                        const cameraId = rearCamera ? rearCamera.id : devices[0].id;
                        console.log('Using camera:', rearCamera ? rearCamera.label : devices[0].label);

                        html5QrCode.start(
                            cameraId,
                            config,
                            onScanSuccess,
                            onScanFailure
                        ).then(() => {
                            isScanning = true;
                            console.log('Scanner started successfully with camera ID:', cameraId);
                            document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                            document.getElementById('scanner-status').style.color = '#666';
                        }).catch(err => {
                            console.error('Failed to start scanner with enumerated camera:', err);
                            console.log('Falling back to facingMode...');
                            html5QrCode.start(
                                { facingMode: "environment" },
                                config,
                                onScanSuccess,
                                onScanFailure
                            ).then(() => {
                                isScanning = true;
                                console.log('Scanner started successfully with environment camera');
                                document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                                document.getElementById('scanner-status').style.color = '#666';
                            }).catch(err2 => {
                                console.error('Failed to start scanner:', err2);
                                document.getElementById('scanner-status').textContent = 'Camera access denied or not available. Use manual entry.';
                                document.getElementById('scanner-status').style.color = '#dc3545';
                            });
                        });
                    } else {
                        console.log('No cameras enumerated, trying facingMode...');
                        html5QrCode.start(
                            { facingMode: "environment" },
                            config,
                            onScanSuccess,
                            onScanFailure
                        ).then(() => {
                            isScanning = true;
                            console.log('Scanner started successfully with environment camera');
                            document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                            document.getElementById('scanner-status').style.color = '#666';
                        }).catch(err => {
                            console.error('Failed to start scanner:', err);
                            document.getElementById('scanner-status').textContent = 'Camera access denied or not available. Use manual entry.';
                            document.getElementById('scanner-status').style.color = '#dc3545';
                        });
                    }
                }).catch(err => {
                    console.error('Failed to enumerate cameras:', err);
                    console.log('Falling back to facingMode...');
                    html5QrCode.start(
                        { facingMode: "environment" },
                        config,
                        onScanSuccess,
                        onScanFailure
                    ).then(() => {
                        isScanning = true;
                        console.log('Scanner started successfully with environment camera');
                        document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                        document.getElementById('scanner-status').style.color = '#666';
                    }).catch(err2 => {
                        console.error('Failed to start scanner:', err2);
                        document.getElementById('scanner-status').textContent = 'Camera access denied or not available. Use manual entry.';
                        document.getElementById('scanner-status').style.color = '#dc3545';
                    });
                });
            };

            setTimeout(() => startCameraWithConfig(), 300);
        } else if (retryCount < 10) {
            console.log('Html5Qrcode not yet available, retrying in 500ms...');
            setTimeout(() => checkLibrary(retryCount + 1), 500);
        } else {
            console.error('Html5Qrcode failed to load after 10 attempts');
            document.getElementById('scanner-status').textContent = 'html5-qrcode library not loaded. Please check your internet connection and refresh the page.';
            document.getElementById('scanner-status').style.color = '#dc3545';
        }
    }

    checkLibrary();
}

function onScanSuccess(decodedText, decodedResult) {
    console.log("SCANNED:", decodedText);
    alert("Scanned: " + decodedText);

    if (html5QrCode && isScanning) {
        html5QrCode.stop().then(() => {
            isScanning = false;
        }).catch(err => {
            console.error('Failed to stop scanner:', err);
        });
    }

    const resultDiv = document.getElementById('scanned-result');
    const status = document.getElementById('scanner-status');
    resultDiv.style.display = 'block';
    resultDiv.style.background = '#d4edda';
    resultDiv.style.border = '2px solid #28a745';
    resultDiv.style.padding = '12px';
    resultDiv.style.borderRadius = '6px';
    resultDiv.textContent = decodedText;
    resultDiv.style.color = '#155724';
    resultDiv.style.fontSize = '1.1rem';
    resultDiv.style.fontWeight = '700';
    status.textContent = 'Barcode found!';
    status.style.color = '#28a745';

    setTimeout(() => {
        handleScannedBarcode(decodedText);
        closeBarcodeScanner();
    }, 500);
}

function onScanFailure(error) {
    // This is normal during scanning - ignore
}

function handleScannedBarcode(barcode) {
    // Search for product by barcode
    const searchInput = document.getElementById('pos-search');
    searchInput.value = barcode;
    // Trigger the search
    searchInput.dispatchEvent(new Event('input'));
}

function showAddCustomerModal() {
    console.log('showAddCustomerModal called');
    const modal = document.getElementById('addCustomerModal');
    console.log('Modal element:', modal);
    if (modal) {
        modal.classList.add('show');
        console.log('Modal show class added');
    } else {
        console.error('Modal element not found');
    }
}

function hideAddCustomerModal() {
    const modal = document.getElementById('addCustomerModal');
    modal.classList.remove('show');
    document.getElementById('addCustomerForm').reset();
}

function addCustomer(event) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);

    fetch(CONFIG.url + '/customers/store', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            // Add new customer to select dropdown
            const select = document.getElementById('pos-customer');
            const option = document.createElement('option');
            option.value = res.customer_id;
            option.textContent = res.name;
            option.selected = true;
            select.appendChild(option);

            hideAddCustomerModal();
            alert('Customer added successfully!');
        } else {
            alert('Error adding customer: ' + res.message);
        }
    })
    .catch(err => alert('Error adding customer: ' + err.message));
}

// Cash Payment Modal Functions
let currentTotalPayable = 0;

function showCashPaymentModal(total) {
    currentTotalPayable = total;
    document.getElementById('modal-total-payable').textContent = CONFIG.currency + total.toFixed(2);
    document.getElementById('amount-received').value = '';
    document.getElementById('change-due').textContent = CONFIG.currency + '0.00';
    const modal = document.getElementById('cashPaymentModal');
    modal.style.display = 'flex';
    modal.style.visibility = 'visible';
    modal.style.opacity = '1';
    modal.style.pointerEvents = 'auto';
    document.getElementById('amount-received').focus();
    // Disable checkout button to prevent double submission
    const btnCheckout = document.getElementById('btn-checkout');
    if (btnCheckout) btnCheckout.disabled = true;
}

function hideCashPaymentModal() {
    const modal = document.getElementById('cashPaymentModal');
    if (modal) {
        modal.style.display = 'none';
        modal.style.visibility = 'hidden';
        modal.style.pointerEvents = 'none';
    }
    // Re-enable checkout button
    const btnCheckout = document.getElementById('btn-checkout');
    if (btnCheckout) btnCheckout.disabled = false;
}

function calculateChange() {
    const amountReceived = parseFloat(document.getElementById('amount-received').value) || 0;
    const change = amountReceived - currentTotalPayable;
    document.getElementById('change-due').textContent = CONFIG.currency + change.toFixed(2);
    
    // Enable/disable confirm button based on sufficient payment
    const confirmBtn = document.getElementById('btn-confirm-payment');
    if (amountReceived >= currentTotalPayable) {
        confirmBtn.disabled = false;
        confirmBtn.style.opacity = '1';
    } else {
        confirmBtn.disabled = true;
        confirmBtn.style.opacity = '0.5';
    }
}

function setQuickAmount(amount) {
    const input = document.getElementById('amount-received');
    const currentValue = parseFloat(input.value) || 0;
    input.value = currentValue + amount;
    calculateChange();
}

function setExactAmount() {
    document.getElementById('amount-received').value = currentTotalPayable.toFixed(2);
    calculateChange();
}

function clearAmountReceived() {
    document.getElementById('amount-received').value = '';
    calculateChange();
}

// Multiple Payment Functions
let multiplePaymentTotal = 0;
let paymentMethodRows = [];

function showMultiplePaymentModal(total) {
    multiplePaymentTotal = total;
    paymentMethodRows = [];

    document.getElementById('multiple-total-payable').textContent = CONFIG.currency + total.toFixed(2);
    document.getElementById('multiple-remaining').textContent = CONFIG.currency + total.toFixed(2);
    document.getElementById('payment-methods-container').innerHTML = '';
    document.getElementById('btn-confirm-multiple-payment').disabled = true;
    document.getElementById('btn-confirm-multiple-payment').style.opacity = '0.5';

    // Add initial Cash payment row
    addPaymentMethodRow('cash');

    document.getElementById('multiplePaymentModal').classList.add('show');
    // Disable checkout button to prevent double submission
    const btnCheckout = document.getElementById('btn-checkout');
    if (btnCheckout) btnCheckout.disabled = true;
}

function hideMultiplePaymentModal() {
    // Prevent closing if processing payment
    if (isProcessing) {
        alert('Payment is being processed. Please wait...');
        return;
    }
    document.getElementById('multiplePaymentModal').classList.remove('show');
    paymentMethodRows = [];
    // Re-enable checkout button if not processing
    const btnCheckout = document.getElementById('btn-checkout');
    if (btnCheckout && !isProcessing) btnCheckout.disabled = false;
}

function addPaymentMethodRow(defaultMethod = '') {
    const container = document.getElementById('payment-methods-container');
    const rowId = 'payment-row-' + Date.now();
    
    const rowHtml = `
        <div id="${rowId}" class="payment-method-row" style="display: grid; grid-template-columns: 1fr 1fr 40px; gap: 8px; margin-bottom: 8px; align-items: center;">
            <select class="payment-method-select" style="padding: 8px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.85rem;" onchange="updateMultiplePaymentTotal()">
                <option value="cash" ${defaultMethod === 'cash' ? 'selected' : ''}>Cash</option>
                <option value="card" ${defaultMethod === 'card' ? 'selected' : ''}>Card</option>
                <option value="bank_transfer" ${defaultMethod === 'bank_transfer' ? 'selected' : ''}>Bank Transfer</option>
                <option value="mobile_money" ${defaultMethod === 'mobile_money' ? 'selected' : ''}>Mobile Money</option>
                <option value="check" ${defaultMethod === 'check' ? 'selected' : ''}>Check</option>
            </select>
            <input type="number" class="payment-amount-input" placeholder="0.00" min="0" step="0.01" style="padding: 8px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.85rem; text-align: right;" oninput="this.dataset.modified = 'true'; updateMultiplePaymentTotal(this)">
            <button type="button" onclick="removePaymentMethodRow('${rowId}')" style="padding: 8px; border: 1px solid #dc3545; background: #dc3545; color: #fff; border-radius: 6px; cursor: pointer; font-size: 0.85rem;">×</button>
        </div>
    `;
    
    container.insertAdjacentHTML('beforeend', rowHtml);
    paymentMethodRows.push(rowId);
    
    // Auto-fill newly added row with remaining balance if any
    const inputs = document.querySelectorAll('.payment-amount-input');
    if (inputs.length > 1) {
        let currentTotal = 0;
        for (let i = 0; i < inputs.length - 1; i++) {
            currentTotal += parseFloat(inputs[i].value) || 0;
        }
        const remainder = multiplePaymentTotal - currentTotal;
        if (remainder > 0) {
            inputs[inputs.length - 1].value = remainder.toFixed(2);
        }
    }
    
    updateMultiplePaymentTotal();
}

function removePaymentMethodRow(rowId) {
    const row = document.getElementById(rowId);
    if (row) {
        row.remove();
        paymentMethodRows = paymentMethodRows.filter(id => id !== rowId);
        updateMultiplePaymentTotal();
    }
}

function updateMultiplePaymentTotal(triggeringInput = null) {
    const inputs = document.querySelectorAll('.payment-amount-input');
    
    // Distribute remaining to the first unmodified input if triggered by a user edit
    if (triggeringInput) {
        let totalModified = 0;
        let unmodifiedInput = null;
        
        inputs.forEach(input => {
            if (input === triggeringInput || input.dataset.modified === 'true') {
                totalModified += parseFloat(input.value) || 0;
            } else if (!unmodifiedInput) {
                unmodifiedInput = input;
            }
        });
        
        if (unmodifiedInput) {
            const remainder = Math.max(0, multiplePaymentTotal - totalModified);
            unmodifiedInput.value = remainder > 0 ? remainder.toFixed(2) : '';
        }
    }
    
    // Recalculate standard total paid display
    let totalPaid = 0;
    inputs.forEach(input => {
        totalPaid += parseFloat(input.value) || 0;
    });
    
    const remaining = multiplePaymentTotal - totalPaid;
    document.getElementById('multiple-remaining').textContent = CONFIG.currency + remaining.toFixed(2);
    
    const btnConfirm = document.getElementById('btn-confirm-multiple-payment');
    if (remaining === 0 && totalPaid > 0) {
        btnConfirm.disabled = false;
        btnConfirm.style.opacity = '1';
    } else {
        btnConfirm.disabled = true;
        btnConfirm.style.opacity = '0.5';
    }
    
    // Update remaining color
    const remainingEl = document.getElementById('multiple-remaining');
    if (remaining === 0) {
        remainingEl.style.color = '#28a745';
    } else if (remaining < 0) {
        remainingEl.style.color = '#dc3545';
    } else {
        remainingEl.style.color = '#ffc107';
    }
}

document.addEventListener('DOMContentLoaded', function() {
    let cart = [];
    const searchInput = document.getElementById('pos-search');
    const resultsContainer = document.getElementById('pos-results');
    const cartContainer = document.getElementById('cart-items');
    const btnCheckout = document.getElementById('btn-checkout');
    let isProcessing = false;



    // Multiple Payment confirmation function
    function confirmMultiplePayment() {
        if (isProcessing) return;

        const rows = document.querySelectorAll('.payment-method-row');
        const payments = [];
        let totalPaid = 0;

        rows.forEach(row => {
            const method = row.querySelector('.payment-method-select').value;
            const amount = parseFloat(row.querySelector('.payment-amount-input').value) || 0;
            if (amount > 0) {
                const methodMap = {
                    'cash': 'cash',
                    'card': 'card',
                    'bank_transfer': 'transfer',
                    'mobile_money': 'other',
                    'check': 'cheque'
                };
                const dbMethod = methodMap[method] || 'other';

                payments.push({
                    method: dbMethod,
                    amount: amount,
                    note: method.charAt(0).toUpperCase() + method.slice(1).replace('_', ' ') + ' payment'
                });
                totalPaid += amount;
            }
        });

        if (totalPaid !== multiplePaymentTotal) {
            alert('Payment amounts must equal total: ' + CONFIG.currency + multiplePaymentTotal.toFixed(2));
            return;
        }

        const btnConfirm = document.getElementById('btn-confirm-multiple-payment');
        if (btnConfirm) {
            btnConfirm.disabled = true;
            btnConfirm.innerHTML = '<span class="loading-spinner"></span> PROCESSING...';
        }
        isProcessing = true;

        hideMultiplePaymentModal();
        
        const subtotal = cart.reduce((sum, item) => sum + (item.qty * item.selling_price), 0);
        const taxEnabled = CONFIG.taxEnabled || 0;
        const taxRate = CONFIG.taxRate || 0;
        let tax = 0;
        if (taxEnabled && taxRate > 0) {
            tax = subtotal * (taxRate / 100);
        }
        const discount = parseFloat(document.getElementById('pos-discount-input').value) || 0;
        const shipping = parseFloat(document.getElementById('pos-shipping-input').value) || 0;
        const total = subtotal + tax - discount + shipping;

        const data = {
            customer_id: document.getElementById('pos-customer').value,
            location_id: document.getElementById('pos-location').value,
            items: cart.map(i => ({ id: i.id, qty: i.qty, price: i.selling_price })),
            total: total,
            tax: tax,
            discount: discount,
            shipping: shipping,
            payable: total,
            type: 'pos',
            status: 'completed',
            payment_status: 'paid',
            payment_method: 'other',
            payments: payments
        };

        btnCheckout.disabled = true;
        if (btnConfirm) btnConfirm.disabled = true;

        fetch(CONFIG.url + '/sales/pos/store', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
            body: JSON.stringify(data)
        })
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                if (confirm('Success! Transaction: ' + res.sale_no + '\n\nDo you want to print the receipt?')) {
                    const receiptUrl = CONFIG.url + '/sales/' + res.sale_id + '/pos-receipt/pos80';
                    const printWindow = window.open(receiptUrl, '_blank');
                    if (printWindow) {
                        printWindow.onload = function() {
                            setTimeout(() => {
                                printWindow.close();
                            }, 2000);
                        };
                    }
                }
                cart = [];
                renderCart();
                searchInput.value = '';
                resultsContainer.innerHTML = '';
                localStorage.removeItem('posCart');
                location.reload();
            } else {
                alert('Error: ' + res.message);
                isProcessing = false;
                btnCheckout.disabled = false;
                if (btnConfirm) {
                    btnConfirm.disabled = false;
                    btnConfirm.innerHTML = 'Complete Payment';
                }
            }
        })
        .catch(err => {
            alert('Error: ' + err.message);
            isProcessing = false;
            btnCheckout.disabled = false;
            if (btnConfirm) {
                btnConfirm.disabled = false;
                btnConfirm.innerHTML = 'Complete Payment';
            }
        });
    }

    // Add event listener for scan button
    const scanButton = document.getElementById('scan-button');
    if (scanButton) {
        scanButton.addEventListener('click', function(e) {
            e.preventDefault();
            console.log('Scan button clicked via event listener');
            if (typeof openBarcodeScanner === 'function') {
                openBarcodeScanner();
            } else {
                console.error('openBarcodeScanner is not defined');
                alert('Scanner function not loaded. Please refresh the page.');
            }
        });
    } else {
        console.error('Scan button not found');
    }

    // Load all products on page load with default location
    const defaultLocationId = document.getElementById('pos-location').value;
    let productsUrl = CONFIG.url + '/sales/pos/products';
    if (defaultLocationId) {
        productsUrl += '?location_id=' + defaultLocationId;
    }
    fetch(productsUrl)
        .then(r => {
            if (!r.ok) throw new Error('Network response was not ok');
            return r.json();
        })
        .then(data => {
            console.log('Products loaded:', data);
            renderProducts(data);
        })
        .catch(err => {
            console.error('Error loading products:', err);
            resultsContainer.innerHTML = '<div class="text-center p-12 text-danger">Error loading products. Please refresh the page.</div>';
        });

    // Search functionality
    let searchTimeout;
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const query = this.value.trim();

        // Always use loadFilteredProducts to respect category and brand filters
        searchTimeout = setTimeout(() => {
            loadFilteredProducts();
        }, 250);
    });

    let allProducts = [];
    let currentPage = 1;
    const perPage = 1000; // Increased to allow natural scrolling as requested


    function renderProducts(products) {
        allProducts = products;
        currentPage = 1;
        renderPage();
    }

    function renderPage() {
        if (allProducts.length === 0) {
            resultsContainer.innerHTML = '<div class="text-center p-12 text-muted" style="grid-column: 1/-1; height: fit-content;">No matches found. Check spelling or scan again.</div>';
            return;
        }

        const totalPages = Math.ceil(allProducts.length / perPage);
        const start = (currentPage - 1) * perPage;
        const pageProducts = allProducts.slice(start, start + perPage);

        let html = pageProducts.map(p => `
            <div class="product-card ${p.stock_qty <= 0 ? 'out-of-stock' : ''}" onclick="addToCart(this)" data-product='${JSON.stringify(p).replace(/'/g, "&apos;").replace(/"/g, "&quot;")}'>

                <div class="product-image">
                    ${p.image ? `<img src="${CONFIG.url}/uploads/<?= Auth::tenantId() ?>/${p.image}" alt="${p.name}">` : '<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="product-image-placeholder"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>'}
                </div>
                <div class="product-name">${p.name}</div>
                <div class="product-sku">${p.sku}</div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div class="product-price">${CONFIG.currency}${parseFloat(p.selling_price).toFixed(2)}</div>
                    <div class="product-stock">${parseFloat(p.stock_qty).toFixed(2)} in stock</div>
                </div>
            </div>
        `).join('');

        if (totalPages > 1) {
            html += `
                <div style="grid-column: 1/-1; display: flex; justify-content: center; align-items: center; gap: 12px; padding: 10px 0;">
                    <button onclick="changePage(-1)" ${currentPage <= 1 ? 'disabled' : ''} style="padding: 6px 14px; border: 1px solid #ddd; background: #fff; border-radius: 4px; font-size: 0.8rem; cursor: pointer; ${currentPage <= 1 ? 'opacity: 0.4; cursor: not-allowed;' : ''}">&laquo; Prev</button>
                    <span style="font-size: 0.8rem; color: #666;">Page ${currentPage} of ${totalPages}</span>
                    <button onclick="changePage(1)" ${currentPage >= totalPages ? 'disabled' : ''} style="padding: 6px 14px; border: 1px solid #ddd; background: #fff; border-radius: 4px; font-size: 0.8rem; cursor: pointer; ${currentPage >= totalPages ? 'opacity: 0.4; cursor: not-allowed;' : ''}">Next &raquo;</button>
                </div>
            `;
        }

        resultsContainer.innerHTML = html;
    }

    window.changePage = function(dir) {
        const totalPages = Math.ceil(allProducts.length / perPage);
        currentPage += dir;
        if (currentPage < 1) currentPage = 1;
        if (currentPage > totalPages) currentPage = totalPages;
        renderPage();
    };

    window.addToCart = function(el) {
        const product = JSON.parse(el.getAttribute('data-product'));
        if (product.stock_qty <= 0 && !CONFIG.allowOverselling) {

            alert('OUT OF STOCK');
            return;
        }
        const existingIndex = cart.findIndex(item => item.id === product.id);
        if (existingIndex !== -1) {
            const existing = cart[existingIndex];
            if (existing.qty >= product.stock_qty) {
                alert('Stock Limit Hit');
                return;
            }
            existing.qty++;
            // Move updated item to the top
            cart.splice(existingIndex, 1);
            cart.unshift(existing);
        } else {
            cart.unshift({ ...product, qty: 1 });
        }
        renderCart();
        saveCart();
    };

    function renderCart() {
        if (cart.length === 0) {
            cartContainer.innerHTML = `
                <tr>
                    <td colspan="5" style="padding: 40px; text-align: center; color: #999;">
                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 10px; opacity: 0.3;"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
                        <p style="margin: 0;">No items in cart</p>
                    </td>
                </tr>
            `;
            updateTotals();
            btnCheckout.disabled = true;
            return;
        }

        cartContainer.innerHTML = cart.map((item, index) => `
            <tr class="cart-table-row">
                <td style="padding: 10px;">
                    <div style="font-weight: 600; color: #333;">${item.name}</div>
                    <div style="font-size: 0.75rem; color: #999;">${item.sku}</div>
                </td>
                <td style="padding: 10px; text-align: center;">
                    <input type="number" class="qty-input" value="${item.qty}" min="0.01" step="0.01" onchange="updateQty(${index}, this.value)">
                </td>
                <td style="padding: 10px; text-align: right;">${CONFIG.currency}${parseFloat(item.selling_price).toFixed(2)}</td>
                <td style="padding: 10px; text-align: right; font-weight: 600;">${CONFIG.currency}${(item.qty * item.selling_price).toFixed(2)}</td>
                <td style="padding: 10px; text-align: center;">
                    <button onclick="removeFromCart(${index})" class="btn-remove-item">&times;</button>
                </td>
            </tr>
        `).join('');

        updateTotals();
        btnCheckout.disabled = false;
    }

    window.updateQty = function(index, qty) {
        qty = parseFloat(qty);
        if (isNaN(qty) || qty < 0.01) {
            cart[index].qty = 0.01;
            renderCart();
            return;
        }
        if (!CONFIG.allowOverselling && qty > cart[index].stock_qty) {
            alert('OUT OF STOCK');
            cart[index].qty = cart[index].stock_qty;
            renderCart();
            return;
        }
        cart[index].qty = qty;
        renderCart();
        saveCart();
    };

    window.removeFromCart = function(index) {
        cart.splice(index, 1);
        renderCart();
        saveCart();
    };

    document.getElementById('clear-cart').addEventListener('click', () => {
        if (cart.length > 0 && confirm('Clear entire sales ledger?')) {
            cart = [];
            renderCart();
            saveCart();
        }
    });

    // Add event listeners for discount and shipping inputs
    document.getElementById('pos-discount-input').addEventListener('input', function() {
        updateTotals();
        saveCart();
    });
    document.getElementById('pos-shipping-input').addEventListener('input', function() {
        updateTotals();
        saveCart();
    });

    // Save cart to localStorage
    function saveCart() {
        const cartData = {
            cart: cart,
            discount: document.getElementById('pos-discount-input').value,
            shipping: document.getElementById('pos-shipping-input').value
        };
        localStorage.setItem('posCart', JSON.stringify(cartData));
    }

    // Load cart from localStorage
    function loadCart() {
        const savedCart = localStorage.getItem('posCart');
        if (savedCart) {
            try {
                const cartData = JSON.parse(savedCart);
                cart = cartData.cart || [];
                document.getElementById('pos-discount-input').value = cartData.discount || 0;
                document.getElementById('pos-shipping-input').value = cartData.shipping || 0;
                renderCart();
                updateTotals();
            } catch (e) {
                console.error('Error loading cart:', e);
            }
        }
    }

    // Load cart on page load
    loadCart();

    function updateTotals() {
        const subtotal = cart.reduce((sum, item) => sum + (item.qty * item.selling_price), 0);
        const itemsCount = cart.reduce((sum, item) => sum + item.qty, 0);

        // Auto-calculate tax based on default tax rate if enabled
        let tax = 0;
        const taxEnabled = CONFIG.taxEnabled || 0;
        const taxRate = CONFIG.taxRate || 0;
        if (taxEnabled && taxRate > 0) {
            tax = subtotal * (taxRate / 100);
        }
        document.getElementById('pos-tax-input').value = tax.toFixed(2);

        const discount = parseFloat(document.getElementById('pos-discount-input').value) || 0;
        const shipping = parseFloat(document.getElementById('pos-shipping-input').value) || 0;
        const total = subtotal + tax - discount + shipping;

        document.getElementById('pos-items-count').textContent = itemsCount;
        document.getElementById('pos-subtotal').textContent = `${CONFIG.currency}${subtotal.toFixed(2)}`;
        document.getElementById('pos-total-payable').textContent = `${CONFIG.currency}${total.toFixed(2)}`;
    }

    // Category and brand filtering
    const categorySelect = document.getElementById('pos-category');
    const brandSelect = document.getElementById('pos-brand');
    const locationSelect = document.getElementById('pos-location');

    function loadFilteredProducts() {
        const categoryId = categorySelect.value;
        const brandId = brandSelect.value;
        const locationId = locationSelect.value;
        const query = searchInput.value.trim();
        
        let url = CONFIG.url + '/sales/pos/products';
        const params = new URLSearchParams();
        if (query) params.append('q', query);
        if (categoryId) params.append('category_id', categoryId);
        if (brandId) params.append('brand_id', brandId);
        if (locationId) params.append('location_id', locationId);
        
        if (params.toString()) {
            url += '?' + params.toString();
        }
        
        fetch(url)
            .then(r => {
                if (!r.ok) throw new Error('Network response was not ok');
                return r.json();
            })
            .then(data => {
                console.log('Filtered products loaded:', data);
                renderProducts(data);
            })
            .catch(err => {
                console.error('Error loading filtered products:', err);
            });
    }

    categorySelect.addEventListener('change', loadFilteredProducts);
    brandSelect.addEventListener('change', loadFilteredProducts);
    locationSelect.addEventListener('change', loadFilteredProducts);

    // Helper function to process checkout with custom parameters
    function processCheckout(params) {
        const subtotal = cart.reduce((sum, item) => sum + (item.qty * item.selling_price), 0);
        const taxEnabled = CONFIG.taxEnabled || 0;
        const taxRate = CONFIG.taxRate || 0;
        let tax = 0;
        if (taxEnabled && taxRate > 0) {
            tax = subtotal * (taxRate / 100);
        }
        const discount = parseFloat(document.getElementById('pos-discount-input').value) || 0;
        const shipping = parseFloat(document.getElementById('pos-shipping-input').value) || 0;
        const total = subtotal + tax - discount + shipping;

        const data = {
            customer_id: document.getElementById('pos-customer').value,
            location_id: document.getElementById('pos-location').value,
            items: cart.map(i => ({ id: i.id, qty: i.qty, price: i.selling_price })),
            total: total,
            tax: tax,
            discount: discount,
            shipping: shipping,
            payable: total,
            ...params
        };

        btnCheckout.disabled = true;
        const originalText = btnCheckout.innerHTML;
        btnCheckout.innerHTML = '<span class="loading-spinner"></span> PROCESSING...';

        fetch(CONFIG.url + '/sales/pos/store', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
            body: JSON.stringify(data)
        })
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                if (confirm('Success! Transaction: ' + res.sale_no + '\n\nDo you want to print the receipt?')) {
                    const receiptUrl = CONFIG.url + '/sales/' + res.sale_id + '/pos-receipt/pos80';
                    console.log('Opening receipt URL:', receiptUrl);
                    const printWindow = window.open(receiptUrl, '_blank');
                    if (printWindow) {
                        printWindow.onload = function() {
                            setTimeout(() => {
                                printWindow.close();
                            }, 2000);
                        };
                    }
                }
                cart = [];
                renderCart();
                searchInput.value = '';
                resultsContainer.innerHTML = '';
                localStorage.removeItem('posCart');
                location.reload();
            } else {
                alert('Error: ' + res.message);
                btnCheckout.disabled = false;
                btnCheckout.innerHTML = originalText;
            }
        })
        .catch(err => {
            alert('Error: ' + err.message);
            btnCheckout.disabled = false;
            btnCheckout.innerHTML = originalText;
        });
    }

    // Suspend button
    document.getElementById('btn-suspend').addEventListener('click', function() {
        if (cart.length === 0) {
            alert('Cart is empty');
            return;
        }

        const subtotal = cart.reduce((sum, item) => sum + (item.qty * item.selling_price), 0);
        const tax = parseFloat(document.getElementById('pos-tax-input').value) || 0;
        const discount = parseFloat(document.getElementById('pos-discount-input').value) || 0;
        const shipping = parseFloat(document.getElementById('pos-shipping-input').value) || 0;
        const total = subtotal + tax - discount + shipping;

        const data = {
            customer_id: document.getElementById('pos-customer').value,
            location_id: document.getElementById('pos-location').value,
            items: cart.map(i => ({ id: i.id, qty: i.qty, price: i.selling_price })),
            total: total,
            tax: tax,
            discount: discount,
            shipping: shipping
        };

        fetch(CONFIG.url + '/sales/pos/suspend', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
            body: JSON.stringify(data)
        })
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                alert('Order suspended: ' + res.sale_no);
                cart = [];
                renderCart();
                localStorage.removeItem('posCart');
            } else {
                alert('Error: ' + res.message);
            }
        });
    });

    // Multiple Pay button
    document.getElementById('btn-multiple').addEventListener('click', function() {
        if (cart.length === 0) {
            alert('Cart is empty');
            return;
        }

        const subtotal = cart.reduce((sum, item) => sum + (item.qty * item.selling_price), 0);
        const taxEnabled = CONFIG.taxEnabled || 0;
        const taxRate = CONFIG.taxRate || 0;
        let tax = 0;
        if (taxEnabled && taxRate > 0) {
            tax = subtotal * (taxRate / 100);
        }
        const discount = parseFloat(document.getElementById('pos-discount-input').value) || 0;
        const shipping = parseFloat(document.getElementById('pos-shipping-input').value) || 0;
        const total = subtotal + tax - discount + shipping;

        showMultiplePaymentModal(total);
    });

    // Complete Payment button (Split Payment)
    document.getElementById('btn-confirm-multiple-payment').addEventListener('click', function() {
        confirmMultiplePayment();
    });

    // Recent Transactions button
    document.querySelector('.pos-recent-btn').addEventListener('click', function() {
        showRecentTransactionsModal();
    });

    function showRecentTransactionsModal() {
        const modal = document.getElementById('recentTransactionsModal');
        const list = document.getElementById('recent-transactions-list');
        const noTransactions = document.getElementById('no-recent-transactions');
        
        list.innerHTML = '';
        noTransactions.style.display = 'none';
        modal.classList.add('show');

        fetch(CONFIG.url + '/sales/pos/recent')
            .then(r => r.json())
            .then(transactions => {
                if (transactions.length === 0) {
                    noTransactions.style.display = 'block';
                    return;
                }

                transactions.forEach(t => {
                    const item = document.createElement('div');
                    item.style.cssText = 'padding: 12px; background: #f9f9f9; border: 1px solid #e5e5e5; border-radius: 6px; transition: all 0.2s;';
                    item.innerHTML = `
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <div style="font-weight: 600; font-size: 0.9rem; color: #333;">${t.sale_no}</div>
                                <div style="font-size: 0.8rem; color: #666; margin-top: 2px;">${new Date(t.created_at).toLocaleString()}</div>
                            </div>
                            <div style="text-align: right;">
                                <div style="font-weight: 700; font-size: 1rem; color: #28a745;">${CONFIG.currency}${parseFloat(t.total).toFixed(2)}</div>
                                <div style="font-size: 0.75rem; color: #666; margin-top: 2px;">${t.payment_method} - ${t.status}</div>
                            </div>
                        </div>
                    `;
                    list.appendChild(item);
                });
            })
            .catch(err => {
                console.error('Error loading recent transactions:', err);
                alert('Error loading recent transactions: ' + err.message);
                hideRecentTransactionsModal();
            });
    }

    // Suspended Orders button
    document.querySelector('.pos-suspended-btn').addEventListener('click', function() {
        showSuspendedOrdersModal();
    });

    function showSuspendedOrdersModal() {
        const modal = document.getElementById('suspendedOrdersModal');
        const list = document.getElementById('suspended-orders-list');
        const noOrders = document.getElementById('no-suspended-orders');
        
        list.innerHTML = '';
        noOrders.style.display = 'none';
        modal.classList.add('show');

        fetch(CONFIG.url + '/sales/pos/suspended')
            .then(r => r.json())
            .then(suspended => {
                if (suspended.length === 0) {
                    noOrders.style.display = 'block';
                    return;
                }

                suspended.forEach(s => {
                    const item = document.createElement('div');
                    item.style.cssText = 'padding: 12px; background: #f9f9f9; border: 1px solid #e5e5e5; border-radius: 6px; cursor: pointer; transition: all 0.2s;';
                    item.innerHTML = `
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <div style="font-weight: 600; font-size: 0.9rem; color: #333;">${s.sale_no}</div>
                                <div style="font-size: 0.8rem; color: #666; margin-top: 2px;">${new Date(s.suspended_at).toLocaleString()}</div>
                            </div>
                            <div style="text-align: right;">
                                <div style="font-weight: 700; font-size: 1rem; color: #28a745;">${CONFIG.currency}${parseFloat(s.total).toFixed(2)}</div>
                                <div style="font-size: 0.75rem; color: #007bff; margin-top: 2px;">Click to resume</div>
                            </div>
                        </div>
                    `;
                    item.addEventListener('click', () => {
                        hideSuspendedOrdersModal();
                        resumeSuspendedOrder(s.id);
                    });
                    item.addEventListener('mouseenter', () => {
                        item.style.background = '#e8f5e9';
                        item.style.borderColor = '#28a745';
                    });
                    item.addEventListener('mouseleave', () => {
                        item.style.background = '#f9f9f9';
                        item.style.borderColor = '#e5e5e5';
                    });
                    list.appendChild(item);
                });
            })
            .catch(err => {
                console.error('Error loading suspended orders:', err);
                alert('Error loading suspended orders: ' + err.message);
                hideSuspendedOrdersModal();
            });
    }

    function resumeSuspendedOrder(saleId) {
        fetch(CONFIG.url + '/sales/pos/resume/' + saleId)
            .then(r => r.json())
            .then(data => {
                if (!data.success) {
                    alert('Failed to resume order: ' + data.message);
                    return;
                }
                // Load the resumed items into cart
                cart = [];
                data.items.forEach(item => {
                    cart.push({
                        id: item.id,
                        name: item.name,
                        sku: item.sku,
                        selling_price: item.price,
                        qty: item.qty,
                        stock_qty: 999
                    });
                });
                // Set customer and location
                document.getElementById('pos-customer').value = data.customer_id || '';
                document.getElementById('pos-location').value = data.location_id;
                // Set discount, tax, and shipping
                document.getElementById('pos-discount-input').value = data.discount || 0;
                document.getElementById('pos-tax-input').value = data.tax || 0;
                document.getElementById('pos-shipping-input').value = data.shipping || 0;
                // Render cart and update totals
                renderCart();
                updateTotals();
                alert('Suspended order resumed successfully');
            })
            .catch(err => alert('Error resuming order: ' + err.message));
    }

    // Checkout processing - show payment modal for Cash
    btnCheckout.addEventListener('click', function() {
        if (cart.length === 0) {
            alert('Cart is empty');
            return;
        }

        const subtotal = cart.reduce((sum, item) => sum + (item.qty * item.selling_price), 0);
        const tax = parseFloat(document.getElementById('pos-tax-input').value) || 0;
        const discount = parseFloat(document.getElementById('pos-discount-input').value) || 0;
        const shipping = parseFloat(document.getElementById('pos-shipping-input').value) || 0;
        const total = subtotal + tax - discount + shipping;

        showCashPaymentModal(total);
    });

    // Confirm cash payment function
    window.confirmCashPayment = function() {
        if (isProcessing) return;

        const amountReceived = parseFloat(document.getElementById('amount-received').value) || 0;

        if (amountReceived < currentTotalPayable) {
            alert('Insufficient payment amount');
            return;
        }

        const btnConfirm = document.getElementById('btn-confirm-payment');
        if (btnConfirm) {
            btnConfirm.disabled = true;
            btnConfirm.innerHTML = '<span class="loading-spinner"></span> PROCESSING...';
        }
        isProcessing = true;
        
        const change = amountReceived - currentTotalPayable;
        
        // Process checkout with amount received and change
        const subtotal = cart.reduce((sum, item) => sum + (item.qty * item.selling_price), 0);
        const taxEnabled = CONFIG.taxEnabled || 0;
        const taxRate = CONFIG.taxRate || 0;
        let tax = 0;
        if (taxEnabled && taxRate > 0) {
            tax = subtotal * (taxRate / 100);
        }
        const discount = parseFloat(document.getElementById('pos-discount-input').value) || 0;
        const shipping = parseFloat(document.getElementById('pos-shipping-input').value) || 0;
        const total = subtotal + tax - discount + shipping;

        const data = {
            customer_id: document.getElementById('pos-customer').value,
            location_id: document.getElementById('pos-location').value,
            items: cart.map(i => ({ id: i.id, qty: i.qty, price: i.selling_price })),
            total: total,
            tax: tax,
            discount: discount,
            shipping: shipping,
            payable: total,
            amount_paid: amountReceived,
            change_due: change,
            type: 'pos',
            status: 'completed',
            payment_status: 'paid',
            payment_method: 'cash'
        };

        const btnCheckout = document.getElementById('btn-checkout');
        if (btnCheckout) btnCheckout.disabled = true;

        fetch(CONFIG.url + '/sales/pos/store', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
            body: JSON.stringify(data)
        })
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                hideCashPaymentModal();
                if (confirm('Success! Transaction: ' + res.sale_no + '\n\nChange Due: ' + CONFIG.currency + change.toFixed(2) + '\n\nDo you want to print the receipt?')) {
                    const receiptUrl = CONFIG.url + '/sales/' + res.sale_id + '/pos-receipt/pos80';
                    const printWindow = window.open(receiptUrl, '_blank');
                    if (printWindow) {
                        printWindow.onload = function() {
                            setTimeout(() => {
                                printWindow.close();
                            }, 2000);
                        };
                    }
                }
                cart = [];
                renderCart();
                searchInput.value = '';
                resultsContainer.innerHTML = '';
                localStorage.removeItem('posCart');
                location.reload();
            } else {
                alert('Error: ' + res.message);
                isProcessing = false;
                if (btnConfirm) {
                    btnConfirm.disabled = false;
                    btnConfirm.innerHTML = 'Complete Payment';
                }
                const btnCheckout = document.getElementById('btn-checkout');
                if (btnCheckout) btnCheckout.disabled = false;
            }
        })
        .catch(err => {
            alert('Error: ' + err.message);
            isProcessing = false;
            if (btnConfirm) {
                btnConfirm.disabled = false;
                btnConfirm.innerHTML = 'Complete Payment';
            }
            const btnCheckout = document.getElementById('btn-checkout');
            if (btnCheckout) btnCheckout.disabled = false;
        });
    };
});

function hideSuspendedOrdersModal() {
    document.getElementById('suspendedOrdersModal').classList.remove('show');
}

function hideRecentTransactionsModal() {
    document.getElementById('recentTransactionsModal').classList.remove('show');
}
</script>
