@extends('layouts.app')

@section('content')
<div x-data="posSystem()" class="h-[calc(100vh-6rem)] flex flex-col md:flex-row gap-6 max-w-screen-2xl mx-auto">
    
    <div class="flex-1 flex flex-col bg-gray-900 border border-gray-800 rounded-2xl shadow-xl overflow-hidden">
        
        <div class="p-6 border-b border-gray-800 bg-gray-950/50 flex flex-col sm:flex-row gap-4 justify-between items-center shrink-0">
            <div>
                <h2 class="text-xl font-bold text-gray-100 flex items-center gap-2">
                    <svg class="w-6 h-6 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
                    Point of Sale
                </h2>
                <p class="text-sm text-gray-500">Scan barcodes or manually enter SKUs below.</p>
            </div>
            
            <div class="relative w-full sm:w-72">
                <input type="text" 
                       x-model="scanInput" 
                       @keydown.enter.prevent="processScan"
                       @change="processScan"
                       x-ref="scannerInput"
                       list="pos-skus"
                       autofocus
                       autocomplete="off"
                       placeholder="Scan or type SKU..." 
                       class="w-full pl-10 pr-4 py-3 bg-gray-950 border border-gray-700 rounded-xl focus:ring-2 focus:ring-green-500 outline-none text-gray-100 font-mono text-lg shadow-inner">
                <svg class="w-5 h-5 text-gray-500 absolute left-3 top-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                
                <datalist id="pos-skus">
                    @foreach($products as $product)
                        @if($product->sku)
                            <option value="{{ $product->sku }}">{{ $product->name }}</option>
                        @endif
                    @endforeach
                </datalist>
            </div>
        </div>

        <div class="flex-1 overflow-y-auto custom-scrollbar p-0">
            <table class="w-full text-left text-sm text-gray-400">
                <thead class="bg-gray-950 border-b border-gray-800 text-gray-300 sticky top-0 z-10">
                    <tr>
                        <th class="p-4 font-semibold">Item</th>
                        <th class="p-4 font-semibold text-center w-32">Qty</th>
                        <th class="p-4 font-semibold text-right">Price</th>
                        <th class="p-4 font-semibold text-right">Total</th>
                        <th class="p-4 font-semibold text-center w-16"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-800">
                    <tr x-show="cart.length === 0">
                        <td colspan="5" class="p-12 text-center text-gray-500">
                            <svg class="w-12 h-12 mx-auto mb-3 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
                            <p class="text-lg">Cart is empty.</p>
                            <p class="text-sm">Scan an item to begin.</p>
                        </td>
                    </tr>
                    
                    <template x-for="(item, index) in cart" :key="item.id">
                        <tr class="hover:bg-gray-800/30 transition-colors">
                            <td class="p-4">
                                <p class="font-bold text-gray-100" x-text="item.name"></p>
                                <p class="text-xs text-gray-500 font-mono" x-text="item.barcode || item.sku"></p>
                            </td>
                            <td class="p-4">
                                <div class="flex items-center justify-center gap-2">
                                    <button @click="updateQty(index, -1)" class="w-8 h-8 rounded bg-gray-800 hover:bg-gray-700 text-gray-300 flex items-center justify-center transition-colors">-</button>
                                    <span class="w-8 text-center font-bold text-gray-100" x-text="item.quantity"></span>
                                    <button @click="updateQty(index, 1)" class="w-8 h-8 rounded bg-gray-800 hover:bg-gray-700 text-gray-300 flex items-center justify-center transition-colors">+</button>
                                </div>
                            </td>
                            <td class="p-4 text-right font-medium text-gray-300" x-text="formatMoney(item.price)"></td>
                            <td class="p-4 text-right font-bold text-green-400" x-text="formatMoney(item.price * item.quantity)"></td>
                            <td class="p-4 text-center">
                                <button @click="removeItem(index)" class="text-red-500 hover:text-red-400 p-2">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                </button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>

    <div class="w-full md:w-96 flex flex-col bg-gray-900 border border-gray-800 rounded-2xl shadow-xl overflow-hidden shrink-0">
        <div class="p-6 border-b border-gray-800 bg-gray-950/50">
            <h2 class="text-xl font-bold text-gray-100">Order Summary</h2>
        </div>
        
        <div class="p-6 flex-1 flex flex-col justify-between">
            <div class="space-y-4">
                <div class="flex justify-between text-gray-400">
                    <span>Subtotal Items (<span x-text="totalItems"></span>)</span>
                    <span class="font-bold text-gray-200" x-text="formatMoney(subtotal)"></span>
                </div>

                <label class="flex items-center justify-between cursor-pointer group pb-2 border-b border-gray-800/50">
                    <span class="text-sm font-medium text-gray-400 group-hover:text-gray-200 transition-colors">Apply 18% VAT</span>
                    <div class="relative">
                        <input type="checkbox" x-model="includeVat" class="sr-only">
                        <div class="block bg-gray-800 w-10 h-6 rounded-full transition-colors" :class="includeVat ? 'bg-green-500' : 'bg-gray-800'"></div>
                        <div class="absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform" :class="includeVat ? 'transform translate-x-4' : ''"></div>
                    </div>
                </label>

                <div class="flex justify-between text-sm transition-opacity" :class="includeVat ? 'text-gray-400' : 'text-gray-600 opacity-50'">
                    <span>VAT (18%)</span>
                    <span x-text="formatMoney(vatAmount)"></span>
                </div>
                
                <hr class="border-gray-800">
                
                <div class="flex justify-between items-end">
                    <span class="text-lg text-gray-300">Total</span>
                    <span class="text-4xl font-black text-green-500 tracking-tight" x-text="formatMoney(grandTotal)"></span>
                </div>
            </div>

            <div class="mt-8 space-y-3">
                <div x-show="statusMessage" x-transition class="p-3 rounded-lg text-sm font-bold text-center" :class="statusType === 'error' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'bg-green-500/10 text-green-400 border border-green-500/20'" x-text="statusMessage" style="display: none;"></div>

                <button @click="openPaymentModal" 
                        :disabled="cart.length === 0"
                        class="w-full py-4 bg-green-600 hover:bg-green-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-lg font-bold rounded-xl shadow-lg shadow-green-900/20 transition-all flex justify-center items-center gap-2">
                    Proceed to Payment
                </button>
                <button @click="clearCart" :disabled="cart.length === 0" class="w-full py-3 bg-gray-800 hover:bg-gray-700 disabled:opacity-50 text-gray-300 text-sm font-bold rounded-xl transition-all">
                    Cancel Order
                </button>
            </div>
        </div>
    </div>

    <div x-show="checkoutModal" style="display: none;" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4" x-transition.opacity>
        <div @click.away="checkoutModal = false" class="bg-gray-900 border border-gray-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden" x-transition>
            
            <div class="p-6 border-b border-gray-800 bg-gray-950/50 flex justify-between items-center">
                <h2 class="text-xl font-bold text-gray-100">Select Payment Method</h2>
                <button @click="checkoutModal = false" class="text-gray-500 hover:text-gray-300">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
            
            <div class="p-6 space-y-6">
                <div class="text-center p-4 bg-gray-950 rounded-xl border border-gray-800">
                    <p class="text-sm text-gray-500 font-bold tracking-widest uppercase mb-1">Amount Due</p>
                    <p class="text-4xl font-black text-green-500" x-text="formatMoney(grandTotal)"></p>
                </div>

                <div class="grid grid-cols-3 gap-3">
                    <button @click="paymentMethod = 'cash'" :class="paymentMethod === 'cash' ? 'bg-green-500/20 border-green-500 text-green-400' : 'bg-gray-800 border-gray-700 text-gray-400 hover:bg-gray-700'" class="p-4 border rounded-xl flex flex-col items-center gap-2 transition-all">
                        <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
                        <span class="font-bold text-sm">Cash</span>
                    </button>

                    <button @click="paymentMethod = 'mobile_money'" :class="paymentMethod === 'mobile_money' ? 'bg-yellow-500/20 border-yellow-500 text-yellow-400' : 'bg-gray-800 border-gray-700 text-gray-400 hover:bg-gray-700'" class="p-4 border rounded-xl flex flex-col items-center gap-2 transition-all">
                        <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path></svg>
                        <span class="font-bold text-sm">Mobile</span>
                    </button>

                    <button @click="paymentMethod = 'card'" :class="paymentMethod === 'card' ? 'bg-blue-500/20 border-blue-500 text-blue-400' : 'bg-gray-800 border-gray-700 text-gray-400 hover:bg-gray-700'" class="p-4 border rounded-xl flex flex-col items-center gap-2 transition-all">
                        <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path></svg>
                        <span class="font-bold text-sm">Card</span>
                    </button>
                    
                </div>

                <button @click="processPaymentSelection" :disabled="isProcessing" class="w-full py-4 bg-green-600 hover:bg-green-500 disabled:opacity-50 text-white text-lg font-bold rounded-xl shadow-lg shadow-green-900/20 transition-all">
                    <span>Continue</span>
                </button>
            </div>
        </div>
    </div>

    <div x-show="mobileMoneyModal" style="display: none;" class="fixed inset-0 z-[105] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4" x-transition.opacity>
        <div @click.away="mobileMoneyModal = false; checkoutModal = true" class="bg-gray-900 border border-gray-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden" x-transition>
            
            <div class="p-6 border-b border-gray-800 bg-gray-950/50 flex justify-between items-center">
                <div class="flex items-center gap-3">
                    <button @click="mobileMoneyModal = false; checkoutModal = true" class="text-gray-500 hover:text-gray-300 transition-colors">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                    </button>
                    <h2 class="text-xl font-bold text-gray-100">Mobile Money</h2>
                </div>
                <div class="px-3 py-1 bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-xs font-bold rounded-full">
                    TZS <span x-text="grandTotal.toLocaleString()"></span>
                </div>
            </div>
            
            <div class="p-6 space-y-6">
                <div class="flex p-1 bg-gray-950 rounded-lg border border-gray-800">
                    <button @click="mobileFlow = 'push'" :class="mobileFlow === 'push' ? 'bg-gray-800 text-white shadow' : 'text-gray-500 hover:text-gray-300'" class="flex-1 py-2 text-sm font-bold rounded-md transition-all">USSD Push</button>
                    <button @click="mobileFlow = 'manual'" :class="mobileFlow === 'manual' ? 'bg-gray-800 text-white shadow' : 'text-gray-500 hover:text-gray-300'" class="flex-1 py-2 text-sm font-bold rounded-md transition-all">Manual Verify</button>
                </div>

                <div x-show="mobileFlow === 'push'" x-transition.opacity class="space-y-4">
                    <p class="text-sm text-gray-400 text-center">Enter the customer's phone number. They will receive a PIN prompt on their phone to complete the payment.</p>
                    <div>
                        <label class="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-2">Customer Phone Number</label>
                        <div class="relative">
                            <span class="absolute left-4 top-3.5 text-gray-500 font-bold">+255</span>
                            <input type="tel" x-model="customerPhone" placeholder="7XX XXX XXX" class="w-full pl-16 pr-4 py-3 bg-gray-950 border border-gray-700 rounded-xl focus:ring-2 focus:ring-yellow-500 outline-none text-gray-100 font-mono text-lg transition-all">
                        </div>
                    </div>
                    
                    <button @click="submitCheckout" :disabled="!customerPhone || isProcessing" class="w-full py-4 bg-yellow-600 hover:bg-yellow-500 disabled:opacity-50 text-white text-lg font-bold rounded-xl shadow-lg shadow-yellow-900/20 transition-all flex justify-center items-center gap-2">
                        <span x-show="!isProcessing">Send Payment Prompt</span>
                        <span x-show="isProcessing">Waiting for Customer...</span>
                    </button>
                </div>

                <div x-show="mobileFlow === 'manual'" x-transition.opacity style="display: none;" class="space-y-4">
                    <div class="p-4 bg-gray-950 border border-gray-800 rounded-xl text-center space-y-1">
                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider">Pay to Safi Technologies</p>
                        <p class="text-3xl font-black text-white tracking-widest">555 1234</p>
                        <p class="text-xs text-green-500 font-medium pt-1">Lipa Namba (M-Pesa / Tigo Pesa)</p>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-2">Receipt / Reference Code</label>
                        <input type="text" x-model="mobileReference" placeholder="e.g. 9A4M3..." class="w-full px-4 py-3 bg-gray-950 border border-gray-700 rounded-xl focus:ring-2 focus:ring-yellow-500 outline-none text-gray-100 font-mono text-lg transition-all uppercase">
                    </div>
                    
                    <button @click="submitCheckout" :disabled="!mobileReference || isProcessing" class="w-full py-4 bg-yellow-600 hover:bg-yellow-500 disabled:opacity-50 text-white text-lg font-bold rounded-xl shadow-lg shadow-yellow-900/20 transition-all">
                        <span x-show="!isProcessing">Verify & Complete Sale</span>
                        <span x-show="isProcessing">Processing...</span>
                    </button>
                </div>

            </div>
        </div>
    </div>

    <div x-show="receiptModal" style="display: none;" class="fixed inset-0 z-[110] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4" x-transition.opacity>
        <div class="bg-gray-900 border border-gray-800 rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden flex flex-col" x-transition>
            
            <div class="p-6 flex-1 overflow-y-auto custom-scrollbar flex justify-center bg-gray-800">
                <div id="thermal-receipt" class="bg-white text-black p-6 w-80 font-mono text-sm leading-tight shadow-xl">
                    <div class="text-center mb-4">
                        <h2 class="text-xl font-black uppercase mb-1">{{ Auth::user()->company->name ?? 'Store Name' }}</h2>
                        <p class="text-xs">Receipt: <span x-text="receiptData.reference"></span></p>
                        <p class="text-xs">Date: <span x-text="receiptData.date"></span></p>
                        <p class="text-xs">Cashier: {{ Auth::user()->name }}</p>
                    </div>
                    
                    <div class="border-t-2 border-b-2 border-dashed border-black py-2 mb-2">
                        <table class="w-full">
                            <thead>
                                <tr class="text-left font-bold">
                                    <th class="pb-1">Item</th>
                                    <th class="pb-1 text-center">Qty</th>
                                    <th class="pb-1 text-right">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="item in receiptData.items" :key="item.id">
                                    <tr>
                                        <td class="py-1 pr-2 truncate max-w-[120px]" x-text="item.name"></td>
                                        <td class="py-1 text-center" x-text="item.quantity"></td>
                                        <td class="py-1 text-right" x-text="item.price * item.quantity"></td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="text-right text-xs mb-1">
                        <p>Subtotal: <span x-text="formatMoney(receiptData.subtotal)"></span></p>
                        <p>VAT (18%): <span x-text="formatMoney(receiptData.vat)"></span></p>
                    </div>
                    
                    <div class="flex justify-between font-black text-lg mb-1 border-t border-black pt-1">
                        <span>TOTAL:</span>
                        <span x-text="formatMoney(receiptData.total)"></span>
                    </div>
                    <div class="flex justify-between text-xs mb-4">
                        <span>Payment Method:</span>
                        <span class="uppercase font-bold" x-text="receiptData.method"></span>
                    </div>
                    
                    <div class="text-center text-xs mt-6">
                        <p>Thank you for your business!</p>
                        <div class="mt-2 flex justify-center">
                            <svg id="receipt-barcode"></svg>
                        </div>
                    </div>
                </div>
            </div>

            <div class="p-4 bg-gray-950 border-t border-gray-800 flex gap-3">
                <button @click="closeReceipt" class="flex-1 py-3 bg-gray-800 hover:bg-gray-700 text-gray-300 font-bold rounded-xl transition-all">New Sale</button>
                <button @click="printReceipt" class="flex-1 py-3 bg-blue-600 hover:bg-blue-500 text-white font-bold rounded-xl shadow-lg shadow-blue-900/20 transition-all flex justify-center items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
                    Print
                </button>
            </div>
        </div>
    </div>

</div>

<div id="print-zone" class="hidden"></div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('posSystem', () => ({
            catalog: @json($products),
            
            scanInput: '',
            cart: [],

            includeVat: true, 

            isProcessing: false,
            statusMessage: '',
            statusType: '',

            // Payment & Receipt States
            checkoutModal: false,
            receiptModal: false,
            mobileMoneyModal: false, //  Controls the mobile payment screen
            mobileFlow: 'push',      // 'push' (API) or 'manual' (Lipa Namba)
            customerPhone: '',       //  For the USSD Push
            mobileReference: '',     //  For the Manual Receipt Code
            paymentMethod: 'cash',
            checkoutModal: false,
            receiptModal: false,
            paymentMethod: 'cash',
            receiptData: { items: [], subtotal: 0, vat: 0, total: 0, reference: '', date: '', method: '' },
            
            get subtotal() { return this.cart.reduce((total, item) => total + (item.price * item.quantity), 0); },
            get vatAmount() { return this.includeVat ? (this.subtotal * 0.18) : 0; },
            get grandTotal() { return this.subtotal + this.vatAmount; },
            get totalItems() { return this.cart.reduce((total, item) => total + item.quantity, 0); },

            formatMoney(amount) { return new Intl.NumberFormat('en-TZ', { style: 'currency', currency: 'TZS' }).format(amount); },
            
            // NEW: Intercept the checkout button
            processPaymentSelection() {
                if (this.paymentMethod === 'mobile_money') {
                    this.checkoutModal = false;
                    this.mobileMoneyModal = true;
                } else {
                    this.submitCheckout(); // Cash/Card process instantly
                }
            },

            processScan() {
                const input = this.scanInput.trim().toLowerCase();
                if (!input) return;

                const product = this.catalog.find(p => (p.barcode && p.barcode.toLowerCase() === input) || (p.sku && p.sku.toLowerCase() === input));

                if (product) {
                    this.addToCart(product);
                    this.showStatus('Product added.', 'success');
                } else {
                    this.showStatus('Product not found!', 'error');
                }

                this.scanInput = '';
                this.$refs.scannerInput.focus();
            },

            addToCart(product) {
                const existingIndex = this.cart.findIndex(item => item.id === product.id);
                if (existingIndex > -1) {
                    if (this.cart[existingIndex].quantity < product.stock_quantity) {
                        this.cart[existingIndex].quantity++;
                    } else {
                        this.showStatus('Maximum stock reached!', 'error');
                    }
                } else {
                    this.cart.unshift({ id: product.id, name: product.name, sku: product.sku, barcode: product.barcode, price: parseFloat(product.selling_price), stock_limit: product.stock_quantity, quantity: 1 });
                }
            },

            updateQty(index, change) {
                const item = this.cart[index];
                const newQty = item.quantity + change;
                if (newQty > 0 && newQty <= item.stock_limit) item.quantity = newQty;
                else if (newQty > item.stock_limit) this.showStatus('Maximum stock reached!', 'error');
            },

            removeItem(index) { this.cart.splice(index, 1); },

            clearCart() {
                this.cart = [];
                this.showStatus('', '');
                this.$refs.scannerInput.focus();
            },

            showStatus(msg, type) {
                this.statusMessage = msg;
                this.statusType = type;
                if(type === 'error' || type === 'success') setTimeout(() => { this.statusMessage = ''; }, 3000);
            },

            openPaymentModal() {
                if (this.cart.length === 0) return;
                this.checkoutModal = true;
            },

            async submitCheckout() {
                if (this.cart.length === 0) return;
                
                this.isProcessing = true;
                this.statusMessage = '';

                try {
                    const response = await fetch('{{ route('pos.checkout') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json', // <-- NEW: Forces Laravel to send JSON errors instead of HTML crashes
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({
                            cart: this.cart.map(item => ({ id: item.id, quantity: item.quantity })),
                            payment_method: this.paymentMethod,
                            include_vat: this.includeVat,
                            customer_phone: this.customerPhone,     // Sent to backend for future API use
                            mobile_reference: this.mobileReference  // Sent to backend for future API use
                        })
                    });

                    const data = await response.json();

                    if (response.ok && data.success) {
                        // 1. Build Receipt Data
                        this.receiptData = {
                            items: [...this.cart],
                            subtotal: this.subtotal,
                            vat: this.vatAmount,
                            total: this.grandTotal,
                            reference: data.reference,
                            date: data.date,
                            method: this.paymentMethod.replace('_', ' ')
                        };
                        
                        // 2. Hide checkout, clear cart, show receipt
                        this.checkoutModal = false;
                        this.cart = [];
                        this.receiptModal = true;

                        // 3. Render barcode on the receipt using JsBarcode
                        setTimeout(() => {
                            JsBarcode("#receipt-barcode", data.reference, { format: "CODE128", width: 1.5, height: 40, displayValue: false, margin: 0 });
                        }, 100);

                    } else {
                        this.showStatus(data.message || 'Error processing sale.', 'error');
                        this.checkoutModal = false;
                    }
                } catch (error) {
                    this.showStatus('Network error. Check connection.', 'error');
                    this.checkoutModal = false;
                } finally {
                    this.isProcessing = false;
                }
            },

            printReceipt() {
                const printZone = document.getElementById('print-zone');
                const receiptHtml = document.getElementById('thermal-receipt').outerHTML;
                
                const originalBody = document.body.innerHTML;
                document.body.innerHTML = `<div style="display: flex; justify-content: center; padding: 20px;">${receiptHtml}</div>`;
                window.print();
                
                document.body.innerHTML = originalBody;
                window.location.reload(); 
            },

            closeReceipt() {
                this.receiptModal = false;
                window.location.reload(); 
            }
        }))
    })
</script>

<style>
    .custom-scrollbar::-webkit-scrollbar { width: 6px; }
    .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: #374151; border-radius: 8px; }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #4B5563; }
</style>
@endsection