@extends('layouts.main')

@section('title', $product->product_title . ' - Checkout Produk')

@section('content')
    <div class="w-full max-w-[1200px] mx-auto px-3 sm:px-4">
        <!-- Header Checkout -->
        <div class="mb-4 md:mb-8">
            <h1 class="text-2xl md:text-3xl font-bold text-gray-800 mb-1 md:mb-2">Checkout</h1>
            <p class="text-sm md:text-base text-gray-600">Lengkapi data pesanan Anda untuk melanjutkan pembayaran</p>
        </div>

        <!-- Main Form -->
        <form action="{{ route('checkout.store', $product->id) }}" method="POST" id="checkoutForm">
            @csrf
            <div class="flex flex-col lg:flex-row gap-4 sm:gap-6">
                <!-- Left Section - Detail Tagihan -->
                <div class="w-full lg:w-3/5 flex flex-col">
                    <!-- Product Card -->
                    <div class="bg-white rounded-lg shadow-md p-3 md:p-4 mb-4 md:mb-6 flex items-start gap-3 md:gap-4">
                        <!-- Delete Button -->
                        <button type="button" id="deleteProduct"
                            class="text-gray-400 hover:text-red-500 transition-colors mt-2">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                                stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                        </button>

                        <!-- Product Image -->
                        <div class="flex-shrink-0">
                            <img src="{{ asset('uploads/products/' . $product->product_image) }}"
                                alt="{{ $product->product_title }}" class="w-24 h-24 md:w-32 md:h-32 object-contain rounded-lg">
                        </div>

                        <!-- Product Info -->
                        <div class="flex-1 min-w-0">
                            <h3 class="text-base md:text-lg font-semibold text-blue-600 mb-1 md:mb-2 line-clamp-2">
                                {{ $product->product_title }}
                            </h3>

                            <!-- Quantity Control -->
                            <div class="flex items-center gap-2 md:gap-3 mb-2 md:mb-3">
                                <button type="button" id="decreaseQtyTop"
                                    class="w-7 h-7 md:w-8 md:h-8 bg-gray-200 hover:bg-gray-300 rounded flex items-center justify-center font-semibold transition-colors text-sm md:text-base">
                                    −
                                </button>
                                <input type="number" id="quantityTop" value="1" min="1"
                                    class="w-14 md:w-16 text-center px-1 md:px-2 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:outline-none text-sm md:text-base">
                                <button type="button" id="increaseQtyTop"
                                    class="w-7 h-7 md:w-8 md:h-8 bg-gray-200 hover:bg-gray-300 rounded flex items-center justify-center font-semibold transition-colors text-sm md:text-base">
                                    +
                                </button>
                            </div>

                            <!-- Price -->
                            <p class="text-lg md:text-xl font-bold text-gray-800" id="topItemPrice">
                                Rp{{ number_format($product->product_prices, 0, ',', '.') }}
                            </p>
                        </div>
                    </div>

                    <!-- Detail Tagihan Form -->
                    <div class="bg-white rounded-lg shadow-md p-4 md:p-5 flex flex-col flex-grow">
                        <h2 class="text-lg md:text-xl font-bold text-gray-800 mb-3 md:mb-4">Detail Data Pemesan</h2>
                        
                        <div class="flex flex-col flex-grow">
                        <!-- Nama Lengkap & Nomor Telepon -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4 mb-3 md:mb-4">
                            <div>
                                <div class="flex items-center justify-between mb-2">
                                    <label class="block text-sm font-medium text-gray-700">
                                        Nama Lengkap <span class="text-red-500">*</span>
                                    </label>
                                    @auth
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" id="useDifferentName" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500">
                                        <span class="text-xs text-gray-600">Gunakan nama lain</span>
                                    </label>
                                    @endauth
                                </div>
                                <input type="text" name="customer_name" id="customer_name" 
                                    value="{{ old('customer_name', auth()->user()->name ?? '') }}"
                                    placeholder="Masukkan nama lengkap" required
                                    class="w-full px-3 md:px-4 py-2 md:py-3 rounded-lg focus:ring-2 focus:outline-none transition-all text-sm md:text-base
                                {{ $errors->has('customer_name') ? 'border border-red-500 focus:ring-red-500 focus:border-red-500' : 'border border-gray-300 focus:ring-blue-500 focus:border-blue-500' }}">
                                @error('customer_name')
                                    <span class="text-red-500 text-sm mt-1 block">{{ $message }}</span>
                                @enderror
                            </div>

                            <div>
                                <div class="flex items-center justify-between mb-2">
                                    <label class="block text-sm font-medium text-gray-700">
                                        Nomor Telepon <span class="text-red-500">*</span>
                                    </label>
                                    @auth
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" id="useDifferentPhone" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500">
                                        <span class="text-xs text-gray-600">Gunakan nomor lain</span>
                                    </label>
                                    @endauth
                                </div>
                                <input type="tel" name="phone_number" id="phone_number" 
                                    value="{{ old('phone_number', auth()->user()->phone ?? '') }}"
                                    placeholder="+6281234567890 atau 081234567890" required
                                    class="w-full px-3 md:px-4 py-2 md:py-3 rounded-lg focus:ring-2 focus:outline-none transition-all text-sm md:text-base
                                {{ $errors->has('phone_number') ? 'border border-red-500 focus:ring-red-500 focus:border-red-500' : 'border border-gray-300 focus:ring-blue-500 focus:border-blue-500' }}">
                                <p class="text-xs text-gray-500 mt-1">Format: +62 atau 08 (minimal 10 digit)</p>
                                @error('phone_number')
                                    <span class="text-red-500 text-sm mt-1 block">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <!-- Alamat Lengkap -->
                        <div class="mb-3 md:mb-4">
                            <div class="flex items-center justify-between mb-2">
                                <label class="block text-sm font-medium text-gray-700">
                                    Alamat Lengkap <span class="text-red-500">*</span>
                                </label>
                                @auth
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="checkbox" id="useDifferentAddress" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500">
                                    <span class="text-xs text-gray-600">Gunakan alamat lain</span>
                                </label>
                                @endauth
                            </div>
                            <textarea name="address" id="address" rows="3" 
                                placeholder="Jalan, RT/RW, Kelurahan, Kecamatan, Kota, Provinsi" required
                                class="w-full px-3 md:px-4 py-2 md:py-3 rounded-lg resize-none focus:ring-2 focus:outline-none transition-all text-sm md:text-base
                            {{ $errors->has('address') ? 'border border-red-500 focus:ring-red-500 focus:border-red-500' : 'border border-gray-300 focus:ring-blue-500 focus:border-blue-500' }}">{{ old('address', auth()->user()->address ?? '') }}</textarea>
                            <p class="text-xs text-gray-500 mt-1">Pastikan alamat lengkap dan jelas untuk memudahkan pengiriman</p>
                            @error('address')
                                <span class="text-red-500 text-xs md:text-sm mt-1 block">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Kode Pos -->
                        <div class="mb-3 md:mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Kode Pos <span class="text-gray-400 text-xs">(Opsional)</span>
                            </label>
                            <input type="text" name="postal_code" id="postal_code" 
                                value="{{ old('postal_code', auth()->user()->postal_code ?? '') }}"
                                placeholder="12345" 
                                pattern="[0-9]{5}"
                                maxlength="5"
                                class="w-full px-3 md:px-4 py-2 md:py-3 rounded-lg focus:ring-2 focus:outline-none transition-all text-sm md:text-base
                            {{ $errors->has('postal_code') ? 'border border-red-500 focus:ring-red-500 focus:border-red-500' : 'border border-gray-300 focus:ring-blue-500 focus:border-blue-500' }}">
                            <p class="text-xs text-gray-500 mt-1">Kode pos membantu mempercepat proses pengiriman</p>
                            @error('postal_code')
                                <span class="text-red-500 text-sm mt-1 block">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Email -->
                        <div class="mb-3 md:mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Alamat Email <span class="text-red-500">*</span>
                            </label>
                            <input type="email" name="customer_email" id="customer_email"
                                value="{{ old('customer_email', auth()->user()->email ?? '') }}"
                                placeholder="email@example.com" required
                                class="w-full px-3 md:px-4 py-2 md:py-3 rounded-lg focus:ring-2 focus:outline-none transition-all text-sm md:text-base
                            {{ $errors->has('customer_email') ? 'border border-red-500 focus:ring-red-500 focus:border-red-500' : 'border border-gray-300 focus:ring-blue-500 focus:border-blue-500' }}">
                            <p class="text-xs text-gray-500 mt-1">Email ini akan digunakan untuk konfirmasi pesanan</p>
                            @error('customer_email')
                                <span class="text-red-500 text-sm mt-1 block">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Hidden Quantity & Price -->
                        <input type="hidden" name="quantity" id="quantity" value="1">
                        <input type="hidden" name="total_price" id="total_price" value="{{ $product->product_prices }}">
                        </div>
                    </div>
                </div>

                <!-- Right Section - Ringkasan Pesanan -->
                <div class="w-full lg:w-2/5 flex flex-col">
                    <div class="bg-white rounded-lg shadow-md p-4 md:p-6 lg:sticky lg:top-4 flex flex-col">
                        <h2 class="text-xl md:text-2xl font-bold text-gray-800 mb-4 md:mb-6">Ringkasan Pesanan</h2>
                        
                        <div class="flex flex-col">
                        <div class="flex items-start gap-3 md:gap-4 mb-4 md:mb-6 pb-4 md:pb-6 border-b border-gray-200">
                            <img src="{{ asset('uploads/products/' . $product->product_image) }}"
                                alt="{{ $product->product_title }}" class="w-16 h-16 md:w-20 md:h-20 object-contain rounded-lg flex-shrink-0">
                            <div class="flex-1 min-w-0">
                                <h3 class="font-semibold text-gray-800 text-xs md:text-sm mb-1 line-clamp-2">
                                    {{ $product->product_title }}</h3>
                                <p class="text-gray-600 text-xs md:text-sm">Jumlah: <span id="displayQty"
                                        class="font-semibold">1</span></p>
                                <p class="text-blue-600 font-semibold mt-1 text-sm md:text-base">
                                    Rp{{ number_format($product->product_prices, 0, ',', '.') }}</p>
                                
                                <!-- Informasi Produk -->
                                <div class="mt-2 space-y-1">
                                    @if($product->product_garansi)
                                        <div class="flex items-center text-xs text-gray-600">
                                            <i class="fas fa-shield-alt text-green-600 mr-1.5"></i>
                                            <span>Garansi: {{ $product->product_garansi }}</span>
                                        </div>
                                    @endif
                                    @if($product->product_work_duration)
                                        <div class="flex items-center text-xs text-gray-600">
                                            <i class="far fa-clock text-blue-600 mr-1.5"></i>
                                            <span>Pengerjaan: {{ $product->product_work_duration }}</span>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>

                        <div class="space-y-2 md:space-y-3 mb-4 md:mb-6">
                            <div class="flex justify-between text-gray-700">
                                <span class="font-medium">Subtotal</span>
                                <span id="subtotal"
                                    class="font-semibold">Rp{{ number_format($product->product_prices, 0, ',', '.') }}</span>
                            </div>
                            <div
                                class="flex justify-between text-xl font-bold text-gray-900 pt-3 border-t-2 border-gray-200">
                                <span>Total</span>
                                <span id="total"
                                    class="text-blue-600">Rp{{ number_format($product->product_prices, 0, ',', '.') }}</span>
                            </div>
                        </div>

                        <!-- Payment Method -->
                        <div class="mb-4 md:mb-6">
                            <label class="block text-sm font-medium text-gray-700 mb-2 md:mb-3">Metode Pembayaran <span
                                    class="text-red-500">*</span></label>
                            <div class="space-y-2 md:space-y-3">
                                <label
                                    class="flex items-center p-3 md:p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-all">
                                    <input type="radio" name="payment_method" value="transfer"
                                        class="w-4 h-4 md:w-5 md:h-5 text-blue-600 flex-shrink-0" checked>
                                    <div class="ml-2 md:ml-3 min-w-0">
                                        <span class="font-medium text-gray-800 text-sm md:text-base block">Transfer Bank</span>
                                        <p class="text-xs text-gray-500 mt-0.5 md:mt-1">Bank Syariah Indonesia (BSI)</p>
                                    </div>
                                </label>
                                <label
                                    class="flex items-center p-3 md:p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-all">
                                    <input type="radio" name="payment_method" value="midtrans"
                                        class="w-4 h-4 md:w-5 md:h-5 text-blue-600 flex-shrink-0">
                                    <div class="ml-2 md:ml-3 min-w-0">
                                        <span class="font-medium text-gray-800 text-sm md:text-base block">E-Wallet / QRIS</span>
                                        <p class="text-xs text-gray-500 mt-0.5 md:mt-1">GoPay, OVO, Dana, QRIS</p>
                                    </div>
                                </label>
                               
                                <!-- <label
                                    class="flex items-center p-3 md:p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-green-500 hover:bg-green-50 transition-all">
                                    <input type="radio" name="payment_method" value="cod"
                                        class="w-4 h-4 md:w-5 md:h-5 text-green-600 flex-shrink-0">
                                    <div class="ml-2 md:ml-3 min-w-0">
                                        <span class="font-medium text-gray-800 text-sm md:text-base block">COD (Bayar di Tempat)</span>
                                        <p class="text-xs text-gray-500 mt-0.5 md:mt-1">Bayar langsung saat barang tiba</p>
                                    </div>
                                </label> -->
                                
                                <label
                                    class="flex items-center p-3 md:p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-orange-500 hover:bg-orange-50 transition-all">
                                    <input type="radio" name="payment_method" value="dp"
                                        class="w-4 h-4 md:w-5 md:h-5 text-orange-600 flex-shrink-0">
                                    <div class="ml-2 md:ml-3 min-w-0">
                                        <span class="font-medium text-gray-800 text-sm md:text-base block">Pembayaran DP (Down Payment)</span>
                                        <p class="text-xs text-gray-500 mt-0.5 md:mt-1">Bayar sebagian sekarang, sisanya saat mesin selesai</p>
                                    </div>
                                </label>
                            </div>
                            
                            <!-- Bank Information (shown when transfer or dp is selected) -->
                            <div id="bank-info" class="mt-3 hidden">
                                <div class="bg-blue-50 border-l-4 border-blue-500 rounded-lg p-3">
                                    <div class="flex items-center mb-2">
                                        <div class="w-7 h-7 bg-green-600 rounded-lg flex items-center justify-center mr-2 flex-shrink-0">
                                            <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path>
                                            </svg>
                                        </div>
                                        <div class="flex-1 min-w-0">
                                            <h4 class="text-xs font-semibold text-blue-900">Bank Syariah Indonesia (BSI)</h4>
                                            <p class="text-xs text-gray-600 mt-0.5">No. Rek: <span class="font-mono font-semibold text-gray-900">1234567890</span> | Atas Nama: <span class="font-medium text-gray-900">Poljam Technology Indonesia</span></p>
                                        </div>
                                    </div>
                                    <p class="text-xs text-blue-700 mt-1.5">Setelah pesanan dibuat, Anda akan diarahkan ke halaman konfirmasi pembayaran.</p>
                                </div>
                            </div>
                        </div>

                        <!-- Hidden Fields -->
                        <input type="hidden" name="product_id" value="{{ $product->id }}">
                        <input type="hidden" name="price" value="{{ $product->product_prices }}">

                        </div>

                        <!-- Submit Button -->
                        <button type="submit" id="submitBtn"
                            class="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-3 md:py-4 px-4 md:px-6 rounded-lg transition duration-200 flex items-center justify-center gap-2 shadow-lg hover:shadow-xl text-sm md:text-base mt-auto">
                            Buat Pesanan
                        </button>
                    </div>
                </div>
            </div>
        </form>

        <!-- Empty Cart -->
        <div id="emptyCart" class="hidden">
            <div class="bg-white rounded-lg shadow-md p-16 text-center">
                <h2 class="text-3xl font-bold text-gray-800 mb-3">Belum Ada Produk Dipilih</h2>
                <p class="text-gray-600 mb-8 text-lg">Silakan pilih produk yang ingin Anda beli dari katalog terlebih
                    dahulu.</p>
                <a href="{{ route('all') }}"
                    class="inline-flex items-center gap-2 bg-blue-500 hover:bg-blue-600 text-white font-semibold py-4 px-8 rounded-lg transition duration-200 shadow-lg hover:shadow-xl">Kembali
                    ke Toko</a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        const productPrice = Number(document.querySelector('input[name="price"]').value) || 0;

        const qtyInput = document.getElementById('quantity');
        const qtyTopInput = document.getElementById('quantityTop');
        const displayQty = document.getElementById('displayQty');
        const subtotalEl = document.getElementById('subtotal');
        const totalEl = document.getElementById('total');
        const totalPriceInput = document.getElementById('total_price');
        const topItemPriceEl = document.getElementById('topItemPrice');

        function updatePrice() {
            const qty = parseInt(qtyTopInput.value);
            const total = productPrice * qty;

            qtyInput.value = qty;
            displayQty.textContent = qty;

            subtotalEl.textContent = 'Rp' + total.toLocaleString('id-ID');
            totalEl.textContent = 'Rp' + total.toLocaleString('id-ID');
            topItemPriceEl.textContent = 'Rp' + total.toLocaleString('id-ID');
            totalPriceInput.value = total;
        }

        document.getElementById('increaseQtyTop').addEventListener('click', () => {
            qtyTopInput.value = parseInt(qtyTopInput.value) + 1;
            updatePrice();
        });

        document.getElementById('decreaseQtyTop').addEventListener('click', () => {
            if (parseInt(qtyTopInput.value) > 1) {
                qtyTopInput.value = parseInt(qtyTopInput.value) - 1;
                updatePrice();
            }
        });

        document.getElementById('deleteProduct').addEventListener('click', function() {
            Swal.fire({
                title: 'Hapus Produk?',
                text: 'Apakah Anda yakin ingin menghapus produk ini dari checkout?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#2563EB',
                cancelButtonColor: '#6B7280',
                confirmButtonText: 'Ya, hapus',
                cancelButtonText: 'Batal',
                reverseButtons: true,
                showClass: {
                    popup: 'animate__animated animate__fadeInDown'
                },
                hideClass: {
                    popup: 'animate__animated animate__fadeOutUp'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const checkoutForm = document.getElementById('checkoutForm');
                    const emptyCart = document.getElementById('emptyCart');

                    // Animasi hilang
                    checkoutForm.style.transition = 'opacity 0.3s';
                    checkoutForm.style.opacity = 0;

                    setTimeout(() => {
                        checkoutForm.style.display = 'none';
                        emptyCart.classList.remove('hidden');
                        emptyCart.style.opacity = 0;
                        emptyCart.style.transition = 'opacity 0.3s';
                        emptyCart.style.opacity = 1;

                        // SweetAlert sukses smooth
                        Swal.fire({
                            title: 'Produk Dihapus!',
                            text: 'Produk berhasil dihapus dari checkout.',
                            icon: 'success',
                            timer: 1200,
                            showConfirmButton: false,
                            position: 'center',
                            timerProgressBar: true,
                            showClass: {
                                popup: 'animate__animated animate__fadeInDown'
                            },
                            hideClass: {
                                popup: 'animate__animated animate__fadeOutUp'
                            }
                        });
                    }, 300);
                }
            });
        });


        qtyTopInput.addEventListener('change', updatePrice);

        // Toggle bank info berdasarkan payment method
        const paymentMethods = document.querySelectorAll('input[name="payment_method"]');
        const bankInfo = document.getElementById('bank-info');
        
        function toggleBankInfo() {
            const selectedMethod = document.querySelector('input[name="payment_method"]:checked');
            if (selectedMethod && (selectedMethod.value === 'transfer' || selectedMethod.value === 'dp')) {
                bankInfo.classList.remove('hidden');
            } else {
                bankInfo.classList.add('hidden');
            }
        }
        
        // Set initial state (transfer is checked by default)
        toggleBankInfo();
        
        // Add event listeners to all payment method radio buttons
        paymentMethods.forEach(method => {
            method.addEventListener('change', toggleBankInfo);
        });

        // Validasi format nomor telepon - menerima +62 atau 08
        const phoneInput = document.getElementById('phone_number');
        const addressInput = document.getElementById('address');
        const customerNameInput = document.getElementById('customer_name');

        // Toggle untuk menggunakan nama/alamat/nomor telepon lain
        @auth
        const useDifferentName = document.getElementById('useDifferentName');
        const useDifferentPhone = document.getElementById('useDifferentPhone');
        const useDifferentAddress = document.getElementById('useDifferentAddress');
        
        // Simpan nilai default dari user
        const defaultName = '{{ old('customer_name', auth()->user()->name ?? '') }}';
        const defaultPhone = '{{ old('phone_number', auth()->user()->phone ?? '') }}';
        const defaultAddress = `{{ old('address', auth()->user()->address ?? '') }}`;

        // Toggle nama lengkap
        if (useDifferentName && customerNameInput) {
            useDifferentName.addEventListener('change', function() {
                if (this.checked) {
                    // Kosongkan field untuk input manual
                    customerNameInput.value = '';
                    customerNameInput.placeholder = 'Masukkan nama lengkap lain';
                    customerNameInput.focus();
                } else {
                    // Kembalikan ke nilai default
                    customerNameInput.value = defaultName;
                    customerNameInput.placeholder = 'Masukkan nama lengkap';
                }
            });
        }

        // Toggle nomor telepon
        if (useDifferentPhone && phoneInput) {
            useDifferentPhone.addEventListener('change', function() {
                if (this.checked) {
                    // Kosongkan field untuk input manual
                    phoneInput.value = '';
                    phoneInput.placeholder = 'Masukkan nomor telepon lain';
                    phoneInput.focus();
                } else {
                    // Kembalikan ke nilai default
                    phoneInput.value = defaultPhone;
                    phoneInput.placeholder = '+6281234567890 atau 081234567890';
                }
            });
        }

        // Toggle alamat
        if (useDifferentAddress && addressInput) {
            useDifferentAddress.addEventListener('change', function() {
                if (this.checked) {
                    // Kosongkan field untuk input manual
                    addressInput.value = '';
                    addressInput.placeholder = 'Masukkan alamat lain';
                    addressInput.focus();
                } else {
                    // Kembalikan ke nilai default
                    addressInput.value = defaultAddress;
                    addressInput.placeholder = 'Jalan, RT/RW, Kelurahan, Kecamatan, Kota, Provinsi';
                }
            });
        }
        @endauth
        if (phoneInput) {
            phoneInput.addEventListener('input', function(e) {
                let value = this.value;
                
                // Izinkan angka, +, dan spasi
                value = value.replace(/[^0-9+]/g, '');
                
                // Normalisasi format +62 menjadi 0
                if (value.startsWith('+62')) {
                    value = '0' + value.substring(3);
                } else if (value.startsWith('62') && !value.startsWith('620')) {
                    value = '0' + value.substring(2);
                }
                
                this.value = value;
            });

            phoneInput.addEventListener('blur', function() {
                let phoneValue = this.value.trim();
                
                // Normalisasi format untuk validasi
                if (phoneValue.startsWith('+62')) {
                    phoneValue = '0' + phoneValue.substring(3);
                } else if (phoneValue.startsWith('62') && phoneValue.length > 2) {
                    phoneValue = '0' + phoneValue.substring(2);
                } else if (phoneValue.startsWith('8') && !phoneValue.startsWith('08')) {
                    phoneValue = '0' + phoneValue;
                }
                
                // Update value jika berubah
                if (phoneValue !== this.value) {
                    this.value = phoneValue;
                }
                
                // Validasi
                if (phoneValue.length > 0 && phoneValue.length < 10) {
                    this.setCustomValidity('Nomor telepon minimal 10 digit');
                } else if (phoneValue.length > 0 && !phoneValue.startsWith('08') && !phoneValue.startsWith('+62')) {
                    this.setCustomValidity('Nomor telepon harus dimulai dengan 08 atau +62');
                } else {
                    this.setCustomValidity('');
                }
            });
        }

        // checkout form
        document.getElementById('checkoutForm').addEventListener('submit', async function(e) {
            e.preventDefault(); // hentikan submit default

            const formData = new FormData(this);
            
            // Ambil payment method yang dipilih
            const paymentMethod = formData.get('payment_method');

            try {
                const response = await fetch(this.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                });

                const data = await response.json();

                // Handle error dari server
                if (data.error) {
                    Swal.fire('Error', data.message || 'Terjadi kesalahan saat memproses pembayaran', 'error');
                    return;
                }

                // Jika Midtrans dipilih, server mengembalikan snap_token
                if (data.snap_token) {
                    // Pastikan snap object sudah tersedia
                    if (typeof snap === 'undefined') {
                        Swal.fire('Error', 'Midtrans Snap belum dimuat. Silakan refresh halaman.', 'error');
                        return;
                    }

                    snap.pay(data.snap_token, {
                        onSuccess: function(result) {
                            // Redirect ke halaman success
                            const orderId = data.order_id || result.order_id;
                            // Gunakan route helper dari Laravel (sudah di-inject di blade)
                            const successUrl = '{{ route("orders.success", ":id") }}'.replace(':id', orderId);
                            window.location.href = successUrl;
                        },
                        onPending: function(result) {
                            // Untuk pending, tetap redirect ke success page
                            const orderId = data.order_id || result.order_id;
                            Swal.fire({
                                title: 'Pembayaran Pending',
                                text: 'Pembayaran sedang diproses. Silakan tunggu konfirmasi.',
                                icon: 'info',
                                confirmButtonText: 'OK'
                            }).then(() => {
                                // Gunakan route helper dari Laravel
                                const successUrl = '{{ route("orders.success", ":id") }}'.replace(':id', orderId);
                                window.location.href = successUrl;
                            });
                        },
                        onError: function(result) {
                            Swal.fire('Error', 'Terjadi kesalahan dalam pembayaran. Silakan coba lagi.', 'error');
                            console.error('Midtrans error:', result);
                        },
                        onClose: function() {
                            // Hapus order yang dibatalkan saat user tutup popup
                            if (data.order_id) {
                                fetch(`/my-orders/${data.order_id}/cancel-midtrans`, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                        'X-Requested-With': 'XMLHttpRequest'
                                    }
                                }).then(response => response.json())
                                .then(result => {
                                    if (result.success) {
                                        console.log('Order cancelled:', result.message);
                                    }
                                }).catch(error => {
                                    console.error('Error cancelling order:', error);
                                });
                            }
                            
                            Swal.fire({
                                title: 'Ditutup',
                                text: 'Anda menutup pembayaran sebelum selesai. Order telah dibatalkan.',
                                icon: 'warning',
                                confirmButtonText: 'OK'
                            });
                        }
                    });
                    return; // Stop, tidak lanjut ke flow success biasa
                }

                if (data.success) {
                    Swal.fire({
                        title: 'Sukses!',
                        text: data.message,
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        // Redirect ke URL yang dikembalikan dari server
                        window.location.href = data.redirect_url;
                    });
                } else {
                    Swal.fire('Gagal', data.message || 'Terjadi kesalahan', 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Terjadi kesalahan server', 'error');
            }
        });
    </script>
@endsection
