<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selesaikan Pesanan | Empal Gentong H. Apud</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Plus Jakarta Sans', sans-serif; }
        /* Animasi loading sederhana */
        .loader {
            border: 3px solid #f3f3f3; border-top: 3px solid #f59e0b;
            border-radius: 50%; width: 20px; height: 20px;
            animation: spin 1s linear infinite; display: none;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body class="bg-stone-100 text-gray-800 min-h-screen">

    <header class="bg-white shadow-sm border-b border-stone-200 py-4">
        <div class="max-w-6xl mx-auto px-4 flex justify-between items-center">
            <h1 class="text-2xl font-bold text-amber-700">Haji Apud.</h1>
            <a href="{{ route('cart.index') }}" class="text-stone-500 hover:text-amber-600 text-sm font-medium">
                <i class="fas fa-arrow-left mr-1"></i> Kembali ke Keranjang
            </a>
        </div>
    </header>

    <main class="max-w-6xl mx-auto px-4 py-8">
        
        @if ($errors->any())
            <div class="mb-8 bg-red-50 border-l-4 border-red-500 p-4 rounded-r-xl shadow-sm">
                <div class="flex items-center mb-2">
                    <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                    <h3 class="text-red-800 font-bold">Mohon periksa kembali data Anda:</h3>
                </div>
                <ul class="list-disc list-inside text-sm text-red-700 ml-6 space-y-1">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        @if (session('error'))
            <div class="mb-8 bg-red-50 border-l-4 border-red-500 p-4 rounded-r-xl shadow-sm flex items-center">
                <i class="fas fa-exclamation-circle text-red-500 mr-3 text-lg"></i>
                <span class="text-red-800 font-medium">{{ session('error') }}</span>
            </div>
        @endif

        <form id="checkoutForm" action="{{ route('checkout.process') }}" method="POST" enctype="multipart/form-data">
            @csrf
            
            <input type="hidden" name="destination_area_id" id="input_area_id" value="" required>
            <input type="hidden" name="shipping_cost" id="input_shipping_cost" value="0" required>
            <input type="hidden" name="courier_company" id="input_courier_company" value="">
            <input type="hidden" name="courier_type" id="input_courier_type" value="">

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
                
                <div class="lg:col-span-7 space-y-6">
                    <div class="bg-white p-6 md:p-8 rounded-3xl border border-stone-200 shadow-sm">
                        <h2 class="text-xl font-bold mb-6 border-b border-stone-100 pb-4">
                            <i class="fas fa-map-marker-alt text-amber-500 mr-2"></i> Informasi Pengiriman
                        </h2>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            <div>
                                <label class="block text-sm font-bold text-stone-700 mb-2">Nama Penerima</label>
                                <input type="text" name="customer_name" value="{{ old('customer_name') }}" required class="w-full bg-stone-50 border border-stone-300 rounded-xl px-4 py-3 focus:ring-2 focus:ring-amber-500 focus:outline-none transition-colors" placeholder="Cth: Budi Santoso">
                            </div>
                            <div>
                                <label class="block text-sm font-bold text-stone-700 mb-2">Nomor WhatsApp</label>
                                <input type="tel" name="customer_phone" value="{{ old('customer_phone') }}" required class="w-full bg-stone-50 border border-stone-300 rounded-xl px-4 py-3 focus:ring-2 focus:ring-amber-500 focus:outline-none transition-colors" placeholder="0812xxxxxx">
                            </div>
                        </div>

                        <div class="mb-6 relative">
                            <label class="block text-sm font-bold text-stone-700 mb-2">Kecamatan / Kota / Kabupaten Tujuan</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="fas fa-search text-stone-400"></i>
                                </div>
                                <input type="text" id="search_area" class="w-full bg-stone-50 border border-stone-300 rounded-xl pl-11 pr-10 py-3 focus:ring-2 focus:ring-amber-500 focus:outline-none transition-colors" placeholder="Ketik minimal 3 huruf kecamatan Anda...">
                                <div class="absolute inset-y-0 right-0 pr-4 flex items-center">
                                    <div class="loader" id="loader_area"></div>
                                </div>
                            </div>
                            <ul id="area_results" class="absolute z-10 w-full bg-white border border-stone-200 mt-1 rounded-xl shadow-xl max-h-60 overflow-y-auto hidden"></ul>
                        </div>

                        <div id="courier_section" class="mb-6 hidden bg-blue-50 border border-blue-200 p-4 rounded-xl">
                            <label class="block text-sm font-bold text-stone-800 mb-3">Pilih Layanan Kurir</label>
                            <div class="loader mb-2" id="loader_rates"></div>
                            <p id="rates_error" class="text-sm text-red-500 hidden"></p>
                            <div id="rates_list" class="space-y-3"></div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            <div class="md:col-span-2">
                                <label class="block text-sm font-bold text-stone-700 mb-2">Alamat Lengkap (Jalan, RT/RW, Patokan)</label>
                                <textarea name="customer_address" required rows="3" class="w-full bg-stone-50 border border-stone-300 rounded-xl px-4 py-3 focus:ring-2 focus:ring-amber-500 focus:outline-none transition-colors" placeholder="Cth: Jl. Merdeka No. 10, RT 01/RW 02, Pagar Hitam...">{{ old('customer_address') }}</textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-bold text-stone-700 mb-2">Kode Pos</label>
                                <input type="number" name="postal_code" id="input_postal" value="{{ old('postal_code') }}" class="w-full bg-stone-50 border border-stone-300 rounded-xl px-4 py-3 focus:ring-2 focus:ring-amber-500 focus:outline-none transition-colors" placeholder="Cth: 40111">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="lg:col-span-5 space-y-6">
                    
                    <div class="bg-white p-6 md:p-8 rounded-3xl border border-stone-200 shadow-sm">
                        <h2 class="text-xl font-bold mb-4 border-b border-stone-100 pb-4">Ringkasan Pesanan</h2>
                        
                        <div class="space-y-4 mb-6">
                            @if(count($cart) > 0)
                                @foreach($cart as $id => $item)
                                    <div class="flex justify-between items-center">
                                        <div>
                                            <p class="font-bold text-sm text-gray-800">{{ $item['name'] ?? 'Produk H. Apud' }}</p>
                                            <p class="text-xs text-stone-500">{{ $item['quantity'] }} x Rp {{ number_format($item['price'], 0, ',', '.') }}</p>
                                        </div>
                                        <p class="font-bold text-sm">Rp {{ number_format($item['price'] * $item['quantity'], 0, ',', '.') }}</p>
                                    </div>
                                @endforeach
                            @else
                                <p class="text-sm text-red-500">Keranjang Anda kosong.</p>
                            @endif
                        </div>

                        <div class="border-t border-dashed border-stone-300 pt-4 space-y-2 mb-4">
                            <div class="flex justify-between text-sm text-stone-600">
                                <span>Subtotal</span>
                                <span class="font-semibold" id="display_subtotal" data-value="{{ $subtotal }}">Rp {{ number_format($subtotal, 0, ',', '.') }}</span>
                            </div>
                            <div class="flex justify-between text-sm text-stone-600">
                                <span>Ongkos Kirim</span>
                                <span class="font-semibold text-stone-800" id="display_shipping">Rp 0</span>
                            </div>
                            <div class="flex justify-between text-sm text-stone-600">
                                <span>Kode Unik</span>
                                <span class="font-semibold text-amber-600" id="display_unique" data-value="{{ $uniqueCode }}">+ Rp {{ $uniqueCode }}</span>
                            </div>
                        </div>

                        <div class="border-t border-stone-200 pt-4 flex flex-col mb-4">
                            <div class="flex justify-between items-center mb-1">
                                <span class="font-bold text-lg">Total Transfer</span>
                                <span class="font-black text-2xl text-amber-600" id="display_grand_total">Rp {{ number_format($subtotal + $uniqueCode, 0, ',', '.') }}</span>
                            </div>
                            <div class="bg-amber-50 text-amber-800 text-xs p-3 rounded-lg mt-2 border border-amber-200 flex items-start gap-2">
                                <i class="fas fa-exclamation-triangle mt-0.5"></i>
                                <p><strong>PENTING:</strong> Pastikan Anda mentransfer nominal tepat hingga 3 digit terakhir agar sistem kami dapat memverifikasi pembayaran Anda dengan cepat.</p>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white p-6 md:p-8 rounded-3xl border border-amber-200 shadow-sm relative overflow-hidden">
                        <div class="absolute top-0 left-0 w-full h-2 bg-amber-500"></div>
                        <h2 class="text-xl font-bold mb-2">Pembayaran QRIS</h2>
                        <p class="text-sm text-stone-500 mb-6">Scan QR Code di bawah ini menggunakan aplikasi M-Banking atau E-Wallet Anda (GoPay, OVO, Dana, dll).</p>
                        
                        <div class="bg-stone-100 rounded-xl p-4 flex justify-center mb-6">
                            <img src="{{ asset('images/qris-apud.png') }}" alt="QRIS Haji Apud" class="w-48 h-48 object-contain rounded-xl shadow-sm border border-stone-200 bg-white">
                        </div>

                        <div class="mb-6">
                            <label class="block text-sm font-bold text-stone-700 mb-2">
                                <i class="fas fa-cloud-upload-alt text-blue-500 mr-1"></i> Unggah Bukti Transfer
                            </label>
                            <input type="file" name="payment_proof" accept="image/*" required class="w-full bg-white border border-stone-300 rounded-xl px-4 py-2 text-sm file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-amber-50 file:text-amber-700 hover:file:bg-amber-100 cursor-pointer">
                            <p class="text-xs text-stone-400 mt-2">*Maksimal ukuran file 2MB (Format: JPG, JPEG, PNG).</p>
                        </div>

                        <button type="submit" id="submit_btn" class="w-full bg-amber-600 hover:bg-gray-900 text-white font-bold text-lg py-4 rounded-xl transition-colors shadow-lg flex justify-center items-center opacity-50 cursor-not-allowed" disabled>
                            <i class="fas fa-check-circle mr-2"></i> Pilih Kurir Terlebih Dahulu
                        </button>
                    </div>

                </div>
            </div>
        </form>
    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search_area');
            const resultsList = document.getElementById('area_results');
            const loaderArea = document.getElementById('loader_area');
            const loaderRates = document.getElementById('loader_rates');
            
            const courierSection = document.getElementById('courier_section');
            const ratesList = document.getElementById('rates_list');
            const ratesError = document.getElementById('rates_error');
            
            const inputAreaId = document.getElementById('input_area_id');
            const inputPostal = document.getElementById('input_postal');
            const inputShippingCost = document.getElementById('input_shipping_cost');
            const inputCourierCompany = document.getElementById('input_courier_company');
            const inputCourierType = document.getElementById('input_courier_type');
            
            const displayShipping = document.getElementById('display_shipping');
            const displayGrandTotal = document.getElementById('display_grand_total');
            const submitBtn = document.getElementById('submit_btn');
            
            const subtotal = parseInt(document.getElementById('display_subtotal').getAttribute('data-value'));
            const uniqueCode = parseInt(document.getElementById('display_unique').getAttribute('data-value'));
            
            let searchTimeout;

            // 1. Fungsi Format Rupiah
            const formatRp = (angka) => {
                return 'Rp ' + angka.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
            };

            // 2. Event Listener saat mengetik kecamatan
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                const keyword = this.value;
                
                if (keyword.length < 3) {
                    resultsList.classList.add('hidden');
                    return;
                }

                loaderArea.style.display = 'block';
                
                // Beri jeda 500ms agar tidak spam API
                searchTimeout = setTimeout(() => {
                    fetch(`/api/biteship/search-area?input=${keyword}`)
                        .then(response => response.json())
                        .then(data => {
                            loaderArea.style.display = 'none';
                            resultsList.innerHTML = '';
                            
                            if(data.success && data.areas.length > 0) {
                                data.areas.forEach(area => {
                                    const li = document.createElement('li');
                                    li.className = 'px-4 py-3 hover:bg-amber-50 cursor-pointer border-b border-stone-100 text-sm';
                                    li.innerHTML = `<span class="font-bold">${area.name}</span>, ${area.administrative_division_level_2_name}, ${area.administrative_division_level_1_name}`;
                                    
                                    li.addEventListener('click', () => {
                                        // Saat kecamatan diklik
                                        searchInput.value = `${area.name}, ${area.administrative_division_level_2_name}`;
                                        inputAreaId.value = area.id;
                                        resultsList.classList.add('hidden');
                                        
                                        // Kosongkan ongkir lama
                                        resetCourierSelection();
                                        
                                        // Cari harga kurir
                                        checkShippingRates(area.id);
                                    });
                                    resultsList.appendChild(li);
                                });
                                resultsList.classList.remove('hidden');
                            } else {
                                resultsList.innerHTML = '<li class="px-4 py-3 text-sm text-stone-500 italic">Area tidak ditemukan</li>';
                                resultsList.classList.remove('hidden');
                            }
                        })
                        .catch(err => {
                            loaderArea.style.display = 'none';
                            console.error('Error fetching area:', err);
                        });
                }, 500);
            });

            // Sembunyikan hasil pencarian jika klik di luar
            document.addEventListener('click', function(e) {
                if (!searchInput.contains(e.target) && !resultsList.contains(e.target)) {
                    resultsList.classList.add('hidden');
                }
            });

            // 3. Fungsi Mengecek Harga Kurir
            function checkShippingRates(areaId) {
                courierSection.classList.remove('hidden');
                ratesList.innerHTML = '';
                ratesError.classList.add('hidden');
                loaderRates.style.display = 'block';

                fetch('/api/biteship/check-rates', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                    },
                    body: JSON.stringify({ destination_area_id: areaId })
                })
                .then(response => response.json())
                .then(data => {
                    loaderRates.style.display = 'none';
                    
                    if(data.success && data.rates.length > 0) {
                        data.rates.forEach((rate, index) => {
                            // Tampilkan opsi radio button untuk setiap layanan kurir
                            const isChecked = index === 0 ? 'checked' : '';
                            const rateHtml = `
                                <label class="flex items-center p-3 border border-stone-200 bg-white rounded-lg cursor-pointer hover:border-amber-400 transition-colors">
                                    <input type="radio" name="courier_selection" class="w-4 h-4 text-amber-600 focus:ring-amber-500 border-gray-300" 
                                           value="${rate.price}" 
                                           data-company="${rate.company}" 
                                           data-type="${rate.type}" 
                                           ${isChecked}>
                                    <div class="ml-3 flex-1 flex justify-between items-center">
                                        <div>
                                            <span class="block text-sm font-bold text-gray-900 uppercase">${rate.company} - ${rate.type}</span>
                                            <span class="block text-xs text-stone-500">Estimasi: ${rate.shipment_duration_range} ${rate.shipment_duration_unit}</span>
                                        </div>
                                        <span class="text-sm font-bold text-amber-700">${formatRp(rate.price)}</span>
                                    </div>
                                </label>
                            `;
                            ratesList.insertAdjacentHTML('beforeend', rateHtml);
                        });

                        // Aktifkan pilihan pertama secara otomatis
                        updateTotals();
                        
                        // Event listener saat kurir diganti
                        const radioButtons = document.querySelectorAll('input[name="courier_selection"]');
                        radioButtons.forEach(radio => {
                            radio.addEventListener('change', updateTotals);
                        });

                    } else {
                        ratesError.textContent = 'Tidak ada layanan kurir yang tersedia untuk area ini.';
                        ratesError.classList.remove('hidden');
                    }
                })
                .catch(err => {
                    loaderRates.style.display = 'none';
                    ratesError.textContent = 'Terjadi kesalahan jaringan saat mengambil tarif.';
                    ratesError.classList.remove('hidden');
                });
            }

            // 4. Fungsi Mengupdate Total Harga dan Mengaktifkan Tombol
            function updateTotals() {
                const selectedCourier = document.querySelector('input[name="courier_selection"]:checked');
                
                if(selectedCourier) {
                    const shippingCost = parseInt(selectedCourier.value);
                    
                    // Update input hidden
                    inputShippingCost.value = shippingCost;
                    inputCourierCompany.value = selectedCourier.getAttribute('data-company');
                    inputCourierType.value = selectedCourier.getAttribute('data-type');
                    
                    // Update tampilan
                    displayShipping.textContent = formatRp(shippingCost);
                    displayGrandTotal.textContent = formatRp(subtotal + shippingCost + uniqueCode);
                    
                    // Aktifkan tombol submit
                    submitBtn.disabled = false;
                    submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                    submitBtn.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Konfirmasi Pesanan';
                }
            }

            // 5. Fungsi Reset
            function resetCourierSelection() {
                inputShippingCost.value = 0;
                inputCourierCompany.value = '';
                inputCourierType.value = '';
                displayShipping.textContent = 'Rp 0';
                displayGrandTotal.textContent = formatRp(subtotal + uniqueCode);
                submitBtn.disabled = true;
                submitBtn.classList.add('opacity-50', 'cursor-not-allowed');
                submitBtn.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Pilih Kurir Terlebih Dahulu';
            }
        });
    </script>
</body>
</html>