@extends('layouts.kurir_sidebar')

@section('title', 'Transaksi Penjualan')

@push('styles')
<style>
    .soft-shadow {
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.04);
    }
    input, select, button {
        transition: all 0.2s ease-in-out;
    }
    input:focus, select:focus {
        border-color: #3b82f6;
        outline: none;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
    .qty-input::-webkit-inner-spin-button,
    .qty-input::-webkit-outer-spin-button {
        -webkit-appearance: none;
        margin: 0;
    }
    .qty-input { -moz-appearance: textfield; }
</style>
@endpush

@section('content')
<div class="max-w-7xl mx-auto pb-10 px-4 sm:px-6 lg:px-8">


    {{-- Stok Cards --}}
    @php
        $gas3kg = $produk->first(fn($item) =>
            stripos($item->nama_produk, '3') !== false && stripos($item->nama_produk, 'kg') !== false
        );
        $gas12kg = $produk->first(fn($item) =>
            stripos($item->nama_produk, '12') !== false && stripos($item->nama_produk, 'kg') !== false
        );
    @endphp

    <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-8">
        {{-- Card Gas 3 KG --}}
        <div class="bg-white rounded-2xl p-6 border border-green-100 flex items-center justify-between cursor-pointer hover:border-green-300 hover:shadow-md transition-all soft-shadow"
             onclick="selectProduct('{{ $gas3kg->id_produk ?? '' }}')">
            <div>
                <p class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Gas 3 KG</p>
                <div class="flex items-baseline gap-2">
                    <span class="text-4xl font-black text-green-500">{{ $gas3kg->stok_isi ?? 0 }}</span>
                    <span class="text-sm font-medium text-slate-500">Tabung</span>
                </div>
                <p class="text-xs text-slate-400 mt-1">Klik untuk pilih produk</p>
            </div>
            <div class="w-20 h-20 bg-green-50 rounded-full flex items-center justify-center flex-shrink-0 overflow-hidden">
                <img src="{{ asset('images/gas_3kg_elpiji.jpg') }}" alt="Gas 3kg" class="w-16 h-16 object-contain drop-shadow-md">
            </div>
        </div>

        {{-- Card Gas 12 KG --}}
        <div class="bg-white rounded-2xl p-6 border border-pink-100 flex items-center justify-between cursor-pointer hover:border-pink-300 hover:shadow-md transition-all soft-shadow"
             onclick="selectProduct('{{ $gas12kg->id_produk ?? '' }}')">
            <div>
                <p class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Gas 12 KG</p>
                <div class="flex items-baseline gap-2">
                    <span class="text-4xl font-black text-pink-500">{{ $gas12kg->stok_isi ?? 0 }}</span>
                    <span class="text-sm font-medium text-slate-500">Tabung</span>
                </div>
                <p class="text-xs text-slate-400 mt-1">Klik untuk pilih produk</p>
            </div>
            <div class="w-20 h-20 bg-pink-50 rounded-full flex items-center justify-center flex-shrink-0 overflow-hidden">
                <img src="{{ asset('images/gas_12kg_bright.jpg') }}" alt="Gas 12kg" class="w-16 h-16 object-contain drop-shadow-md">
            </div>
        </div>
    </div>

    {{-- Form Utama: 2 kolom (kiri: pelanggan + barang) | (kanan: ringkasan) --}}
    <form action="{{ route('kurir.penjualan.store') }}" method="POST" id="transactionForm" class="no-loader">
        @csrf
        <input type="hidden" name="id_produk" id="hidden_id_produk" required>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

            {{-- ===== KOLOM KIRI (2/3) ===== --}}
            <div class="lg:col-span-2 space-y-5">

                {{-- Cari Pelanggan --}}
                <div class="bg-white p-6 rounded-2xl border border-slate-200 soft-shadow">
                    <div class="flex items-center gap-2 mb-4">
                        <i data-lucide="users" class="w-5 h-5 text-blue-500"></i>
                        <h3 class="font-bold text-slate-700 text-sm">Cari Pelanggan</h3>
                    </div>
                    <div class="relative" id="customerSearchContainer">
                        <!-- Search Input -->
                        <div class="relative">
                            <input type="text" id="customer_search_input"
                                   class="w-full pl-4 pr-10 py-3 bg-white border border-slate-200 rounded-xl text-slate-700 text-sm focus:ring-2 focus:ring-blue-500 outline-none transition-all placeholder:text-slate-400" 
                                   placeholder="Ketik nama / kategori produk..." autocomplete="off" required>
                            <div class="absolute inset-y-0 right-0 flex items-center px-4 pointer-events-none text-slate-400 cursor-pointer" onclick="document.getElementById('customer_search_input').focus()">
                                <i data-lucide="search" class="w-4 h-4"></i>
                            </div>
                        </div>

                        <!-- Dropdown Options -->
                        <div id="customer_dropdown" class="absolute z-20 w-full mt-2 bg-white border border-slate-100 rounded-xl shadow-[0_10px_40px_-10px_rgba(0,0,0,0.1)] max-h-64 overflow-y-auto hidden">
                            @foreach($pelanggan as $p)
                                <div class="customer-option p-3 hover:bg-slate-50 cursor-pointer border-b border-slate-50 transition-colors"
                                     data-id="{{ $p->customers_id }}"
                                     data-product="{{ $p->product_name ?? '' }}"
                                     data-search="{{ strtolower($p->name . ' ' . ($p->product_name ?? '') . ' ' . ($p->phone ?? '')) }}">
                                    <div class="flex justify-between items-start">
                                        <div>
                                            <div class="font-bold text-slate-700 text-sm customer-name">{{ $p->name }}</div>
                                            <div class="text-xs text-slate-400 mt-1 flex items-center gap-2">
                                                @if($p->phone)
                                                    <span class="flex items-center gap-1"><i data-lucide="phone" class="w-3 h-3"></i> {{ $p->phone }}</span>
                                                @endif
                                            </div>
                                        </div>
                                        <div class="bg-blue-50 text-blue-600 px-2.5 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase border border-blue-100">
                                            {{ $p->product_name ?? 'Umum' }}
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                            <div id="customer_no_result" class="p-4 text-center text-sm text-slate-500 hidden">
                                Pelanggan tidak ditemukan
                            </div>
                        </div>

                        <!-- Hidden Select -->
                        <select id="customers_id" name="customers_id" class="hidden">
                            <option value="">-- Pilih Pelanggan --</option>
                            @foreach($pelanggan as $p)
                                <option value="{{ $p->customers_id }}"
                                        data-nama="{{ $p->name }}"
                                        data-idpel="{{ $p->customers_id }}"
                                        data-phone="{{ $p->phone ?? '-' }}"
                                        data-address="{{ $p->address ?? '-' }}"
                                        data-kategori="{{ $p->price_category ?? 0 }}"
                                        data-product="{{ $p->product_name ?? '' }}">
                                    {{ $p->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    @error('customers_id')
                        <p class="mt-1.5 text-xs text-red-500">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Informasi Pelanggan --}}
                <div class="bg-white p-6 rounded-2xl border border-slate-200 soft-shadow">
                    <h3 class="font-bold text-slate-400 text-xs tracking-wider uppercase mb-5">Informasi Pelanggan</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs text-slate-500 mb-1.5 font-medium">ID Pelanggan</label>
                            <input type="text" id="info_id"
                                   class="w-full px-4 py-2.5 bg-slate-50 border border-slate-100 rounded-lg text-slate-600 text-sm cursor-not-allowed" readonly>
                        </div>
                        <div>
                            <label class="block text-xs text-slate-500 mb-1.5 font-medium">Nama Lengkap</label>
                            <input type="text" id="info_nama"
                                   class="w-full px-4 py-2.5 bg-slate-50 border border-slate-100 rounded-lg text-slate-600 text-sm cursor-not-allowed" readonly>
                        </div>
                        <div>
                            <label class="block text-xs text-slate-500 mb-1.5 font-medium">Nomor HP</label>
                            <input type="text" id="info_phone"
                                   class="w-full px-4 py-2.5 bg-slate-50 border border-slate-100 rounded-lg text-slate-600 text-sm cursor-not-allowed" readonly>
                        </div>
                        <div>
                            <label class="block text-xs text-slate-500 mb-1.5 font-medium">Alamat</label>
                            <input type="text" id="info_address"
                                   class="w-full px-4 py-2.5 bg-slate-50 border border-slate-100 rounded-lg text-slate-600 text-sm cursor-not-allowed" readonly>
                        </div>
                    </div>
                </div>

                {{-- Detail Barang --}}
                <div class="bg-white p-6 rounded-2xl border border-slate-200 soft-shadow">
                    <h3 class="font-bold text-slate-400 text-xs tracking-wider uppercase mb-5 pb-3 border-b border-slate-100">
                        Detail Barang
                    </h3>

                    {{-- Sembunyikan semua produk sebagai JSON untuk dipakai JS --}}
                    <script id="produk-data" type="application/json">
                        [
                            @foreach($produk as $item)
                            {
                                "id_produk": "{{ $item->id_produk }}",
                                "nama_produk": "{{ addslashes($item->nama_produk) }}",
                                "harga": {{ $item->price ?? 0 }},
                                "stok_isi": {{ $item->stok_isi ?? 0 }}
                            }{{ !$loop->last ? ',' : '' }}
                            @endforeach
                        ]
                    </script>

                    {{-- Card info produk (muncul setelah pelanggan dipilih) --}}
                    <div id="produk-empty-state" class="flex flex-col items-center justify-center py-8 text-slate-400">
                        <i data-lucide="package" class="w-10 h-10 mb-2 opacity-30"></i>
                        <p class="text-sm">Pilih pelanggan terlebih dahulu</p>
                        <p class="text-xs mt-1 opacity-70">Kategori barang akan terisi otomatis</p>
                    </div>

                    <div id="produk-info" class="hidden">
                        <div class="flex items-center gap-4 p-4 bg-slate-50 rounded-xl border border-slate-100 mb-5">
                            <div class="w-12 h-12 rounded-full bg-blue-50 border border-blue-100 flex items-center justify-center flex-shrink-0">
                                <i data-lucide="package-2" class="w-6 h-6 text-blue-500"></i>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-xs text-slate-400 font-medium uppercase tracking-wider mb-0.5">Kategori Barang</p>
                                <p id="produk-nama-display" class="text-base font-bold text-slate-700 truncate">—</p>
                            </div>
                            <div class="text-right flex-shrink-0">
                                <p class="text-xs text-slate-400 font-medium mb-0.5">Harga Satuan</p>
                                <p id="produk-harga-display" class="text-base font-bold text-blue-600">Rp 0</p>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            {{-- Stok info --}}
                            <div>
                                <label class="block text-xs text-slate-500 mb-1.5 font-medium">Stok Tersedia</label>
                                <div class="flex items-center gap-2 px-4 py-2.5 bg-slate-50 border border-slate-100 rounded-lg">
                                    <i data-lucide="boxes" class="w-4 h-4 text-green-500 flex-shrink-0"></i>
                                    <span id="produk-stok-display" class="text-sm font-bold text-slate-700">0</span>
                                    <span class="text-xs text-slate-400">tabung tersedia</span>
                                </div>
                            </div>

                            {{-- Jumlah Beli --}}
                            <div>
                                <label class="block text-xs text-slate-500 mb-1.5 font-medium">Jumlah Beli</label>
                                <div class="flex items-center border border-slate-200 rounded-lg overflow-hidden">
                                    <button type="button" onclick="decrement('qty_beli')"
                                            class="w-10 h-10 bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-slate-600 font-bold text-lg flex-shrink-0">
                                        −
                                    </button>
                                    <input type="number" id="qty_beli" name="qty_beli" value="1" min="1"
                                           class="qty-input w-full h-10 text-center text-base font-bold text-slate-700 border-x border-slate-200 focus:ring-0 focus:outline-none bg-white" required>
                                    <button type="button" onclick="increment('qty_beli')"
                                            class="w-10 h-10 bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-slate-600 font-bold text-lg flex-shrink-0">
                                        +
                                    </button>
                                </div>
                                <p id="warningStok" class="text-xs text-red-500 mt-1.5 hidden"></p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>{{-- akhir kolom kiri --}}

            {{-- ===== KOLOM KANAN / SIDEBAR (1/3) ===== --}}
            <div class="space-y-5">

                {{-- Ringkasan Transaksi --}}
                <div class="bg-white p-6 rounded-2xl border border-slate-200 soft-shadow">
                    <h3 class="font-bold text-slate-400 text-xs tracking-wider uppercase mb-5">Ringkasan</h3>

                    <div class="space-y-3">
                        <div class="flex justify-between items-center text-sm">
                            <span class="text-slate-500">Produk</span>
                            <span id="summary-produk" class="font-semibold text-slate-700 text-right">—</span>
                        </div>
                        <div class="flex justify-between items-center text-sm">
                            <span class="text-slate-500">Harga Satuan</span>
                            <span id="summary-harga" class="font-semibold text-slate-700">Rp 0</span>
                        </div>
                        <div class="flex justify-between items-center text-sm">
                            <span class="text-slate-500">Jumlah Beli</span>
                            <span id="summary-qty" class="font-semibold text-slate-700">0 tabung</span>
                        </div>
                    </div>

                    <div class="border-t border-slate-100 mt-4 pt-4 flex justify-between items-center">
                        <span class="text-slate-600 font-semibold text-sm">Total Tagihan</span>
                        <span id="summary-total" class="text-2xl font-black text-blue-600">Rp 0</span>
                    </div>
                </div>

                {{-- Pengirim, Tanggal & Pembayaran --}}
                <div class="bg-white p-6 rounded-2xl border border-slate-200 soft-shadow">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-xs text-slate-500 mb-1.5 font-medium">Nama Pengirim</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i data-lucide="user" class="w-4 h-4 text-slate-400"></i>
                                </div>
                                <input type="text" name="nama_pengirim" value="{{ auth()->user()->name ?? 'Kurir' }}"
                                       class="w-full pl-10 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-slate-700 text-sm focus:ring-2 focus:ring-blue-500 outline-none" readonly>
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs text-slate-500 mb-1.5 font-medium">Tanggal Transaksi</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i data-lucide="calendar" class="w-4 h-4 text-slate-400"></i>
                                </div>
                                <input type="date" name="tanggal" value="{{ date('Y-m-d') }}"
                                       class="w-full pl-10 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-slate-700 text-sm focus:ring-2 focus:ring-blue-500 outline-none" required>
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs text-slate-500 mb-1.5 font-medium">Metode Pembayaran</label>
                            <div class="relative">
                                <select name="metode_bayar" id="metode_bayar"
                                        onchange="togglePaymentInfo(this.value)"
                                        class="w-full pl-4 pr-10 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-slate-700 text-sm appearance-none cursor-pointer focus:ring-2 focus:ring-blue-500 outline-none" required>
                                    <option value="Tunai">Tunai</option>
                                    <option value="Transfer">Transfer Bank</option>
                                    <option value="Qris">QRIS</option>
                                </select>
                                <div class="absolute inset-y-0 right-0 flex items-center px-4 pointer-events-none text-slate-400">
                                    <i data-lucide="chevron-down" class="w-4 h-4"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Card Info Rekening Bank (muncul jika Transfer) --}}
                <div id="card-transfer" class="hidden bg-gradient-to-br from-blue-50 to-indigo-50 p-5 rounded-2xl border border-blue-200 soft-shadow">
                    <div class="flex items-center gap-2 mb-4">
                        <div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
                            <i data-lucide="landmark" class="w-4 h-4 text-white"></i>
                        </div>
                        <h3 class="font-bold text-blue-800 text-sm">Info Rekening Bank</h3>
                    </div>

                    {{-- Bank 1 --}}
                    <div class="bg-white rounded-xl border border-blue-100 p-4 mb-3 shadow-sm">
                        <div class="flex items-center justify-between mb-1">
                            <span class="text-[10px] font-bold uppercase tracking-wider text-blue-400">BRI</span>
                            <span class="text-[10px] text-slate-400">Margiyanto</span>
                        </div>
                        <div class="flex items-center justify-between mt-1">
                            <span id="rek-bri" class="text-lg font-black text-slate-800 tracking-widest">0820-0102-2799-500</span>
                            <button type="button" onclick="copyRekening('rek-bri', this)"
                                    class="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold rounded-lg transition-all active:scale-95">
                                <i data-lucide="copy" class="w-3 h-3"></i>
                                <span class="btn-copy-text">Salin</span>
                            </button>
                        </div>
                    </div>

                    {{-- Bank 2 --}}
                    <div class="bg-white rounded-xl border border-blue-100 p-4 shadow-sm">
                        <div class="flex items-center justify-between mb-1">
                            <span class="text-[10px] font-bold uppercase tracking-wider text-blue-400">BCA</span>
                            <span class="text-[10px] text-slate-400">Margiyanto</span>
                        </div>
                        <div class="flex items-center justify-between mt-1">
                            <span id="rek-bca" class="text-lg font-black text-slate-800 tracking-widest">0987-6543-210</span>
                            <button type="button" onclick="copyRekening('rek-bca', this)"
                                    class="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold rounded-lg transition-all active:scale-95">
                                <i data-lucide="copy" class="w-3 h-3"></i>
                                <span class="btn-copy-text">Salin</span>
                            </button>
                        </div>
                    </div>

                    <p class="text-[10px] text-blue-500 mt-3 flex items-center gap-1">
                        <i data-lucide="info" class="w-3 h-3"></i>
                        Harap konfirmasi pembayaran setelah transfer
                    </p>
                </div>

                {{-- Card QRIS (muncul jika QRIS) --}}
                <div id="card-qris" class="hidden bg-gradient-to-br from-purple-50 to-pink-50 p-5 rounded-2xl border border-purple-200 soft-shadow">
                    <div class="flex items-center gap-2 mb-4">
                        <div class="w-8 h-8 bg-purple-600 rounded-lg flex items-center justify-center">
                            <i data-lucide="qr-code" class="w-4 h-4 text-white"></i>
                        </div>
                        <h3 class="font-bold text-purple-800 text-sm">Scan QRIS untuk Bayar</h3>
                    </div>
                    <div class="flex flex-col items-center">
                        <div class="bg-white p-3 rounded-2xl border-2 border-purple-200 shadow-md inline-block w-full max-w-[240px] flex justify-center">
                            <img src="{{ asset('images/qris_baru.jpeg') }}" alt="Barcode QRIS" class="w-full h-auto object-contain rounded-xl">
                        </div>
                        <a href="{{ asset('images/qris_baru.jpeg') }}" download="QRIS_Pembayaran.jpeg" class="mt-3 flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white text-sm font-semibold rounded-xl transition-all shadow-sm active:scale-95">
                            <i data-lucide="download" class="w-4 h-4"></i>
                            Download QRIS
                        </a>
                        <p class="text-xs text-purple-600 font-semibold mt-3">Scan dengan aplikasi e-wallet / mobile banking</p>
                        <div class="flex items-center gap-2 mt-2 flex-wrap justify-center">
                            <span class="text-[10px] bg-white border border-purple-100 text-purple-500 px-2 py-1 rounded-full">GoPay</span>
                            <span class="text-[10px] bg-white border border-purple-100 text-purple-500 px-2 py-1 rounded-full">OVO</span>
                            <span class="text-[10px] bg-white border border-purple-100 text-purple-500 px-2 py-1 rounded-full">Dana</span>
                            <span class="text-[10px] bg-white border border-purple-100 text-purple-500 px-2 py-1 rounded-full">ShopeePay</span>
                            <span class="text-[10px] bg-white border border-purple-100 text-purple-500 px-2 py-1 rounded-full">M-Banking</span>
                        </div>
                    </div>
                </div>

                {{-- Tombol Aksi --}}
                <div class="bg-white p-5 rounded-2xl border border-slate-200 soft-shadow space-y-3">
                    <button type="submit" id="btnSubmit"
                            class="w-full bg-blue-600 text-white py-3.5 rounded-xl font-bold text-sm shadow-[0_8px_20px_-6px_rgba(37,99,235,0.5)] hover:bg-blue-700 hover:-translate-y-0.5 transition-all flex justify-center items-center gap-2">
                        <i data-lucide="check-square" class="w-5 h-5"></i>
                        <span>Simpan Transaksi</span>
                    </button>

                    <button type="reset"
                            class="w-full bg-slate-100 text-slate-600 py-3 rounded-xl font-semibold text-sm hover:bg-slate-200 transition-colors flex justify-center items-center gap-2">
                        <i data-lucide="rotate-ccw" class="w-4 h-4"></i>
                        <span>Reset Form</span>
                    </button>
                </div>

            </div>{{-- akhir kolom kanan --}}

        </div>{{-- akhir grid --}}
    </form>

</div>
@endsection

@push('scripts')
<script>
    // ── Toggle card Transfer / QRIS ───────────────────────────────────────
    function togglePaymentInfo(value) {
        const cardTransfer = document.getElementById('card-transfer');
        const cardQris     = document.getElementById('card-qris');
        cardTransfer.classList.toggle('hidden', value !== 'Transfer');
        cardQris.classList.toggle('hidden', value !== 'Qris');
        if (typeof lucide !== 'undefined') lucide.createIcons();
    }

    // ── Salin nomor rekening ──────────────────────────────────────────────
    function copyRekening(elementId, btn) {
        const el   = document.getElementById(elementId);
        const text = el ? el.textContent.trim() : '';
        if (!text) return;

        // Fungsi bantu: update tampilan tombol setelah berhasil salin
        function onCopied() {
            const label = btn.querySelector('.btn-copy-text');
            if (label) label.textContent = '✓ Disalin!';
            btn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
            btn.classList.add('bg-green-500');
            setTimeout(() => {
                if (label) label.textContent = 'Salin';
                btn.classList.remove('bg-green-500');
                btn.classList.add('bg-blue-600', 'hover:bg-blue-700');
            }, 2000);
        }

        // Utamakan execCommand (bekerja di HTTP/localhost)
        try {
            const ta = document.createElement('textarea');
            ta.value = text;
            ta.setAttribute('readonly', '');
            ta.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;';
            document.body.appendChild(ta);
            ta.focus();
            ta.select();
            const success = document.execCommand('copy');
            document.body.removeChild(ta);
            if (success) { onCopied(); return; }
        } catch (e) {}

        // Fallback ke Clipboard API (HTTPS)
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(onCopied).catch(() => {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal Menyalin',
                    text: 'Silakan salin manual: ' + text
                });
            });
        } else {
            Swal.fire({
                icon: 'info',
                title: 'Nomor Rekening',
                text: text,
                confirmButtonText: 'OK'
            });
        }
    }

    // ── Data produk dari server (di-embed via JSON) ──────────────────────
    const PRODUK_DATA = JSON.parse(
        document.getElementById('produk-data')?.textContent || '[]'
    );

    // State produk aktif saat ini
    let activeProduk = null; // { id_produk, nama_produk, harga, stok_isi }

    // ── Cari produk berdasarkan nama (product_name pelanggan) ─────────────
    function findProdukByName(productName) {
        if (!productName) return null;
        const pn = productName.toLowerCase().trim();
        return PRODUK_DATA.find(p => {
            const nm = p.nama_produk.toLowerCase().trim();
            return nm === pn || nm.includes(pn) || pn.includes(nm);
        }) || null;
    }

    // ── Set produk aktif & update tampilan card ───────────────────────────
    function setProdukAktif(produk, hargaOverride) {
        const emptyState  = document.getElementById('produk-empty-state');
        const produkInfo  = document.getElementById('produk-info');

        if (!produk) {
            activeProduk = null;
            document.getElementById('hidden_id_produk').value = '';
            emptyState.classList.remove('hidden');
            produkInfo.classList.add('hidden');
            return;
        }

        // Harga: gunakan price_category pelanggan jika > 0, else harga produk
        const hargaFinal = (hargaOverride && hargaOverride > 0) ? hargaOverride : produk.harga;

        activeProduk = { ...produk, hargaFinal };
        document.getElementById('hidden_id_produk').value = produk.id_produk;

        // Update card display
        document.getElementById('produk-nama-display').textContent  = produk.nama_produk;
        document.getElementById('produk-harga-display').textContent = 'Rp ' + hargaFinal.toLocaleString('id-ID');
        document.getElementById('produk-stok-display').textContent  = produk.stok_isi;

        emptyState.classList.add('hidden');
        produkInfo.classList.remove('hidden');
        if (typeof lucide !== 'undefined') lucide.createIcons();
    }

    // ── Hitung dan tampilkan ringkasan ────────────────────────────────────
    function calculateTotal() {
        const qtyBeli = parseInt(document.getElementById('qty_beli').value) || 0;
        document.getElementById('summary-qty').textContent = qtyBeli + ' tabung';

        if (activeProduk) {
            const harga = activeProduk.hargaFinal || 0;
            const stok  = activeProduk.stok_isi  || 0;

            document.getElementById('summary-produk').textContent = activeProduk.nama_produk;
            document.getElementById('summary-harga').textContent  = 'Rp ' + harga.toLocaleString('id-ID');

            const warningStok = document.getElementById('warningStok');
            if (qtyBeli > stok) {
                warningStok.classList.remove('hidden');
                warningStok.textContent = `⚠ Stok tersedia hanya ${stok} tabung`;
            } else {
                warningStok.classList.add('hidden');
            }

            const total = harga * qtyBeli;
            document.getElementById('summary-total').textContent = 'Rp ' + total.toLocaleString('id-ID');
        } else {
            document.getElementById('summary-produk').textContent = '—';
            document.getElementById('summary-harga').textContent  = 'Rp 0';
            document.getElementById('summary-total').textContent  = 'Rp 0';
            document.getElementById('warningStok').classList.add('hidden');
        }
    }

    // ── Klik card stok (opsional, masih bisa dipakai) ─────────────────────
    function selectProduct(id) {
        const produk = PRODUK_DATA.find(p => p.id_produk === id);
        if (produk) {
            setProdukAktif(produk, 0);
            calculateTotal();
        }
    }

    function increment(id) {
        const input = document.getElementById(id);
        if (input && parseInt(input.value) < 999) {
            input.value = parseInt(input.value) + 1;
            calculateTotal();
        }
    }

    function decrement(id) {
        const input = document.getElementById(id);
        if (!input) return;
        const min = parseInt(input.getAttribute('min')) || 1;
        if (parseInt(input.value) > min) {
            input.value = parseInt(input.value) - 1;
            calculateTotal();
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        if (typeof lucide !== 'undefined') lucide.createIcons();

        // Listener: hidden select pelanggan berubah
        const customerSelect = document.getElementById('customers_id');
        if (customerSelect) {
            customerSelect.addEventListener('change', function () {
                const selIdx    = customerSelect.selectedIndex;
                const selOption = customerSelect.options[selIdx];

                if (selIdx > 0) {
                    // Isi info pelanggan
                    document.getElementById('info_id').value      = selOption.getAttribute('data-idpel')  || '-';
                    document.getElementById('info_nama').value    = selOption.getAttribute('data-nama')   || '-';
                    document.getElementById('info_phone').value   = selOption.getAttribute('data-phone')  || '-';
                    document.getElementById('info_address').value = selOption.getAttribute('data-address')|| '-';

                    // Cari & set produk sesuai product_name pelanggan
                    const productName   = selOption.getAttribute('data-product')  || '';
                    const kategoriHarga = parseFloat(selOption.getAttribute('data-kategori')) || 0;
                    const produk        = findProdukByName(productName);
                    setProdukAktif(produk, kategoriHarga);
                } else {
                    // Reset info pelanggan
                    ['info_id','info_nama','info_phone','info_address'].forEach(id => {
                        document.getElementById(id).value = '';
                    });
                    setProdukAktif(null);
                }

                calculateTotal();
            });
        }

        // qty_beli berubah → hitung ulang
        const qtyInput = document.getElementById('qty_beli');
        if (qtyInput) qtyInput.addEventListener('input', calculateTotal);

        // -------------------------------------------------------------
        // Custom Searchable Dropdown Pelanggan
        // -------------------------------------------------------------
        const customerSearchContainer = document.getElementById('customerSearchContainer');
        if (customerSearchContainer) {
            const searchInput = document.getElementById('customer_search_input');
            const dropdown = document.getElementById('customer_dropdown');
            const options = document.querySelectorAll('.customer-option');
            const noResult = document.getElementById('customer_no_result');
            const hiddenSelect = document.getElementById('customers_id');

            searchInput.addEventListener('focus', () => {
                dropdown.classList.remove('hidden');
                filterDropdown();
            });

            document.addEventListener('click', (e) => {
                if (!customerSearchContainer.contains(e.target)) {
                    dropdown.classList.add('hidden');
                }
            });

            searchInput.addEventListener('input', () => {
                if (hiddenSelect.value !== "") {
                    hiddenSelect.value = "";
                    hiddenSelect.dispatchEvent(new Event('change'));
                }
                searchInput.classList.remove('text-blue-700', 'font-semibold');
                filterDropdown();
            });

            function filterDropdown() {
                const keyword = searchInput.value.toLowerCase();
                let hasVisible = false;

                options.forEach(opt => {
                    const searchStr = opt.getAttribute('data-search');
                    if (searchStr.includes(keyword)) {
                        opt.style.display = 'block';
                        hasVisible = true;
                    } else {
                        opt.style.display = 'none';
                    }
                });

                if (hasVisible) {
                    noResult.classList.add('hidden');
                } else {
                    noResult.classList.remove('hidden');
                }
            }

            options.forEach(opt => {
                opt.addEventListener('click', () => {
                    const id   = opt.getAttribute('data-id');
                    const name = opt.querySelector('.customer-name').textContent;

                    searchInput.value = name;
                    searchInput.classList.add('text-blue-700', 'font-semibold');
                    dropdown.classList.add('hidden');

                    // Set hidden select value → triggers 'change' → setProdukAktif + calculateTotal
                    hiddenSelect.value = id;
                    hiddenSelect.dispatchEvent(new Event('change'));
                });
            });
            
            document.getElementById('transactionForm').addEventListener('submit', function(e) {
                if(!hiddenSelect.value) {
                    e.preventDefault();
                    searchInput.focus();
                    Swal.fire({
                        icon: 'warning',
                        title: 'Pelanggan Belum Terpilih!',
                        text: 'Silakan pilih pelanggan dari daftar yang tersedia terlebih dahulu.',
                        confirmButtonColor: '#2563eb'
                    });
                    return;
                }
                
                // Show loader manually on success
                const loader = document.getElementById('pageLoader');
                if (loader) {
                    loader.classList.remove('opacity-0', 'pointer-events-none');
                    loader.classList.add('opacity-100');
                }
            });
            
            if (typeof lucide !== 'undefined') lucide.createIcons();
        }
    });
</script>
@endpush
