@extends('layouts.pos')

@section('content')
<div class="h-full flex" x-data="posSystem()">
    <!-- Bagian Kiri: Produk & Pencarian -->
    <div class="w-2/3 flex flex-col bg-white border-r border-gray-200 h-full">
        <!-- Pencarian -->
        <div class="p-4 border-b border-gray-200 bg-white">
            <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <svg class="w-6 h-6 text-gray-400" 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>
                </div>
                <input type="text" x-model="searchQuery" @input.debounce.300ms="searchMedicines()" class="w-full pl-10 pr-4 py-3 text-lg border-2 border-gray-200 rounded-xl focus:border-emerald-500 focus:ring-0 outline-none transition-colors" placeholder="Ketik nama obat, kode, atau scan barcode..." autofocus>
            </div>
        </div>

        <!-- Daftar Obat Hasil Pencarian -->
        <div class="flex-1 overflow-y-auto p-4 bg-gray-50 h-[calc(100vh-140px)]">
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                <template x-for="med in searchResults" :key="med.id">
                    <div @click="addToCart(med)" class="bg-white p-4 rounded-xl border border-gray-200 shadow-sm cursor-pointer hover:border-emerald-500 hover:shadow-md transition-all group flex flex-col justify-between min-h-[140px]">
                        <div>
                            <div class="text-xs text-gray-400 mb-1" x-text="med.code"></div>
                            <h3 class="font-bold text-gray-800 leading-tight mb-2 group-hover:text-emerald-600 line-clamp-2" x-text="med.name"></h3>
                        </div>
                        <div class="flex justify-between items-end mt-2">
                            <span class="text-emerald-600 font-bold" x-text="formatRupiah(med.selling_price)"></span>
                            <span class="text-xs px-2 py-1 bg-gray-100 rounded-full font-medium" :class="med.current_stock > 0 ? 'text-gray-600' : 'text-red-500 bg-red-50'" x-text="'Stok: ' + med.current_stock"></span>
                        </div>
                    </div>
                </template>
                
                <div x-show="searchResults.length === 0 && searchQuery !== ''" class="col-span-full text-center py-10 text-gray-500">
                    <svg class="w-12 h-12 mx-auto text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    <p>Obat tidak ditemukan.</p>
                </div>

                <div x-show="searchResults.length === 0 && searchQuery === ''" class="col-span-full text-center py-20 text-gray-400">
                    <svg class="w-16 h-16 mx-auto text-gray-200 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm14 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"></path></svg>
                    <p class="text-lg font-medium">Mulai ketik di kolom pencarian untuk menambahkan obat ke keranjang</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Bagian Kanan: Keranjang & Pembayaran -->
    <div class="w-1/3 flex flex-col bg-gray-50 h-full relative">
        <!-- List Keranjang -->
        <div class="flex-1 overflow-y-auto p-4 pb-48">
            <template x-for="(item, index) in cart" :key="item.id">
                <div class="bg-white p-3 rounded-xl border border-gray-200 shadow-sm mb-3 relative group">
                    <div class="flex justify-between items-start mb-2 pr-6">
                        <div>
                            <h4 class="font-bold text-gray-800 leading-tight" x-text="item.name"></h4>
                            <p class="text-xs text-emerald-600 font-medium mt-1" x-text="formatRupiah(item.price) + ' / ' + item.unit"></p>
                        </div>
                    </div>
                    
                    <button @click="removeFromCart(index)" class="absolute top-3 right-3 text-gray-300 hover:text-red-500 transition-colors p-1 rounded-full hover:bg-red-50">
                        <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="M6 18L18 6M6 6l12 12"></path></svg>
                    </button>

                    <div class="flex justify-between items-center mt-3">
                        <div class="flex items-center border border-gray-300 rounded-lg overflow-hidden w-28 shadow-inner">
                            <button @click="decreaseQty(index)" class="w-8 h-8 bg-gray-100 flex items-center justify-center hover:bg-gray-200 font-bold text-gray-600 transition-colors">-</button>
                            <input type="number" x-model.number="item.qty" @input="updateSubtotal(index)" class="w-12 h-8 text-center text-sm font-bold focus:outline-none border-x border-gray-300" min="1">
                            <button @click="increaseQty(index)" class="w-8 h-8 bg-gray-100 flex items-center justify-center hover:bg-gray-200 font-bold text-gray-600 transition-colors">+</button>
                        </div>
                        <span class="font-bold text-gray-800 text-lg" x-text="formatRupiah(item.subtotal)"></span>
                    </div>
                </div>
            </template>
            
            <div x-show="cart.length === 0" class="h-full flex flex-col items-center justify-center text-gray-400 mt-20">
                <svg class="w-20 h-20 mb-4 opacity-30" 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="font-medium text-lg">Keranjang Kosong</p>
            </div>
        </div>

        <!-- Total & Bayar (Fixed Bottom) -->
        <div class="bg-white border-t border-gray-200 p-5 shadow-[0_-10px_15px_-3px_rgba(0,0,0,0.05)] absolute bottom-0 w-full z-10 h-44 flex flex-col justify-between">
            <div class="flex justify-between items-center mb-2">
                <span class="text-gray-500 font-bold text-lg uppercase tracking-wider">Total Tagihan</span>
                <span class="text-4xl font-black text-emerald-600" x-text="formatRupiah(totalAmount)"></span>
            </div>
            
            <div class="grid grid-cols-3 gap-3 h-14 mt-auto">
                <button @click="holdTransaction()" class="col-span-1 rounded-xl font-bold text-orange-600 bg-orange-50 border border-orange-200 hover:bg-orange-100 transition-colors flex flex-col items-center justify-center gap-1 leading-tight" :disabled="cart.length === 0" :class="{'opacity-50 cursor-not-allowed': cart.length === 0}">
                    <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="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
                    <span class="text-xs">Hold Transaksi</span>
                </button>
                <button @click="openPayment()" class="col-span-2 rounded-xl font-bold text-white bg-emerald-600 hover:bg-emerald-700 shadow-md hover:shadow-lg transition-all flex items-center justify-center gap-2 text-lg transform hover:-translate-y-0.5 active:translate-y-0" :disabled="cart.length === 0" :class="{'opacity-50 cursor-not-allowed transform-none': cart.length === 0}">
                    <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="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>
                    BAYAR SEKARANG
                </button>
            </div>
        </div>
    </div>

    <!-- Modal Pembayaran -->
    <div x-show="isPaymentOpen" class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-60 backdrop-blur-sm" x-cloak>
        <div @click.away="closePayment()" class="bg-white rounded-3xl p-8 w-[500px] shadow-2xl transform transition-all" x-show="isPaymentOpen" x-transition:enter="ease-out duration-300" x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100" x-transition:leave="ease-in duration-200" x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100" x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
            <h3 class="text-2xl font-bold text-gray-800 mb-6 border-b pb-4">Proses Pembayaran</h3>
            
            <div class="mb-6 bg-emerald-50 p-5 rounded-2xl border border-emerald-100 flex flex-col items-center justify-center">
                <span class="text-emerald-800 font-semibold text-sm mb-1 uppercase tracking-wider">Total Tagihan</span>
                <span class="text-4xl font-black text-emerald-600" x-text="formatRupiah(totalAmount)"></span>
            </div>

            <div class="mb-6">
                <label class="block text-sm font-semibold text-gray-700 mb-2">Jumlah Uang Diterima (Rp)</label>
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                        <span class="text-gray-500 font-bold text-xl">Rp</span>
                    </div>
                    <input type="number" x-model.number="amountPaid" @input="calculateChange()" class="w-full pl-14 pr-4 py-4 text-3xl font-bold text-right text-gray-800 border-2 border-gray-300 rounded-xl focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/20 outline-none transition-all shadow-inner" placeholder="0" autofocus id="amountPaidInput">
                </div>
                
                <!-- Quick Cash Buttons -->
                <div class="grid grid-cols-4 gap-2 mt-3">
                    <button type="button" @click="setExactAmount()" class="py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm font-semibold text-gray-700 transition-colors">Uang Pas</button>
                    <button type="button" @click="addAmount(50000)" class="py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm font-semibold text-gray-700 transition-colors">50k</button>
                    <button type="button" @click="addAmount(100000)" class="py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm font-semibold text-gray-700 transition-colors">100k</button>
                    <button type="button" @click="amountPaid = ''; calculateChange()" class="py-2 bg-red-50 hover:bg-red-100 rounded-lg text-sm font-semibold text-red-600 transition-colors">Clear</button>
                </div>
            </div>

            <div class="mb-8 p-5 rounded-2xl border transition-colors" :class="changeAmount >= 0 ? 'bg-blue-50 border-blue-200' : 'bg-red-50 border-red-200'">
                <div class="flex justify-between items-center">
                    <span class="font-bold text-lg" :class="changeAmount >= 0 ? 'text-blue-800' : 'text-red-800'">Kembalian</span>
                    <span class="text-3xl font-black" :class="changeAmount >= 0 ? 'text-blue-600' : 'text-red-600'" x-text="formatRupiah(changeAmount)"></span>
                </div>
            </div>

            <div class="flex justify-end gap-3 mt-4">
                <button type="button" @click="closePayment()" class="px-6 py-4 text-sm font-bold text-gray-600 bg-gray-100 rounded-xl hover:bg-gray-200 transition-colors w-1/3">Batal</button>
                <button type="button" @click="submitTransaction()" class="px-6 py-4 text-lg font-bold text-white bg-emerald-600 rounded-xl shadow-lg hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 w-2/3 transition-all" :disabled="changeAmount < 0 || isSubmitting">
                    <span x-show="!isSubmitting" class="flex items-center gap-2">
                        <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="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>
                        Cetak Struk
                    </span>
                    <span x-show="isSubmitting" class="flex items-center gap-2">
                        <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                        Memproses...
                    </span>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    function posSystem() {
        return {
            searchQuery: '',
            searchResults: [],
            cart: [],
            totalAmount: 0,
            
            isPaymentOpen: false,
            amountPaid: '',
            changeAmount: 0,
            isSubmitting: false,
            
            searchMedicines() {
                if (this.searchQuery.trim() === '') {
                    this.searchResults = [];
                    return;
                }
                
                fetch(`{{ route('pos.search') }}?q=${encodeURIComponent(this.searchQuery)}`)
                    .then(res => res.json())
                    .then(data => {
                        this.searchResults = data;
                    });
            },
            
            addToCart(medicine) {
                if (medicine.current_stock <= 0) {
                    alert('Stok obat habis!');
                    return;
                }
            
                const existingIndex = this.cart.findIndex(item => item.medicine_id === medicine.id);
                if (existingIndex >= 0) {
                    if (this.cart[existingIndex].qty >= medicine.current_stock) {
                        alert('Stok tidak mencukupi!');
                        return;
                    }
                    this.increaseQty(existingIndex);
                } else {
                    this.cart.push({
                        id: Date.now(),
                        medicine_id: medicine.id,
                        name: medicine.name,
                        price: parseFloat(medicine.selling_price),
                        unit: medicine.unit ? medicine.unit.name : 'pcs',
                        qty: 1,
                        stock: medicine.current_stock,
                        subtotal: parseFloat(medicine.selling_price)
                    });
                }
                this.calculateTotal();
                this.searchQuery = '';
                this.searchResults = [];
                // document.querySelector('input[type="text"]').focus(); // keep focus on search
            },
            
            increaseQty(index) {
                if (this.cart[index].qty >= this.cart[index].stock) {
                    alert('Stok maksimal tercapai!');
                    return;
                }
                this.cart[index].qty++;
                this.updateSubtotal(index);
            },
            
            decreaseQty(index) {
                if (this.cart[index].qty > 1) {
                    this.cart[index].qty--;
                    this.updateSubtotal(index);
                }
            },
            
            updateSubtotal(index) {
                if (this.cart[index].qty < 1) this.cart[index].qty = 1;
                if (this.cart[index].qty > this.cart[index].stock) {
                    this.cart[index].qty = this.cart[index].stock;
                    alert('Stok maksimal tercapai!');
                }
                this.cart[index].subtotal = this.cart[index].qty * this.cart[index].price;
                this.calculateTotal();
            },
            
            removeFromCart(index) {
                this.cart.splice(index, 1);
                this.calculateTotal();
            },
            
            calculateTotal() {
                this.totalAmount = this.cart.reduce((sum, item) => sum + item.subtotal, 0);
                this.calculateChange();
            },
            
            openPayment() {
                this.isPaymentOpen = true;
                this.amountPaid = '';
                this.changeAmount = -this.totalAmount;
                setTimeout(() => document.getElementById('amountPaidInput').focus(), 100);
            },
            
            closePayment() {
                this.isPaymentOpen = false;
            },
            
            setExactAmount() {
                this.amountPaid = this.totalAmount;
                this.calculateChange();
            },
            
            addAmount(amount) {
                const current = parseFloat(this.amountPaid) || 0;
                this.amountPaid = current + amount;
                this.calculateChange();
            },
            
            calculateChange() {
                const paid = parseFloat(this.amountPaid) || 0;
                this.changeAmount = paid - this.totalAmount;
            },
            
            submitTransaction() {
                if (this.changeAmount < 0) return;
                
                this.isSubmitting = true;
                
                const payload = {
                    items: this.cart,
                    amount_paid: this.amountPaid,
                    change_amount: this.changeAmount,
                    payment_method: 'cash',
                    _token: '{{ csrf_token() }}'
                };
                
                fetch('{{ route("pos.transaction") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(payload)
                })
                .then(res => res.json())
                .then(data => {
                    this.isSubmitting = false;
                    if (data.success) {
                        this.closePayment();
                        this.cart = [];
                        this.calculateTotal();
                        
                        // Auto Print Struk
                        const printUrl = `{{ url('pos/print') }}/${data.sale_id}`;
                        const printWindow = window.open(printUrl, '_blank', 'width=400,height=600');
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    this.isSubmitting = false;
                    alert('Terjadi kesalahan jaringan: ' + error);
                });
            },
            
            holdTransaction() {
                alert('Transaksi ditahan (Hold).');
                // Could store in localStorage here
                this.cart = [];
                this.calculateTotal();
            },
            
            formatRupiah(number) {
                return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(number);
            }
        }
    }
</script>
@endsection
