@extends('layouts.app')

@section('title', 'Point of Sale')

@section('style')
<style>
    .pos-container {
        display: grid;
        grid-template-columns: 3fr 2fr;
        gap: 20px;
        min-height: calc(100vh - 200px);
    }
    
    .product-search-section, .cart-section {
        background: #fff;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        border: 1px solid #e9ecef;
    }
    
    .cart-section {
        display: flex;
        flex-direction: column;
        height: calc(100vh - 200px);
    }
    
    .product-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 15px;
        margin-top: 20px;
        max-height: 500px;
        overflow-y: auto;
        padding: 5px;
    }
    
    .product-card {
        border: 1px solid #e2e8f0;
        border-radius: 10px;
        padding: 15px;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #fff;
        position: relative;
        overflow: hidden;
    }
    
    .product-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.1);
        border-color: #5d87ff;
    }
    
    .product-card .product-name {
        font-weight: 600;
        font-size: 14px;
        margin-bottom: 8px;
        color: #2a3547;
    }
    
    .product-card .product-price {
        color: #5d87ff;
        font-weight: 700;
        font-size: 16px;
        margin-bottom: 5px;
    }
    
    .product-card .product-stock {
        font-size: 12px;
        color: #5a6a85;
        background: #f2f6fc;
        padding: 2px 8px;
        border-radius: 20px;
        display: inline-block;
    }
    
    .cart-items {
        flex: 1;
        overflow-y: auto;
        margin-bottom: 20px;
        max-height: 400px;
        padding: 5px;
    }
    
    .cart-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px;
        border-bottom: 1px solid #f2f6fc;
        background: #fff;
        border-radius: 8px;
        margin-bottom: 8px;
        border: 1px solid #f2f6fc;
    }
    
    .cart-item:hover {
        background: #f8fafc;
    }
    
    .cart-item-info {
        flex: 1;
    }
    
    .cart-item-name {
        font-weight: 500;
        color: #2a3547;
        font-size: 14px;
    }
    
    .cart-item-price {
        color: #5a6a85;
        font-size: 13px;
    }
    
    .cart-item-controls {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .quantity-control {
        display: flex;
        align-items: center;
        gap: 5px;
    }
    
    .quantity-btn {
        width: 28px;
        height: 28px;
        border: 1px solid #dfe5ef;
        border-radius: 6px;
        background: #fff;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        color: #5a6a85;
        transition: all 0.2s;
    }
    
    .quantity-btn:hover {
        background: #f2f6fc;
        border-color: #5d87ff;
        color: #5d87ff;
    }
    
    .quantity-input {
        width: 45px;
        text-align: center;
        border: 1px solid #dfe5ef;
        border-radius: 6px;
        padding: 4px;
        font-size: 14px;
        background: #fff;
    }
    
    .cart-summary {
        border-top: 2px solid #f2f6fc;
        padding-top: 20px;
        background: #fff;
        border-radius: 0 0 12px 12px;
    }
    
    .summary-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        color: #5a6a85;
        font-size: 14px;
    }
    
    .summary-row.total {
        font-weight: 700;
        font-size: 18px;
        color: #2a3547;
        border-top: 2px solid #f2f6fc;
        padding-top: 12px;
        margin-top: 12px;
    }
    
    .vat-breakdown {
        background: #f8fafc;
        border-radius: 8px;
        padding: 12px;
        margin-top: 15px;
        font-size: 12px;
        color: #5a6a85;
        border: 1px solid #f2f6fc;
    }
    
    .customer-section {
        background: linear-gradient(135deg, #f8fafc 0%, #f2f6fc 100%);
        border-radius: 10px;
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid #e9ecef;
    }
    
    .checkout-btn {
        width: 100%;
        padding: 15px;
        background: linear-gradient(135deg, #5d87ff 0%, #4a73e8 100%);
        color: white;
        border: none;
        border-radius: 12px;
        font-weight: 600;
        font-size: 16px;
        cursor: pointer;
        transition: all 0.3s;
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }
    
    .checkout-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(93, 135, 255, 0.25);
    }
    
    .checkout-btn:disabled {
        background: #dfe5ef;
        color: #9da8b6;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }
    
    .hidden {
        display: none !important;
    }
    
    .mpesa-response {
        background: #e8f5e9;
        border: 1px solid #c8e6c9;
        border-radius: 8px;
        padding: 12px;
        margin-top: 15px;
        color: #2e7d32;
        font-size: 14px;
    }
    
    .fab-container {
        position: fixed;
        bottom: 30px;
        right: 30px;
        display: flex;
        flex-direction: column;
        gap: 15px;
        z-index: 1000;
    }
    
    .fab {
        width: 56px;
        height: 56px;
        border-radius: 16px;
        background: #5d87ff;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        box-shadow: 0 4px 20px rgba(93, 135, 255, 0.3);
        transition: all 0.3s;
        font-size: 20px;
    }
    
    .fab:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 25px rgba(93, 135, 255, 0.4);
        background: #4a73e8;
    }
    
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.5);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 1100;
        padding: 20px;
        backdrop-filter: blur(4px);
    }
    
    .modal-content {
        background: white;
        border-radius: 16px;
        padding: 0;
        width: 100%;
        max-width: 500px;
        max-height: 90vh;
        overflow: hidden;
        box-shadow: 0 20px 25px rgba(0,0,0,0.1);
        animation: modalSlideIn 0.3s ease-out;
    }
    
    @keyframes modalSlideIn {
        from {
            transform: translateY(-30px);
            opacity: 0;
        }
        to {
            transform: translateY(0);
            opacity: 1;
        }
    }
    
    .modal-header {
        padding: 20px 30px;
        border-bottom: 1px solid #f2f6fc;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #fff;
    }
    
    .modal-body {
        padding: 30px;
        max-height: 60vh;
        overflow-y: auto;
    }
    
    .modal-footer {
        padding: 20px 30px;
        border-top: 1px solid #f2f6fc;
        background: #f8fafc;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
    
    .shortcuts-hint {
        position: fixed;
        bottom: 30px;
        left: 30px;
        background: rgba(42, 53, 71, 0.9);
        color: white;
        padding: 12px 16px;
        border-radius: 10px;
        font-size: 12px;
        z-index: 100;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255,255,255,0.1);
    }
    
    .shortcuts-hint div {
        margin-bottom: 4px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .shortcuts-hint div:last-child {
        margin-bottom: 0;
    }
    
    .shortcuts-hint strong {
        color: #5d87ff;
        min-width: 30px;
    }
    
    .category-filter {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        flex-wrap: wrap;
    }
    
    .category-btn {
        padding: 8px 16px;
        background: #f2f6fc;
        border: 1px solid #dfe5ef;
        border-radius: 20px;
        color: #5a6a85;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .category-btn:hover, .category-btn.active {
        background: #5d87ff;
        color: white;
        border-color: #5d87ff;
    }
    
    .customer-item {
        padding: 12px;
        border-radius: 8px;
        margin-bottom: 8px;
        cursor: pointer;
        border: 1px solid #f2f6fc;
        transition: all 0.3s;
    }
    
    .customer-item:hover {
        background: #f2f6fc;
        border-color: #5d87ff;
    }
    
    .barcode-scanner {
        width: 100%;
        height: 300px;
        background: #000;
        border-radius: 10px;
        overflow: hidden;
        margin-bottom: 20px;
    }
    
    .sale-status-badge {
        font-size: 11px;
        padding: 3px 8px;
        border-radius: 4px;
    }
    
    .wizard-progress {
        display: flex;
        justify-content: space-between;
        margin-bottom: 30px;
        position: relative;
    }
    
    .wizard-progress:before {
        content: '';
        position: absolute;
        top: 20px;
        left: 0;
        right: 0;
        height: 2px;
        background: #e9ecef;
        z-index: 1;
    }
    
    .progress-step {
        position: relative;
        z-index: 2;
        text-align: center;
        flex: 1;
    }
    
    .step-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #e9ecef;
        color: #6c757d;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 10px;
        border: 3px solid #fff;
        font-weight: bold;
        font-size: 14px;
    }
    
    .step-circle.active {
        background: #5d87ff;
        color: #fff;
    }
    
    .step-circle.completed {
        background: #13deb9;
        color: #fff;
    }
    
    .step-label {
        font-size: 12px;
        color: #6c757d;
        font-weight: 500;
    }
    
    .step-label.active {
        color: #5d87ff;
        font-weight: 600;
    }
    
    /* Payment Options Grid */
    .payment-options-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        margin-bottom: 25px;
    }
    
    .payment-option-card {
        padding: 20px;
        border: 2px solid #dfe5ef;
        border-radius: 12px;
        background: #fff;
        cursor: pointer;
        transition: all 0.3s;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
    }
    
    .payment-option-card:hover {
        border-color: #5d87ff;
        background: #f8fafc;
        transform: translateY(-2px);
    }
    
    .payment-option-card.active {
        border-color: #5d87ff;
        background: #f2f6fc;
        box-shadow: 0 4px 12px rgba(93, 135, 255, 0.1);
    }
    
    .payment-option-icon {
        width: 50px;
        height: 50px;
        border-radius: 12px;
        background: linear-gradient(135deg, #f2f6fc 0%, #e9ecef 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: #5d87ff;
    }
    
    .payment-option-card.active .payment-option-icon {
        background: linear-gradient(135deg, #5d87ff 0%, #4a73e8 100%);
        color: white;
    }
    
    .payment-option-title {
        font-weight: 600;
        color: #2a3547;
        font-size: 14px;
    }
    
    .payment-option-subtitle {
        font-size: 12px;
        color: #5a6a85;
    }
    
    .payment-form-section {
        animation: fadeIn 0.3s ease-out;
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .cash-details {
        background: #f8fafc;
        border-radius: 10px;
        padding: 20px;
        margin-top: 15px;
    }
    
    .amount-display {
        font-size: 24px;
        font-weight: 700;
        color: #2a3547;
        text-align: center;
        margin-bottom: 20px;
    }
    
    .change-display {
        background: #e8f5e9;
        border-radius: 8px;
        padding: 15px;
        margin-top: 20px;
        text-align: center;
        border: 1px solid #c8e6c9;
    }
    
    .change-display .label {
        font-size: 12px;
        color: #2e7d32;
        margin-bottom: 5px;
    }
    
    .change-display .amount {
        font-size: 20px;
        font-weight: 700;
        color: #2e7d32;
    }
    
    /* Keyboard focus styles */
    .product-card:focus,
    .payment-option-card:focus,
    .quantity-btn:focus {
        outline: 2px solid #5d87ff;
        outline-offset: 2px;
    }
    
    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }
    
    ::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }
    
    .empty-cart {
        text-align: center;
        padding: 60px 20px;
        color: #9da8b6;
    }
    
    .empty-cart i {
        font-size: 48px;
        margin-bottom: 15px;
        color: #dfe5ef;
    }
    
    .alert-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1200;
        min-width: 300px;
        animation: slideInRight 0.3s ease;
    }
    
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @media (max-width: 1200px) {
        .pos-container {
            grid-template-columns: 1fr;
            gap: 20px;
        }
        
        .cart-section {
            height: auto;
            min-height: 500px;
        }
    }
    
    @media (max-width: 768px) {
        .product-grid {
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        }
        
        .cart-item {
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
        }
        
        .cart-item-controls {
            width: 100%;
            justify-content: space-between;
        }
        
        .payment-options-grid {
            grid-template-columns: 1fr;
        }
        
        .fab-container {
            bottom: 20px;
            right: 20px;
        }
        
        .fab {
            width: 50px;
            height: 50px;
            border-radius: 14px;
            font-size: 18px;
        }
    }
</style>
@endsection

@section('content')
<div class="page-wrapper">
    <div class="page-content">
        <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
            <div class="breadcrumb-title pe-3">
                <i class="bx bx-cart me-1"></i> Point of Sale
            </div>
            <div class="ps-3">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 p-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}"><i class="bx bx-home-alt"></i></a></li>
                        <li class="breadcrumb-item active" aria-current="page">POS</li>
                    </ol>
                </nav>
            </div>
            <div class="ms-auto">
                <div class="btn-group">
                    <button class="btn btn-outline-primary" id="newSaleBtn">
                        <i class="bx bx-receipt me-2"></i>New Sale
                    </button>
                    <button class="btn btn-outline-secondary" id="holdSaleBtn">
                        <i class="bx bx-pause me-2"></i>Hold Sale
                    </button>
                    <button class="btn btn-outline-info" id="savedSalesBtn">
                        <i class="bx bx-history me-2"></i>Saved Sales
                    </button>
                </div>
            </div>
        </div>

        <div class="pos-container">
            <!-- Left Section: Product Search & Selection -->
            <div class="product-search-section">
                <!-- Customer Section -->
                <div class="customer-section">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">Customer</h5>
                        <button class="btn btn-sm btn-light" id="selectCustomerBtn">
                            <i class="bx bx-user-plus me-1"></i>Select Customer
                        </button>
                    </div>
                    <div id="customerDisplay">
                        <div class="text-muted">Walk-in Customer</div>
                    </div>
                    <input type="hidden" id="customerId" value="">
                </div>
                
                <!-- Search Box -->
                <div class="search-box mb-4">
                    <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                            <i class="bx bx-search"></i>
                        </span>
                        <input type="text" 
                               class="form-control border-start-0" 
                               id="productSearch" 
                               placeholder="Scan barcode or search by name, SKU..."
                               autofocus>
                        <button class="btn btn-light border" id="scanBarcodeBtn">
                            <i class="bx bx-barcode"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Category Filters -->
                <div class="category-filter" id="categoryFilters">
                    <button class="category-btn active" data-category="all">All</button>
                    <!-- Categories will be loaded here -->
                </div>
                
                <!-- Product Grid -->
                <div class="product-grid" id="productGrid">
                    <!-- Products will be loaded here -->
                </div>
            </div>
            
            <!-- Right Section: Shopping Cart & Checkout -->
            <div class="cart-section">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">Shopping Cart</h5>
                    <span class="badge bg-light text-dark" id="cartCount">0 items</span>
                </div>
                
                <!-- Cart Items -->
                <div class="cart-items" id="cartItems">
                    <div class="empty-cart">
                        <i class="bx bx-cart"></i>
                        <p>No items in cart</p>
                    </div>
                </div>
                
                <!-- Cart Summary -->
                <div class="cart-summary">
                    <div class="summary-row">
                        <span>Subtotal:</span>
                        <span id="subtotal">KES 0.00</span>
                    </div>
                    <div class="summary-row">
                        <span>VAT (16%):</span>
                        <span id="vatAmount">KES 0.00</span>
                    </div>
                    <div class="summary-row">
                        <span>Discount:</span>
                        <span id="discountAmount">KES 0.00</span>
                    </div>
                    <div class="summary-row total">
                        <span>Total:</span>
                        <span id="totalAmount">KES 0.00</span>
                    </div>
                    
                    <div class="vat-breakdown" id="vatBreakdown">
                        <div class="text-muted mb-1">VAT Breakdown:</div>
                        <div>VATable Amount: KES 0.00</div>
                        <div>VAT Rate: 16%</div>
                        <div>VAT Amount: KES 0.00</div>
                    </div>
                    
                    <!-- Checkout Button -->
                    <button class="checkout-btn" id="checkoutBtn" disabled>
                        <i class="bx bx-credit-card me-2"></i>Proceed to Checkout
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Shortcuts Hint -->
        <div class="shortcuts-hint">
            <div><strong>F1:</strong> Search Product</div>
            <div><strong>F2:</strong> Select Customer</div>
            <div><strong>F3:</strong> New Sale</div>
            <div><strong>F8:</strong> Checkout</div>
        </div>
        
        <!-- Floating Action Buttons -->
        <div class="fab-container">
            <div class="fab" title="Print Receipt" id="printReceiptFab">
                <i class="bx bx-printer"></i>
            </div>
            <div class="fab" title="Quick Discount" id="quickDiscountFab">
                <i class="bx bx-percent"></i>
            </div>
            <div class="fab" title="Hold Sale" id="holdSaleFab">
                <i class="bx bx-pause"></i>
            </div>
        </div>
    </div>
</div>

<!-- Customer Selection Modal -->
<div class="modal-overlay" id="customerModal">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Select Customer</h5>
            <button type="button" class="btn-close" id="closeCustomerModal"></button>
        </div>
        <div class="modal-body">
            <div class="mb-3">
                <input type="text" class="form-control" id="customerSearch" placeholder="Search customers...">
            </div>
            <div class="customer-list" id="customerList" style="max-height: 300px; overflow-y: auto;">
                <!-- Customers will be loaded here -->
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-light" id="quickAddCustomer">
                <i class="bx bx-plus me-2"></i>Quick Add Customer
            </button>
            <button class="btn btn-secondary" id="cancelCustomerSelection">Cancel</button>
        </div>
    </div>
</div>

<!-- Discount Modal -->
<div class="modal-overlay" id="discountModal">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Apply Discount</h5>
            <button type="button" class="btn-close" id="closeDiscountModal"></button>
        </div>
        <div class="modal-body">
            <div class="mb-3">
                <label class="form-label">Discount Type</label>
                <select class="form-select" id="discountType">
                    <option value="amount">Fixed Amount</option>
                    <option value="percent">Percentage</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Discount Value</label>
                <input type="number" class="form-control" id="discountValue" min="0" step="0.01">
            </div>
            <div class="mb-3">
                <label class="form-label">Reason (Optional)</label>
                <input type="text" class="form-control" id="discountReason" placeholder="Seasonal discount, loyalty discount, etc.">
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" id="applyDiscount">Apply Discount</button>
            <button class="btn btn-secondary" id="cancelDiscount">Cancel</button>
        </div>
    </div>
</div>

<!-- Payment Modal -->
<div class="modal-overlay" id="paymentModal">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Payment Method</h5>
            <button type="button" class="btn-close" id="closePaymentModal"></button>
        </div>
        <div class="modal-body">
            <!-- Payment Summary -->
            <div class="mb-4">
                <div class="amount-display" id="paymentTotalAmount">KES 0.00</div>
                <div class="text-center text-muted mb-3">Total Amount Due</div>
            </div>
            
            <!-- Payment Method Selection -->
            <h6 class="mb-3">Select Payment Method</h6>
            <div class="payment-options-grid">
                <div class="payment-option-card" data-method="cash" id="cashPaymentOption">
                    <div class="payment-option-icon">
                        <i class="bx bx-money"></i>
                    </div>
                    <div class="payment-option-title">Cash</div>
                    <div class="payment-option-subtitle">Pay with cash</div>
                </div>
                
                <div class="payment-option-card" data-method="mpesa" id="mpesaPaymentOption">
                    <div class="payment-option-icon">
                        <i class="bx bx-mobile-alt"></i>
                    </div>
                    <div class="payment-option-title">M-Pesa</div>
                    <div class="payment-option-subtitle">Mobile money</div>
                </div>
                
                <div class="payment-option-card" data-method="card" id="cardPaymentOption">
                    <div class="payment-option-icon">
                        <i class="bx bx-credit-card"></i>
                    </div>
                    <div class="payment-option-title">Card</div>
                    <div class="payment-option-subtitle">Credit/Debit card</div>
                </div>
                
                <div class="payment-option-card" data-method="credit" id="creditPaymentOption">
                    <div class="payment-option-icon">
                        <i class="bx bx-credit-card-front"></i>
                    </div>
                    <div class="payment-option-title">Credit</div>
                    <div class="payment-option-subtitle">Pay later</div>
                </div>
            </div>
            
            <!-- Payment Forms -->
            <div class="payment-form-section" id="paymentForms">
                <!-- Cash Payment Form -->
                <div class="cash-payment-form hidden" id="cashPaymentForm">
                    <div class="cash-details">
                        <div class="mb-3">
                            <label class="form-label">Amount Received</label>
                            <div class="input-group">
                                <span class="input-group-text">KES</span>
                                <input type="number" 
                                       class="form-control" 
                                       id="amountReceived" 
                                       placeholder="0.00"
                                       min="0"
                                       step="0.01"
                                       autofocus>
                            </div>
                        </div>
                        
                        <div id="cashChangeDisplay" class="change-display hidden">
                            <div class="label">Change Due</div>
                            <div class="amount" id="changeAmount">KES 0.00</div>
                        </div>
                    </div>
                </div>
                
                <!-- M-Pesa Payment Form -->
                <div class="mpesa-payment-form hidden" id="mpesaPaymentForm">
                    <div class="alert alert-light mb-3">
                        <i class="bx bx-info-circle me-2"></i>
                        Enter phone number to send payment request
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Phone Number</label>
                        <input type="tel" 
                               class="form-control" 
                               id="mpesaPhone"
                               placeholder="07XXXXXXXX"
                               pattern="[0-9]{10}">
                    </div>
                    <div id="mpesaResponse" class="mpesa-response hidden">
                        <!-- M-Pesa response will be shown here -->
                    </div>
                </div>
                
                <!-- Card Payment Form -->
                <div class="card-payment-form hidden" id="cardPaymentForm">
                    <div class="alert alert-light mb-3">
                        <i class="bx bx-info-circle me-2"></i>
                        Connect card reader or enter manual details
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Card Number</label>
                        <input type="text" 
                               class="form-control" 
                               id="cardNumber"
                               placeholder="1234 5678 9012 3456"
                               maxlength="19">
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Expiry Date</label>
                            <input type="text" 
                                   class="form-control" 
                                   id="cardExpiry"
                                   placeholder="MM/YY">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">CVV</label>
                            <input type="text" 
                                   class="form-control" 
                                   id="cardCvv"
                                   placeholder="123"
                                   maxlength="3">
                        </div>
                    </div>
                </div>
                
                <!-- Credit Payment Form -->
                <div class="credit-payment-form hidden" id="creditPaymentForm">
                    <div class="alert alert-light mb-3">
                        <i class="bx bx-info-circle me-2"></i>
                        Credit sale will be recorded and payment can be made later
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Payment Terms (days)</label>
                        <input type="number" 
                               class="form-control" 
                               id="creditTerms"
                               value="30"
                               min="1">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Notes (Optional)</label>
                        <textarea class="form-control" 
                                  id="creditNotes" 
                                  rows="2"
                                  placeholder="Additional notes for this credit sale..."></textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-light" id="backToMethodsBtn" style="display: none;">
                <i class="bx bx-arrow-back me-2"></i>Back
            </button>
            <button class="btn btn-secondary" id="cancelPayment">Cancel</button>
            <button class="btn btn-primary" id="completePayment">
                <span id="paymentButtonText">Complete Payment</span>
                <span id="paymentLoading" class="hidden ms-2">
                    <i class="bx bx-loader-circle bx-spin"></i>
                </span>
            </button>
        </div>
    </div>
</div>

<!-- Barcode Scanner Modal -->
<div class="modal-overlay" id="barcodeModal">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Scan Barcode</h5>
            <button type="button" class="btn-close" id="closeBarcodeModal"></button>
        </div>
        <div class="modal-body">
            <div class="text-center">
                <div class="barcode-scanner" id="barcodeScanner">
                    <video id="barcodeVideo" width="100%" height="100%"></video>
                </div>
                <div class="mt-3">
                    <p class="text-muted">Point camera at barcode to scan</p>
                    <button class="btn btn-light" id="toggleCamera">
                        <i class="bx bx-camera me-2"></i>Toggle Camera
                    </button>
                </div>
            </div>
            <div class="mt-3">
                <input type="text" 
                       class="form-control" 
                       id="manualBarcode"
                       placeholder="Or enter barcode manually">
            </div>
        </div>
    </div>
</div>

<!-- Saved Sales Modal -->
<div class="modal-overlay" id="savedSalesModal">
    <div class="modal-content" style="max-width: 800px;">
        <div class="modal-header">
            <h5 class="modal-title">Saved & Hold Sales</h5>
            <button type="button" class="btn-close" id="closeSavedSalesModal"></button>
        </div>
        <div class="modal-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Sale ID</th>
                            <th>Customer</th>
                            <th>Items</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Saved At</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="savedSalesTable">
                        <!-- Saved sales will be loaded here -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Receipt Preview Modal -->
<div class="modal-overlay" id="receiptModal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h5 class="modal-title">Receipt</h5>
            <button type="button" class="btn-close" id="closeReceiptModal"></button>
        </div>
        <div class="modal-body">
            <div id="receiptContent" style="font-family: 'Courier New', monospace; font-size: 14px;">
                <!-- Receipt content will be loaded here -->
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-light" id="printReceiptBtn">
                <i class="bx bx-printer me-2"></i>Print
            </button>
            <button class="btn btn-primary" id="emailReceiptBtn">
                <i class="bx bx-envelope me-2"></i>Email
            </button>
            <button class="btn btn-secondary" id="closeReceiptBtn">Close</button>
        </div>
    </div>
</div>
@endsection

@section('script')
<script>
    // Global variables
    let cart = [];
    let customer = null;
    let currentPaymentMethod = null;
    let categories = [];
    let scanner = null;
    let currentSaleId = null;
    
    // Initialize POS
    document.addEventListener('DOMContentLoaded', function() {
        initializePOS();
        loadCategories();
        loadProducts();
        setupEventListeners();
        setupKeyboardShortcuts();
    });
    
    function initializePOS() {
        updateCartDisplay();
        updateSummary();
        updateCheckoutButton();
    }
    
function loadCategories() {
    fetch('{{ route("api.categories") }}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                categories = data.categories;
                renderCategoryFilters();
            }
        })
        .catch(error => console.error('Error loading categories:', error));
}
    
function renderCategoryFilters() {
    const container = document.getElementById('categoryFilters');
    container.innerHTML = '';
    
    // Add "All" button
    const allBtn = document.createElement('button');
    allBtn.className = 'category-btn active';
    allBtn.textContent = 'All';
    allBtn.dataset.category = 'all';
    allBtn.onclick = () => filterProductsByCategory('all');
    container.appendChild(allBtn);
    
    // Add category buttons
    categories.forEach(category => {
        const btn = document.createElement('button');
        btn.className = 'category-btn';
        btn.textContent = category.name;
        btn.dataset.category = category.id;
        btn.onclick = () => filterProductsByCategory(category.id);
        btn.style.borderLeftColor = category.color || '#5d87ff';
        btn.style.borderLeftWidth = '4px';
        container.appendChild(btn);
    });
}
    
    function filterProductsByCategory(categoryId) {
        // Update active button
        document.querySelectorAll('.category-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');
        
        loadProducts(categoryId === 'all' ? null : categoryId);
    }
    
  function loadProducts(categoryId = null) {
    let url = '{{ route("api.products") }}?limit=50';
    if (categoryId) {
        url += `&category_id=${categoryId}`;
    }
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderProducts(data.products);
            }
        })
        .catch(error => console.error('Error loading products:', error));
}

    
function renderProducts(products) {
    const container = document.getElementById('productGrid');
    container.innerHTML = '';
    
    if (products.length === 0) {
        container.innerHTML = `
            <div class="col-12 text-center py-5">
                <i class="bx bx-package bx-lg text-muted mb-3"></i>
                <p class="text-muted">No products found</p>
            </div>
        `;
        return;
    }
    
    products.forEach(product => {
        const card = document.createElement('div');
        card.className = 'product-card';
        card.onclick = () => addToCart(product);
        card.tabIndex = 0;
        card.onkeypress = (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                addToCart(product);
            }
        };
        
        // Format price with VAT info
        let priceHtml = `<div class="product-price">KES ${product.final_price.toFixed(2)}</div>`;
        if (product.is_vatable) {
            priceHtml += `<small class="text-muted">Incl. VAT ${product.tax_rate}%</small>`;
        }
        
        card.innerHTML = `
            <div class="product-name">${product.name}</div>
            ${priceHtml}
            <div class="product-stock">${product.stock} in stock</div>
            ${product.is_low_stock ? '<span class="badge bg-warning bg-opacity-10 text-warning mt-2">Low Stock</span>' : ''}
            ${product.is_vatable ? '<span class="badge bg-info bg-opacity-10 text-info mt-2">VAT</span>' : ''}
        `;
        container.appendChild(card);
    });
}
    
function searchProducts(query) {
    fetch(`{{ route("api.products") }}?search=${encodeURIComponent(query)}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderProducts(data.products);
            }
        })
        .catch(error => console.error('Error searching products:', error));
}
    
    function addToCart(product, quantity = 1) {
        // Check if product already in cart
        const existingItem = cart.find(item => item.id === product.id);
        
        if (existingItem) {
            // Check stock availability
            if (existingItem.quantity + quantity > product.stock) {
                showAlert('error', `Only ${product.stock} units available in stock`);
                return;
            }
            existingItem.quantity += quantity;
        } else {
            // Check stock availability
            if (quantity > product.stock) {
                showAlert('error', `Only ${product.stock} units available in stock`);
                return;
            }
            
            cart.push({
                id: product.id,
                sku: product.sku,
                name: product.name,
                price: product.final_price,
                cost_price: product.cost_price,
                quantity: quantity,
                tax_rate: product.tax_rate || 16,
                is_vatable: product.is_vatable || false,
                stock: product.stock
            });
        }
        
        updateCartDisplay();
        updateSummary();
        updateCheckoutButton();
        showAlert('success', `${product.name} added to cart`);
        
        // Focus back on search
        document.getElementById('productSearch').focus();
    }
    
    function updateCartDisplay() {
        const container = document.getElementById('cartItems');
        const cartCount = document.getElementById('cartCount');
        
        if (cart.length === 0) {
            container.innerHTML = `
                <div class="empty-cart">
                    <i class="bx bx-cart"></i>
                    <p>No items in cart</p>
                </div>
            `;
            cartCount.textContent = '0 items';
            return;
        }
        
        container.innerHTML = '';
        cartCount.textContent = `${cart.length} ${cart.length === 1 ? 'item' : 'items'}`;
        
        cart.forEach((item, index) => {
            const itemDiv = document.createElement('div');
            itemDiv.className = 'cart-item';
            itemDiv.innerHTML = `
                <div class="cart-item-info">
                    <div class="cart-item-name">${item.name}</div>
                    <div class="cart-item-price">KES ${item.price.toFixed(2)} each</div>
                    ${item.is_vatable ? '<span class="badge bg-info bg-opacity-10 text-info">VAT</span>' : ''}
                </div>
                <div class="cart-item-controls">
                    <div class="quantity-control">
                        <button class="quantity-btn" onclick="updateQuantity(${index}, -1)">-</button>
                        <input type="number" 
                               class="quantity-input" 
                               value="${item.quantity}" 
                               min="1" 
                               max="${item.stock}"
                               onchange="updateQuantity(${index}, 0, this.value)">
                        <button class="quantity-btn" onclick="updateQuantity(${index}, 1)">+</button>
                    </div>
                    <div class="ms-3">
                        <strong>KES ${(item.price * item.quantity).toFixed(2)}</strong>
                    </div>
                    <button class="btn btn-sm btn-light ms-2" onclick="removeFromCart(${index})">
                        <i class="bx bx-trash"></i>
                    </button>
                </div>
            `;
            container.appendChild(itemDiv);
        });
    }
    
    function updateQuantity(index, change, newValue = null) {
        const item = cart[index];
        
        if (newValue !== null) {
            newValue = parseInt(newValue);
            if (isNaN(newValue) || newValue < 1) newValue = 1;
            if (newValue > item.stock) {
                showAlert('error', `Only ${item.stock} units available in stock`);
                newValue = item.stock;
            }
            item.quantity = newValue;
        } else {
            const newQuantity = item.quantity + change;
            if (newQuantity < 1) {
                removeFromCart(index);
                return;
            }
            if (newQuantity > item.stock) {
                showAlert('error', `Only ${item.stock} units available in stock`);
                return;
            }
            item.quantity = newQuantity;
        }
        
        updateCartDisplay();
        updateSummary();
        updateCheckoutButton();
    }
    
    function removeFromCart(index) {
        cart.splice(index, 1);
        updateCartDisplay();
        updateSummary();
        updateCheckoutButton();
    }
    
    function updateSummary() {
        const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        const vatableAmount = cart
            .filter(item => item.is_vatable)
            .reduce((sum, item) => sum + (item.price * item.quantity), 0);
        const vatAmount = vatableAmount * 0.16; // Kenya VAT rate 16%
        
        // Calculate discount if any
        let discount = 0;
        const discountElement = document.getElementById('discountValue');
        if (discountElement && discountElement.value) {
            discount = parseFloat(discountElement.value) || 0;
        }
        
        const total = subtotal + vatAmount - discount;
        
        // Update display
        document.getElementById('subtotal').textContent = `KES ${subtotal.toFixed(2)}`;
        document.getElementById('vatAmount').textContent = `KES ${vatAmount.toFixed(2)}`;
        document.getElementById('discountAmount').textContent = `KES ${discount.toFixed(2)}`;
        document.getElementById('totalAmount').textContent = `KES ${total.toFixed(2)}`;
        
        // Update VAT breakdown
        const vatBreakdown = document.getElementById('vatBreakdown');
        vatBreakdown.innerHTML = `
            <div class="text-muted mb-1">VAT Breakdown:</div>
            <div>VATable Amount: KES ${vatableAmount.toFixed(2)}</div>
            <div>VAT Rate: 16%</div>
            <div>VAT Amount: KES ${vatAmount.toFixed(2)}</div>
        `;
    }
    
    function updateCheckoutButton() {
        const checkoutBtn = document.getElementById('checkoutBtn');
        const total = parseFloat(document.getElementById('totalAmount').textContent.replace('KES ', '')) || 0;
        
        if (cart.length === 0 || total === 0) {
            checkoutBtn.disabled = true;
            checkoutBtn.innerHTML = '<i class="bx bx-credit-card me-2"></i>Proceed to Checkout';
        } else {
            checkoutBtn.disabled = false;
            checkoutBtn.innerHTML = `<i class="bx bx-credit-card me-2"></i>Checkout KES ${total.toFixed(2)}`;
        }
    }
    
    function setupEventListeners() {
        // Product Search
        document.getElementById('productSearch').addEventListener('input', function(e) {
            const query = e.target.value.trim();
            if (query.length >= 2) {
                searchProducts(query);
            } else if (query.length === 0) {
                loadProducts();
            }
        });
        
        // Customer Selection
        document.getElementById('selectCustomerBtn').addEventListener('click', showCustomerModal);
        
        // Checkout Button
        document.getElementById('checkoutBtn').addEventListener('click', showPaymentModal);
        
        // New Sale
        document.getElementById('newSaleBtn').addEventListener('click', newSale);
        
        // Hold Sale
        document.getElementById('holdSaleBtn').addEventListener('click', holdSale);
        document.getElementById('holdSaleFab').addEventListener('click', holdSale);
        
        // Saved Sales
        document.getElementById('savedSalesBtn').addEventListener('click', showSavedSales);
        
        // Quick Discount
        document.getElementById('quickDiscountFab').addEventListener('click', showDiscountModal);
        
        // Print Receipt
        document.getElementById('printReceiptFab').addEventListener('click', printReceipt);
        
        // Barcode Scanner
        document.getElementById('scanBarcodeBtn').addEventListener('click', showBarcodeScanner);
        
        // Modal Close Buttons
        document.getElementById('closeCustomerModal').addEventListener('click', hideCustomerModal);
        document.getElementById('closeDiscountModal').addEventListener('click', hideDiscountModal);
        document.getElementById('closeBarcodeModal').addEventListener('click', hideBarcodeScanner);
        document.getElementById('closeSavedSalesModal').addEventListener('click', hideSavedSalesModal);
        document.getElementById('closePaymentModal').addEventListener('click', hidePaymentModal);
        document.getElementById('closeReceiptModal').addEventListener('click', hideReceiptModal);
        
        // Payment Modal Events
        document.getElementById('cancelPayment').addEventListener('click', hidePaymentModal);
        document.getElementById('backToMethodsBtn').addEventListener('click', showPaymentMethods);
        
        // Payment Method Selection
        document.querySelectorAll('.payment-option-card').forEach(card => {
            card.addEventListener('click', function() {
                selectPaymentMethod(this.dataset.method);
            });
        });
        
        // Cash Payment
        document.getElementById('amountReceived')?.addEventListener('input', updateCashChange);
        
        // Complete Payment
        document.getElementById('completePayment').addEventListener('click', processPayment);
        
        // Customer Modal Events
        document.getElementById('customerSearch')?.addEventListener('input', function(e) {
            searchCustomers(e.target.value);
        });
        
        document.getElementById('quickAddCustomer')?.addEventListener('click', quickAddCustomer);
        document.getElementById('cancelCustomerSelection')?.addEventListener('click', hideCustomerModal);
        
        // Discount Modal Events
        document.getElementById('applyDiscount')?.addEventListener('click', applyDiscount);
        document.getElementById('cancelDiscount')?.addEventListener('click', hideDiscountModal);
        
        // Manual barcode entry
        document.getElementById('manualBarcode')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const barcode = this.value.trim();
                if (barcode) {
                    searchProducts(barcode);
                    hideBarcodeScanner();
                }
            }
        });
        
        // Receipt Modal
        document.getElementById('printReceiptBtn').addEventListener('click', function() {
            window.print();
        });
        
        document.getElementById('emailReceiptBtn').addEventListener('click', emailReceipt);
        document.getElementById('closeReceiptBtn').addEventListener('click', hideReceiptModal);
    }
    
    function showPaymentModal() {
        if (cart.length === 0) {
            showAlert('error', 'Cart is empty');
            return;
        }
        
        // Update payment total
        const total = document.getElementById('totalAmount').textContent;
        document.getElementById('paymentTotalAmount').textContent = total;
        
        // Reset payment selection
        document.querySelectorAll('.payment-option-card').forEach(card => {
            card.classList.remove('active');
        });
        currentPaymentMethod = null;
        
        // Hide all forms
        document.querySelectorAll('.payment-form-section > div').forEach(form => {
            form.classList.add('hidden');
        });
        
        // Show back button as hidden initially
        document.getElementById('backToMethodsBtn').style.display = 'none';
        
        // Reset button text
        document.getElementById('paymentButtonText').textContent = 'Complete Payment';
        document.getElementById('paymentLoading').classList.add('hidden');
        
        // Show modal
        document.getElementById('paymentModal').style.display = 'flex';
    }
    
    function hidePaymentModal() {
        document.getElementById('paymentModal').style.display = 'none';
        resetPaymentForms();
    }
    
    function selectPaymentMethod(method) {
        currentPaymentMethod = method;
        
        // Update active card
        document.querySelectorAll('.payment-option-card').forEach(card => {
            card.classList.remove('active');
        });
        document.getElementById(`${method}PaymentOption`).classList.add('active');
        
        // Show payment form
        document.querySelectorAll('.payment-form-section > div').forEach(form => {
            form.classList.add('hidden');
        });
        document.getElementById(`${method}PaymentForm`).classList.remove('hidden');
        
        // Show back button
        document.getElementById('backToMethodsBtn').style.display = 'block';
        
        // Set focus on first input
        setTimeout(() => {
            const firstInput = document.getElementById(`${method}PaymentForm`).querySelector('input');
            if (firstInput) firstInput.focus();
        }, 100);
    }
    
    function showPaymentMethods() {
        currentPaymentMethod = null;
        
        // Remove active from cards
        document.querySelectorAll('.payment-option-card').forEach(card => {
            card.classList.remove('active');
        });
        
        // Hide all forms
        document.querySelectorAll('.payment-form-section > div').forEach(form => {
            form.classList.add('hidden');
        });
        
        // Hide back button
        document.getElementById('backToMethodsBtn').style.display = 'none';
    }
    
    function updateCashChange() {
        const amountReceived = parseFloat(document.getElementById('amountReceived').value) || 0;
        const total = parseFloat(document.getElementById('totalAmount').textContent.replace('KES ', ''));
        const change = amountReceived - total;
        
        const changeDisplay = document.getElementById('cashChangeDisplay');
        const changeAmount = document.getElementById('changeAmount');
        
        if (amountReceived > 0 && change >= 0) {
            changeAmount.textContent = `KES ${change.toFixed(2)}`;
            changeDisplay.classList.remove('hidden');
        } else {
            changeDisplay.classList.add('hidden');
        }
    }
    
    function resetPaymentForms() {
        // Reset all form values
        document.getElementById('amountReceived').value = '';
        document.getElementById('mpesaPhone').value = '';
        document.getElementById('cardNumber').value = '';
        document.getElementById('cardExpiry').value = '';
        document.getElementById('cardCvv').value = '';
        document.getElementById('creditTerms').value = '30';
        document.getElementById('creditNotes').value = '';
        
        // Hide all responses
        document.getElementById('mpesaResponse').classList.add('hidden');
        document.getElementById('cashChangeDisplay').classList.add('hidden');
    }
    
    function processPayment() {
        if (!currentPaymentMethod) {
            showAlert('error', 'Please select a payment method');
            return;
        }
        
        // Show loading
        document.getElementById('paymentButtonText').textContent = 'Processing...';
        document.getElementById('paymentLoading').classList.remove('hidden');
        document.getElementById('completePayment').disabled = true;
        
        switch(currentPaymentMethod) {
            case 'cash':
                processCashPayment();
                break;
            case 'mpesa':
                processMpesaPayment();
                break;
            case 'card':
                processCardPayment();
                break;
            case 'credit':
                processCreditPayment();
                break;
        }
    }
    
    function processCashPayment() {
        const amountReceived = parseFloat(document.getElementById('amountReceived').value);
        const total = parseFloat(document.getElementById('totalAmount').textContent.replace('KES ', ''));
        
        if (!amountReceived || amountReceived < total) {
            showAlert('error', 'Insufficient payment');
            resetPaymentButton();
            return;
        }
        
        processSale('cash', {
            amount_received: amountReceived,
            change: amountReceived - total
        });
    }
    
    async function processMpesaPayment() {
        const phone = document.getElementById('mpesaPhone').value.trim();
        if (!phone || !/^[0-9]{10}$/.test(phone)) {
            showAlert('error', 'Please enter a valid 10-digit phone number');
            resetPaymentButton();
            return;
        }
        
        const total = parseFloat(document.getElementById('totalAmount').textContent.replace('KES ', ''));
        
        try {
            const response = await fetch('/pos/process-mpesa', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({
                    phone: phone,
                    amount: total,
                    cart: cart,
                    customer_id: document.getElementById('customerId').value
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                document.getElementById('mpesaResponse').classList.remove('hidden');
                document.getElementById('mpesaResponse').innerHTML = `
                    <div class="text-success">
                        <i class="bx bx-check-circle me-2"></i>
                        ${data.message}
                    </div>
                    <div class="mt-2 small">Check your phone to complete payment</div>
                `;
                
                // Change button text
                document.getElementById('paymentButtonText').textContent = 'Waiting for Payment...';
                
                // Start polling for payment confirmation
                pollMpesaPayment(data.transaction_id);
            } else {
                showAlert('error', data.message || 'M-Pesa payment failed');
                resetPaymentButton();
            }
        } catch (error) {
            console.error('M-Pesa error:', error);
            showAlert('error', 'Failed to initiate M-Pesa payment');
            resetPaymentButton();
        }
    }
    
    async function pollMpesaPayment(transactionId) {
        let attempts = 0;
        const maxAttempts = 30; // 30 * 2 seconds = 60 seconds
        
        const poll = setInterval(async () => {
            attempts++;
            
            try {
                const response = await fetch(`/pos/check-mpesa-payment/${transactionId}`);
                const data = await response.json();
                
                if (data.status === 'success') {
                    clearInterval(poll);
                    document.getElementById('mpesaResponse').innerHTML = `
                        <div class="text-success">
                            <i class="bx bx-check-circle me-2"></i>
                            Payment confirmed!
                        </div>
                    `;
                    processSale('mpesa', {
                        mpesa_receipt: data.mpesa_receipt,
                        phone: data.phone,
                        transaction_id: transactionId
                    });
                } else if (data.status === 'failed' || attempts >= maxAttempts) {
                    clearInterval(poll);
                    showAlert('error', 'M-Pesa payment timed out or failed');
                    resetPaymentButton();
                }
            } catch (error) {
                console.error('Polling error:', error);
                if (attempts >= maxAttempts) {
                    clearInterval(poll);
                    showAlert('error', 'Payment confirmation timeout');
                    resetPaymentButton();
                }
            }
        }, 2000); // Poll every 2 seconds
    }
    
    function processCardPayment() {
        const cardNumber = document.getElementById('cardNumber').value.trim();
        const cardExpiry = document.getElementById('cardExpiry').value.trim();
        const cardCvv = document.getElementById('cardCvv').value.trim();
        
        if (!cardNumber || !cardExpiry || !cardCvv) {
            showAlert('error', 'Please fill all card details');
            resetPaymentButton();
            return;
        }
        
        processSale('card', {
            card_last_four: cardNumber.slice(-4),
            card_expiry: cardExpiry
        });
    }
    
    function processCreditPayment() {
        const terms = document.getElementById('creditTerms').value;
        const notes = document.getElementById('creditNotes').value;
        
        processSale('credit', {
            payment_terms: terms,
            notes: notes
        });
    }
    
    function resetPaymentButton() {
        document.getElementById('paymentButtonText').textContent = 'Complete Payment';
        document.getElementById('paymentLoading').classList.add('hidden');
        document.getElementById('completePayment').disabled = false;
    }
    
    function processSale(paymentMethod, paymentDetails = {}) {
        const saleData = {
            cart: cart,
            customer_id: document.getElementById('customerId').value,
            payment_method: paymentMethod,
            payment_details: paymentDetails,
            subtotal: parseFloat(document.getElementById('subtotal').textContent.replace('KES ', '')),
            vat: parseFloat(document.getElementById('vatAmount').textContent.replace('KES ', '')),
            discount: parseFloat(document.getElementById('discountAmount').textContent.replace('KES ', '')),
            total: parseFloat(document.getElementById('totalAmount').textContent.replace('KES ', ''))
        };
        
        fetch('/pos/sale', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify(saleData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentSaleId = data.sale_id;
                
                // Hide payment modal
                hidePaymentModal();
                
                // Show success message
                showAlert('success', 'Sale completed successfully');
                
                // Show receipt modal
                showReceipt(data.sale_id);
                
                // Send to eTIMS if enabled
                if (data.send_to_etims) {
                    sendToETIMS(data.sale_id);
                }
            } else {
                showAlert('error', data.message || 'Failed to process sale');
                resetPaymentButton();
            }
        })
        .catch(error => {
            console.error('Sale error:', error);
            showAlert('error', 'Failed to process sale');
            resetPaymentButton();
        });
    }
    
    function sendToETIMS(saleId) {
        fetch(`/pos/send-to-etims/${saleId}`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log('eTIMS response:', data);
                showAlert('info', 'Invoice sent to eTIMS');
            }
        })
        .catch(error => {
            console.error('eTIMS error:', error);
        });
    }
    
    function showReceipt(saleId) {
        fetch(`/sales/${saleId}/receipt-html`)
            .then(response => response.text())
            .then(html => {
                document.getElementById('receiptContent').innerHTML = html;
                document.getElementById('receiptModal').style.display = 'flex';
            })
            .catch(error => {
                console.error('Error loading receipt:', error);
                // Continue with new sale even if receipt fails
                newSale();
            });
    }
    
    function hideReceiptModal() {
        document.getElementById('receiptModal').style.display = 'none';
        // Start new sale after closing receipt
        setTimeout(() => newSale(), 300);
    }
    
    function emailReceipt() {
        if (!currentSaleId) return;
        
        const email = prompt('Enter customer email address:');
        if (!email) return;
        
        fetch(`/sales/${currentSaleId}/email-receipt`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ email: email })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', 'Receipt sent to email');
            } else {
                showAlert('error', 'Failed to send email');
            }
        })
        .catch(error => {
            console.error('Email error:', error);
            showAlert('error', 'Failed to send email');
        });
    }
    
    function newSale() {
        cart = [];
        customer = null;
        currentSaleId = null;
        document.getElementById('customerId').value = '';
        document.getElementById('customerDisplay').innerHTML = '<div class="text-muted">Walk-in Customer</div>';
        
        // Reset discount
        document.getElementById('discountValue').value = '';
        
        updateCartDisplay();
        updateSummary();
        updateCheckoutButton();
        document.getElementById('productSearch').focus();
        
        showAlert('info', 'New sale started');
    }
    
    function holdSale() {
        if (cart.length === 0) {
            showAlert('error', 'Cart is empty');
            return;
        }
        
        const saleName = prompt('Enter name for saved sale (optional):') || 'Hold Sale';
        
        fetch('/pos/hold-sale', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({
                name: saleName,
                cart: cart,
                customer_id: document.getElementById('customerId').value
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', 'Sale saved for later');
                newSale();
            }
        })
        .catch(error => {
            console.error('Hold sale error:', error);
            showAlert('error', 'Failed to save sale');
        });
    }
    
    function showSavedSales() {
        fetch('/pos/saved-sales')
            .then(response => response.json())
            .then(data => {
                renderSavedSales(data);
                document.getElementById('savedSalesModal').style.display = 'flex';
            })
            .catch(error => {
                console.error('Error loading saved sales:', error);
                showAlert('error', 'Failed to load saved sales');
            });
    }
    
    function renderSavedSales(sales) {
        const container = document.getElementById('savedSalesTable');
        container.innerHTML = '';
        
        sales.forEach(sale => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${sale.id}</td>
                <td>${sale.customer_name || 'Walk-in'}</td>
                <td>${sale.item_count} items</td>
                <td>KES ${sale.total.toFixed(2)}</td>
                <td><span class="badge bg-warning bg-opacity-10 text-warning sale-status-badge">${sale.status}</span></td>
                <td>${new Date(sale.created_at).toLocaleString()}</td>
                <td>
                    <button class="btn btn-sm btn-light" onclick="loadSavedSale(${sale.id})">
                        <i class="bx bx-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-light" onclick="deleteSavedSale(${sale.id})">
                        <i class="bx bx-trash"></i>
                    </button>
                </td>
            `;
            container.appendChild(row);
        });
    }
    
    function loadSavedSale(saleId) {
        fetch(`/pos/saved-sales/${saleId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    cart = data.cart;
                    if (data.customer) {
                        customer = data.customer;
                        document.getElementById('customerId').value = customer.id;
                        document.getElementById('customerDisplay').innerHTML = `
                            <div class="fw-bold">${customer.name}</div>
                            <div class="text-muted small">${customer.phone || ''}</div>
                        `;
                    }
                    updateCartDisplay();
                    updateSummary();
                    updateCheckoutButton();
                    hideSavedSalesModal();
                    showAlert('success', 'Sale loaded successfully');
                }
            })
            .catch(error => {
                console.error('Error loading sale:', error);
                showAlert('error', 'Failed to load saved sale');
            });
    }
    
    function deleteSavedSale(saleId) {
        if (confirm('Delete this saved sale?')) {
            fetch(`/pos/saved-sales/${saleId}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSavedSales();
                    showAlert('success', 'Sale deleted');
                }
            })
            .catch(error => {
                console.error('Error deleting sale:', error);
                showAlert('error', 'Failed to delete saved sale');
            });
        }
    }
    
    function hideSavedSalesModal() {
        document.getElementById('savedSalesModal').style.display = 'none';
    }
    
    function showCustomerModal() {
        loadCustomers();
        document.getElementById('customerModal').style.display = 'flex';
    }
    
    function hideCustomerModal() {
        document.getElementById('customerModal').style.display = 'none';
    }
    
function loadCustomers(search = '') {
    let url = '{{ route("api.customers") }}?limit=20';
    if (search) {
        url += `&search=${encodeURIComponent(search)}`;
    }
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderCustomerList(data.customers);
            }
        })
        .catch(error => console.error('Error loading customers:', error));
}
    
    function searchCustomers(query) {
        loadCustomers(query);
    }
    
function renderCustomerList(customers) {
    const container = document.getElementById('customerList');
    container.innerHTML = '';
    
    // Add walk-in customer option
    const walkInDiv = document.createElement('div');
    walkInDiv.className = 'customer-item';
    walkInDiv.innerHTML = `
        <div class="fw-bold">Walk-in Customer</div>
        <div class="text-muted small">No customer selected</div>
    `;
    walkInDiv.addEventListener('click', () => selectWalkInCustomer());
    container.appendChild(walkInDiv);
    
    // Add actual customers
    customers.forEach(customer => {
        const div = document.createElement('div');
        div.className = 'customer-item';
        div.innerHTML = `
            <div class="fw-bold">${customer.name}</div>
            <div class="text-muted small">${customer.phone || 'No phone'}</div>
            <div class="text-muted small">${customer.email || 'No email'}</div>
            ${customer.credit_limit > 0 ? `<div class="text-muted small">Credit: KES ${customer.available_credit.toFixed(2)}</div>` : ''}
        `;
        div.addEventListener('click', () => selectCustomer(customer));
        container.appendChild(div);
    });
}

function selectWalkInCustomer() {
    customer = null;
    document.getElementById('customerDisplay').innerHTML = `
        <div class="text-muted">Walk-in Customer</div>
    `;
    document.getElementById('customerId').value = '';
    hideCustomerModal();
}

function selectCustomer(selectedCustomer) {
    customer = selectedCustomer;
    document.getElementById('customerDisplay').innerHTML = `
        <div class="fw-bold">${customer.name}</div>
        <div class="text-muted small">${customer.phone || ''}</div>
    `;
    document.getElementById('customerId').value = customer.id;
    hideCustomerModal();
}
    
function quickAddCustomer() {
    const name = prompt('Enter customer name:');
    if (name) {
        const phone = prompt('Enter phone number (optional):');
        const email = prompt('Enter email (optional):');
        
       fetch('{{ route("customers.quick-create") }}', {

            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({
                name: name,
                phone: phone || '',
                email: email || '',
                customer_type: 'walk-in'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                selectCustomer(data.customer);
                showAlert('success', 'Customer added successfully');
            } else {
                showAlert('error', data.message || 'Failed to add customer');
            }
        })
        .catch(error => {
            console.error('Error adding customer:', error);
            showAlert('error', 'Failed to add customer');
        });
    }
}
    
    function showDiscountModal() {
        document.getElementById('discountModal').style.display = 'flex';
    }
    
    function hideDiscountModal() {
        document.getElementById('discountModal').style.display = 'none';
    }
    
    function applyDiscount() {
        const type = document.getElementById('discountType').value;
        const value = parseFloat(document.getElementById('discountValue').value);
        
        if (isNaN(value) || value <= 0) {
            showAlert('error', 'Please enter a valid discount value');
            return;
        }
        
        const total = parseFloat(document.getElementById('totalAmount').textContent.replace('KES ', ''));
        
        if (type === 'percent' && value > 100) {
            showAlert('error', 'Discount percentage cannot exceed 100%');
            return;
        }
        
        // Calculate discount amount
        let discountAmount = 0;
        if (type === 'percent') {
            discountAmount = (total * value) / 100;
        } else {
            discountAmount = value;
        }
        
        // Apply discount
        document.getElementById('discountValue').value = discountAmount.toFixed(2);
        updateSummary();
        updateCheckoutButton();
        hideDiscountModal();
        showAlert('success', 'Discount applied');
    }
    
    function printReceipt(saleId = null) {
        if (!saleId && cart.length === 0) {
            showAlert('error', 'Nothing to print');
            return;
        }
        
        let url = '/pos/print-receipt';
        if (saleId) {
            url = `/sales/${saleId}/receipt`;
        }
        
        // Open receipt in new window for printing
        window.open(url, '_blank');
    }
    
    function showBarcodeScanner() {
        document.getElementById('barcodeModal').style.display = 'flex';
        initializeBarcodeScanner();
    }
    
    function hideBarcodeScanner() {
        document.getElementById('barcodeModal').style.display = 'none';
        stopBarcodeScanner();
    }
    
    function initializeBarcodeScanner() {
        // Use QuaggaJS or similar library for barcode scanning
        const video = document.getElementById('barcodeVideo');
        
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ 
                video: { facingMode: 'environment' } 
            })
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function(error) {
                console.error('Camera error:', error);
                showAlert('error', 'Cannot access camera');
            });
        }
    }
    
    function stopBarcodeScanner() {
        const video = document.getElementById('barcodeVideo');
        if (video.srcObject) {
            const tracks = video.srcObject.getTracks();
            tracks.forEach(track => track.stop());
            video.srcObject = null;
        }
    }
    
    function setupKeyboardShortcuts() {
        document.addEventListener('keydown', function(e) {
            // Ignore if typing in input fields
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
                return;
            }
            
            switch(e.key) {
                case 'F1':
                    e.preventDefault();
                    document.getElementById('productSearch').focus();
                    break;
                    
                case 'F2':
                    e.preventDefault();
                    showCustomerModal();
                    break;
                    
                case 'F3':
                    e.preventDefault();
                    newSale();
                    break;
                    
                case 'F8':
                    e.preventDefault();
                    document.getElementById('checkoutBtn').click();
                    break;
                    
                case 'Escape':
                    hideCustomerModal();
                    hideDiscountModal();
                    hideBarcodeScanner();
                    hideSavedSalesModal();
                    hidePaymentModal();
                    hideReceiptModal();
                    break;
                    
                case '+':
                    if (cart.length > 0) {
                        updateQuantity(cart.length - 1, 1);
                    }
                    break;
                    
                case '-':
                    if (cart.length > 0) {
                        updateQuantity(cart.length - 1, -1);
                    }
                    break;
            }
        });
    }
    
    function showAlert(type, message) {
        // Remove existing alerts
        document.querySelectorAll('.alert-toast').forEach(alert => alert.remove());
        
        // Create alert element
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type === 'error' ? 'danger' : type} alert-toast`;
        alertDiv.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="bx ${type === 'success' ? 'bx-check-circle' : type === 'error' ? 'bx-error-circle' : 'bx-info-circle'} me-2"></i>
                <div>${message}</div>
                <button type="button" class="btn-close ms-auto" onclick="this.parentElement.parentElement.remove()"></button>
            </div>
        `;
        
        // Add to page
        document.body.appendChild(alertDiv);
        
        // Auto remove after 3 seconds
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 3000);
    }
</script>
@endsection