<?php $__env->startSection('title', 'Checkout Pesanan'); ?>

<?php $__env->startSection('content'); ?>
<div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10">

    <!-- Header & Breadcrumb -->
    <div class="mb-8 flex items-center justify-between">
        <form action="<?php echo e(route('pesanans.batalkan', $pesanan->id)); ?>" method="POST" class="inline">
            <?php echo csrf_field(); ?>
            <button type="submit" class="inline-flex items-center gap-2 text-sm font-medium text-gray-500 hover:text-primary bg-white px-4 py-2 rounded-full border border-gray-200 hover:border-gray-300 transition-all shadow-sm">
                <i class="bi bi-arrow-left"></i> Batal & Kembali ke Keranjang
            </button>
        </form>
        <h1 class="text-2xl font-extrabold text-primary tracking-tight hidden sm:block">Proses Checkout</h1>
    </div>

    <?php if(session('success')): ?>
        <div class="bg-green-50 text-green-700 border border-green-200 rounded-xl p-4 flex items-center gap-3 mb-6 font-medium text-sm">
            <i class="bi bi-check-circle-fill text-green-500 text-lg"></i>
            <?php echo e(session('success')); ?>

        </div>
    <?php endif; ?>
    
    <?php if(session('error')): ?>
        <div class="bg-red-50 text-red-700 border border-red-200 rounded-xl p-4 flex items-center gap-3 mb-6 font-medium text-sm">
            <i class="bi bi-exclamation-triangle-fill text-red-500 text-lg"></i>
            <?php echo e(session('error')); ?>

        </div>
    <?php endif; ?>

    <?php if($errors->any()): ?>
        <div class="bg-red-50 text-red-700 border border-red-200 rounded-xl p-4 mb-6 font-medium text-sm">
            <ul class="list-disc list-inside">
                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <li><?php echo e($error); ?></li>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        <!-- Kolom Kiri: Alamat & Produk -->
        <div class="lg:col-span-8 space-y-6">
            
            <!-- ALAMAT PENGIRIMAN -->
            <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-[0_8px_30px_rgb(0,0,0,0.04)]">
                <div class="flex items-center gap-2 text-lg font-bold text-primary mb-5">
                    <i class="bi bi-geo-alt-fill text-accent"></i> Alamat Pengiriman
                </div>
                
                <?php if($pesanan->alamat_tujuan): ?>
                    <div class="bg-gray-50 border border-gray-100 rounded-xl p-4 mb-4">
                        <div class="font-bold text-primary mb-1"><?php echo e($pesanan->user->nama ?? 'Pembeli'); ?></div>
                        <div class="text-sm text-secondary leading-relaxed">
                            <?php echo e($pesanan->alamat_tujuan); ?><br>
                            Desa/Kel. <?php echo e($pesanan->desa->name ?? '-'); ?>, Kec. <?php echo e($pesanan->kecamatan->name ?? '-'); ?><br>
                            <?php echo e($pesanan->regency->name ?? '-'); ?>, <?php echo e($pesanan->provinsi->name ?? '-'); ?> <?php echo e($pesanan->kode_pos); ?>

                        </div>
                    </div>
                    <button type="button" class="inline-flex items-center gap-2 bg-white text-primary border border-gray-200 px-4 py-2 rounded-full text-sm font-bold hover:bg-gray-50 hover:border-gray-300 transition" onclick="openAddressModal()">
                        <i class="bi bi-pencil"></i> Ubah Alamat
                    </button>
                <?php else: ?>
                    <div class="bg-red-50 border border-red-100 text-red-600 p-4 rounded-xl text-center font-medium text-sm mb-4 flex items-center justify-center gap-2">
                        <i class="bi bi-exclamation-circle-fill"></i> Anda belum memasukkan alamat pengiriman.
                    </div>
                    <button type="button" class="inline-flex items-center gap-2 bg-primary text-white border border-transparent px-5 py-2.5 rounded-full text-sm font-bold hover:bg-gray-800 transition" onclick="openAddressModal()">
                        <i class="bi bi-plus-circle"></i> Tambah Alamat
                    </button>
                <?php endif; ?>
            </div>

            <!-- DETAIL PRODUK -->
            <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-[0_8px_30px_rgb(0,0,0,0.04)]">
                <div class="flex items-center gap-2 text-lg font-bold text-primary mb-5">
                    <i class="bi bi-box-seam-fill text-accent"></i> Produk Dipesan
                </div>
                
                <div class="divide-y divide-gray-100">
                    <?php $__empty_1 = true; $__currentLoopData = $pesanan->detailPesanans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $detail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <div class="py-4 first:pt-0 last:pb-0 flex items-center gap-4">
                            <?php if($detail->produk && $detail->produk->foto): ?>
                                <img src="<?php echo e(asset('storage/' . $detail->produk->foto)); ?>" alt="<?php echo e($detail->produk->nama); ?>" class="w-16 h-16 rounded-xl object-cover bg-gray-50 border border-gray-100 shrink-0">
                            <?php else: ?>
                                <div class="w-16 h-16 bg-gray-50 rounded-xl flex items-center justify-center text-gray-300 border border-gray-100 shrink-0">
                                    <i class="bi bi-image text-2xl"></i>
                                </div>
                            <?php endif; ?>
                            <div class="flex-1 min-w-0">
                                <h4 class="text-sm font-bold text-primary truncate mb-1"><?php echo e($detail->produk ? $detail->produk->nama : 'Produk Tidak Diketahui'); ?></h4>
                                <div class="flex items-center justify-between">
                                    <span class="text-secondary font-semibold text-sm">Rp <?php echo e(number_format($detail->harga, 0, ',', '.')); ?></span>
                                    <span class="text-xs font-bold bg-gray-100 text-gray-600 px-2 py-1 rounded"><?php echo e($detail->jumlah); ?> x</span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <div class="text-center text-gray-400 py-6 text-sm">Tidak ada produk dalam pesanan ini.</div>
                    <?php endif; ?>
                </div>
            </div>
            
        </div>

        <!-- Kolom Kanan: Ringkasan & Bayar -->
        <div class="lg:col-span-4">
            <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-[0_8px_30px_rgb(0,0,0,0.04)] sticky top-24">
                <div class="flex items-center gap-2 text-lg font-bold text-primary mb-6">
                    <i class="bi bi-receipt-cutoff text-accent"></i> Ringkasan Belanja
                </div>
                
                <div class="space-y-3 text-sm font-medium text-secondary mb-6">
                    <div class="flex justify-between items-center">
                        <span>Total Harga (<?php echo e($pesanan->detailPesanans->sum('jumlah')); ?> Barang)</span>
                        <span class="text-primary font-bold">Rp <?php echo e(number_format($pesanan->total_harga, 0, ',', '.')); ?></span>
                    </div>
                </div>

                <div class="border-t border-gray-100 pt-4 mb-6">
                    <div class="flex justify-between items-center">
                        <span class="text-primary font-bold">Total Tagihan</span>
                        <span class="text-xl font-extrabold text-accentDark">Rp <?php echo e(number_format($pesanan->total_harga, 0, ',', '.')); ?></span>
                    </div>
                </div>

                <div class="bg-green-50 text-green-700 p-3 rounded-xl text-xs font-medium flex gap-2 items-start mb-6 border border-green-100">
                    <i class="bi bi-shield-check text-base mt-0.5"></i>
                    <p>Pembayaran aman dengan Midtrans. Mendukung transfer bank, e-wallet, dan QRIS.</p>
                </div>

                <button id="pay-button" class="w-full bg-primary text-white font-bold py-3.5 rounded-xl transition shadow-lg shadow-gray-200 hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-primary" <?php echo e(!$pesanan->alamat_tujuan ? 'disabled' : ''); ?> title="<?php echo e(!$pesanan->alamat_tujuan ? 'Silakan isi alamat terlebih dahulu' : ''); ?>">
                    Bayar Sekarang
                </button>
                <?php if(!$pesanan->alamat_tujuan): ?>
                    <div class="text-red-500 text-center mt-3 text-xs font-semibold">Isi alamat pengiriman untuk melanjutkan pembayaran.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Modal Tambah/Ubah Alamat -->
<div id="addressModal" class="fixed inset-0 z-50 flex hidden items-center justify-center p-4 bg-gray-900/40 backdrop-blur-sm transition-opacity duration-300 opacity-0">
    <!-- Modal Content -->
    <div class="bg-white rounded-3xl w-full max-w-2xl shadow-2xl flex flex-col max-h-[90vh] transform scale-95 transition-transform duration-300 overflow-hidden" id="addressModalContent" onclick="event.stopPropagation()">
        
        <!-- Header -->
        <div class="px-6 py-5 border-b border-gray-100 flex justify-between items-center bg-white">
            <h5 class="text-lg font-bold text-primary">Pilih Alamat Pengiriman</h5>
            <button type="button" class="text-gray-400 hover:text-red-500 transition text-2xl leading-none" onclick="closeAddressModal()">&times;</button>
        </div>
        
        <!-- Body (Scrollable) -->
        <div class="flex-1 overflow-y-auto w-full p-6 bg-gray-50/50">
            
            <!-- SECTION: ADDRESS LIST -->
            <div id="addressListSection">
                <?php $userAlamats = auth()->user()->alamats; ?>
                <?php if($userAlamats && $userAlamats->count() > 0): ?>
                    <form action="<?php echo e(route('pesanans.pilih_alamat', $pesanan->id)); ?>" method="POST">
                        <?php echo csrf_field(); ?>
                        <div class="space-y-3 mb-6">
                            <?php $__currentLoopData = $userAlamats; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $alamat): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <label class="block bg-white border border-gray-200 p-4 rounded-2xl cursor-pointer hover:border-accent transition relative <?php echo e($pesanan->alamat_tujuan == $alamat->alamat_lengkap ? '!border-accent ring-1 ring-accent bg-blue-50/10' : ''); ?>">
                                    <div class="flex items-start gap-3">
                                        <div class="pt-1">
                                            <input type="radio" name="alamat_id" value="<?php echo e($alamat->id); ?>" <?php echo e($pesanan->alamat_tujuan == $alamat->alamat_lengkap ? 'checked' : ''); ?> class="w-4 h-4 text-accent border-gray-300 focus:ring-accent">
                                        </div>
                                        <div class="flex-1">
                                            <div class="font-bold text-primary flex items-center gap-2">
                                                <?php echo e($alamat->label); ?> 
                                                <?php if($alamat->is_utama): ?> <span class="bg-green-100 text-green-700 text-[10px] uppercase font-bold px-2 py-0.5 rounded">Utama</span> <?php endif; ?>
                                            </div>
                                            <div class="text-sm font-semibold text-gray-700 mt-1"><?php echo e($alamat->nama_penerima); ?> <span class="text-gray-400 font-normal">(<?php echo e($alamat->no_telp); ?>)</span></div>
                                            <div class="text-sm text-gray-500 mt-1 leading-relaxed">
                                                <?php echo e($alamat->alamat_lengkap); ?><br>
                                                Desa/Kel. <?php echo e($alamat->desa->name ?? '-'); ?>, Kec. <?php echo e($alamat->kecamatan->name ?? '-'); ?><br>
                                                <?php echo e($alamat->regency->name ?? '-'); ?>, <?php echo e($alamat->provinsi->name ?? '-'); ?> <?php echo e($alamat->kode_pos); ?>

                                            </div>
                                        </div>
                                    </div>
                                </label>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                        <button type="submit" class="w-full bg-primary text-white font-bold py-3 rounded-xl hover:bg-gray-800 transition">Gunakan Alamat Terpilih</button>
                    </form>
                    
                    <div class="flex items-center my-6">
                        <div class="flex-1 border-t border-gray-200"></div>
                        <span class="px-4 text-xs font-bold text-gray-400 uppercase tracking-widest">ATAU</span>
                        <div class="flex-1 border-t border-gray-200"></div>
                    </div>
                <?php endif; ?>
                
                <button type="button" class="w-full bg-white border-2 border-gray-200 text-primary font-bold py-3 rounded-xl hover:border-gray-300 hover:bg-gray-50 transition" onclick="showAddressForm()">
                    <i class="bi bi-plus-lg mr-1"></i> Tambah Alamat Baru
                </button>
            </div>

            <!-- SECTION: ADDRESS FORM -->
            <div id="addressFormSection" style="display: <?php echo e(($userAlamats && $userAlamats->count() > 0) ? 'none' : 'block'); ?>;">
                <div class="flex items-center gap-3 mb-6 bg-white p-4 rounded-xl border border-gray-100 shadow-sm shadow-[0_4px_10px_rgb(0,0,0,0.02)]">
                    <?php if($userAlamats && $userAlamats->count() > 0): ?>
                    <button type="button" class="w-8 h-8 rounded-full bg-gray-50 hover:bg-gray-200 flex items-center justify-center transition border border-gray-200" onclick="showAddressList()">
                        <i class="bi bi-arrow-left text-primary"></i>
                    </button>
                    <?php endif; ?>
                    <h6 class="font-bold text-primary mb-0">Form Alamat Baru</h6>
                </div>
                
                <form action="<?php echo e(route('pesanans.simpan_alamat', $pesanan->id)); ?>" method="POST" class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
                    <?php echo csrf_field(); ?>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div class="md:col-span-2 space-y-1.5">
                            <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Label Alamat <span class="text-red-500">*</span></label>
                            <input type="text" name="label" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" placeholder="Rumah, Kantor, dll" value="Rumah" required>
                        </div>
                        <div class="space-y-1.5">
                            <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Nama Penerima <span class="text-red-500">*</span></label>
                            <input type="text" name="nama_penerima" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" placeholder="Nama lengkap penerima" value="<?php echo e(auth()->user()->nama); ?>" required>
                        </div>
                        <div class="space-y-1.5">
                            <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">No. HP <span class="text-red-500">*</span></label>
                            <input type="text" name="no_telp" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" placeholder="Contoh: 08123456789" required>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div class="space-y-1.5">
                            <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Provinsi <span class="text-red-500">*</span></label>
                            <select name="provinsi_id" id="provinsi" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" required>
                                <option value="">-- Pilih Provinsi --</option>
                            </select>
                        </div>
                        <div class="space-y-1.5">
                            <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Kota / Kabupaten <span class="text-red-500">*</span></label>
                            <select name="kota_id" id="kota" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" required disabled>
                                <option value="">-- Pilih Kota --</option>
                            </select>
                        </div>
                        <div class="space-y-1.5">
                            <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Kecamatan <span class="text-red-500">*</span></label>
                            <select name="kecamatan_id" id="kecamatan" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" required disabled>
                                <option value="">-- Pilih Kecamatan --</option>
                            </select>
                        </div>
                        <div class="space-y-1.5">
                            <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Desa / Kel <span class="text-red-500">*</span></label>
                            <select name="desa_id" id="desa" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" required disabled>
                                <option value="">-- Pilih Desa --</option>
                            </select>
                        </div>
                    </div>

                    <div class="space-y-1.5 mb-4">
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Kode Pos <span class="text-red-500">*</span></label>
                        <input type="text" name="kode_pos" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" placeholder="Contoh: 12345" required>
                    </div>

                    <div class="space-y-1.5 mb-6">
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wider">Detail Alamat <span class="text-red-500">*</span></label>
                        <textarea name="alamat_tujuan" class="w-full border-gray-200 rounded-xl focus:border-accent focus:ring-accent text-sm py-2.5" rows="3" placeholder="Nama Jalan, Gedung, No. Rumah, RT/RW, Patokan..." required></textarea>
                    </div>
                    
                    <div class="flex gap-3 justify-end pt-4 border-t border-gray-100">
                        <button type="button" class="bg-white border border-gray-200 text-gray-700 font-bold py-2.5 px-6 rounded-xl hover:bg-gray-50 transition" onclick="closeAddressModal()">Batal</button>
                        <button type="submit" class="bg-primary text-white font-bold py-2.5 px-6 rounded-xl hover:bg-gray-800 transition">Simpan Alamat</button>
                    </div>
                </form>
            </div>

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

<!-- Midtrans Snap Script -->
<script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="<?php echo e(config('midtrans.client_key')); ?>"></script>

<script>
// ---------- Payment Script ----------
function sendFrontendCallback(result, redirectUrl = null) {
    fetch("<?php echo e(route('midtrans.frontend_callback')); ?>", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": "<?php echo e(csrf_token()); ?>"
        },
        body: JSON.stringify(result)
    }).then(() => {
        if (redirectUrl) {
            window.location.href = redirectUrl;
        }
    }).catch(console.error);
}

const payBtn = document.getElementById('pay-button');
if (payBtn && !payBtn.disabled) {
    payBtn.onclick = function () {
        snap.pay('<?php echo e($snapToken); ?>', {
            onSuccess: function(result) {
                sendFrontendCallback(result, "/customer/dashboard");
            },
            onPending: function(result) {
                sendFrontendCallback(result);
                alert("⏳ Menunggu pembayaran! Silakan selesaikan pembayaran Anda.");
            },
            onError: function(result) {
                sendFrontendCallback(result);
                alert("❌ Pembayaran gagal! Silakan coba lagi.");
            }
        });
    };
}

// ---------- Address Modal Script ----------
const overlay = document.getElementById('addressModal');
const modalContent = document.getElementById('addressModalContent');

function openAddressModal() {
    overlay.classList.remove('hidden');
    // slight delay for transition
    setTimeout(() => {
        overlay.classList.remove('opacity-0');
        overlay.classList.add('opacity-100');
        modalContent.classList.remove('scale-95');
        modalContent.classList.add('scale-100');
    }, 10);
    document.body.style.overflow = 'hidden';
    
    // Load provinces on open if not loaded and form is visible
    if (document.getElementById('addressFormSection').style.display !== 'none') {
        const provSelect = document.getElementById('provinsi');
        if (provSelect.options.length <= 1) {
            fetchRegions('<?php echo e(route("regions.provinces")); ?>', provSelect);
        }
    }
}

function showAddressForm() {
    document.getElementById('addressListSection').style.display = 'none';
    document.getElementById('addressFormSection').style.display = 'block';
    const provSelect = document.getElementById('provinsi');
    if (provSelect.options.length <= 1) {
        fetchRegions('<?php echo e(route("regions.provinces")); ?>', provSelect);
    }
}

function showAddressList() {
    document.getElementById('addressListSection').style.display = 'block';
    document.getElementById('addressFormSection').style.display = 'none';
}

function closeAddressModal() {
    overlay.classList.remove('opacity-100');
    overlay.classList.add('opacity-0');
    modalContent.classList.remove('scale-100');
    modalContent.classList.add('scale-95');
    
    setTimeout(() => {
        overlay.classList.add('hidden');
        document.body.style.overflow = 'auto';
    }, 300);
}

// Close on background click
overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
        closeAddressModal();
    }
});


// ---------- Indoregion Dynamic Select Script ----------
const elProvinsi = document.getElementById('provinsi');
const elKota = document.getElementById('kota');
const elKecamatan = document.getElementById('kecamatan');
const elDesa = document.getElementById('desa');

// Helper fetch
async function fetchRegions(url, selectElement, defaultText = "Pilih") {
    try {
        selectElement.innerHTML = `<option value="">-- Sedang memuat... --</option>`;
        selectElement.disabled = true;
        
        const response = await fetch(url);
        const data = await response.json();
        
        selectElement.innerHTML = `<option value="">-- ${defaultText} --</option>`;
        
        data.forEach(item => {
            const option = document.createElement('option');
            option.value = item.id;
            option.textContent = item.name;
            selectElement.appendChild(option);
        });
        
        selectElement.disabled = false;
    } catch (error) {
        console.error('Error fetching data:', error);
        selectElement.innerHTML = `<option value="">-- Gagal memuat data --</option>`;
    }
}

elProvinsi.addEventListener('change', function() {
    elKota.innerHTML = `<option value="">-- Pilih Kota --</option>`;
    elKecamatan.innerHTML = `<option value="">-- Pilih Kecamatan --</option>`;
    elDesa.innerHTML = `<option value="">-- Pilih Desa --</option>`;
    elKota.disabled = true;
    elKecamatan.disabled = true;
    elDesa.disabled = true;

    if (this.value) {
        fetchRegions('<?php echo e(url("regions/cities")); ?>/' + this.value, elKota, "Pilih Kota");
    }
});

elKota.addEventListener('change', function() {
    elKecamatan.innerHTML = `<option value="">-- Pilih Kecamatan --</option>`;
    elDesa.innerHTML = `<option value="">-- Pilih Desa --</option>`;
    elKecamatan.disabled = true;
    elDesa.disabled = true;

    if (this.value) {
        fetchRegions('<?php echo e(url("regions/districts")); ?>/' + this.value, elKecamatan, "Pilih Kecamatan");
    }
});

elKecamatan.addEventListener('change', function() {
    elDesa.innerHTML = `<option value="">-- Pilih Desa --</option>`;
    elDesa.disabled = true;

    if (this.value) {
        fetchRegions('<?php echo e(url("regions/villages")); ?>/' + this.value, elDesa, "Pilih Desa");
    }
});
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.customer', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\Toko-miftah\resources\views/pesanans/process_checkout.blade.php ENDPATH**/ ?>