@extends('layout.temp')

@section('title', 'Penyelesaian Pesanan - ' . ($shop_settings['shop_name'] ?? 'PrintPro'))

@section('styles')
<style>
    :root {
        --c-primary: #2563eb;
        --c-slate-950: #020617;
        --c-slate-900: #0f172a;
        --c-slate-800: #1e293b;
        --c-slate-400: #94a3b8;
        --c-slate-100: #f1f5f9;
        --c-radius: 36px;
    }

    body {
        background: #fdfdfd;
        font-family: 'Plus Jakarta Sans', sans-serif;
    }

    .checkout-scene {
        padding: 80px 0 140px;
    }

    .page-header-v6 {
        margin-bottom: 60px;
    }

    .page-title-v6 {
        font-size: clamp(2rem, 5vw, 3.2rem);
        font-weight: 950;
        letter-spacing: -3px;
        color: var(--c-slate-900);
        line-height: 1;
        margin-bottom: 12px;
    }

    .page-breadcrumb {
        display: flex;
        align-items: center;
        gap: 15px;
        color: var(--c-slate-400);
        font-weight: 700;
        font-size: 14px;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    /* Modern Card System */
    .checkout-step-card {
        background: white;
        border-radius: var(--c-radius);
        border: 1px solid var(--c-slate-100);
        padding: 50px;
        margin-bottom: 40px;
        position: relative;
        transition: 0.4s;
    }

    .step-card-header {
        display: flex; align-items: center; gap: 20px; margin-bottom: 40px;
    }

    .step-number {
        width: 45px; height: 45px; background: var(--c-slate-900);
        color: white; border-radius: 14px; display: flex;
        align-items: center; justify-content: center; font-weight: 900;
    }

    .step-label { font-size: 1.4rem; font-weight: 900; letter-spacing: -1px; }

    /* Address Selection Modern */
    .address-selection-grid {
        display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 25px;
    }

    .modern-address-item { cursor: pointer; position: relative; }
    .address-input-hidden { display: none; }

    .address-card-v6 {
        padding: 30px; border-radius: 28px; border: 2px solid var(--c-slate-100);
        background: white; transition: 0.4s cubic-bezier(0.165, 0.84, 0.44, 1); height: 100%;
    }

    .address-input-hidden:checked + .address-card-v6 {
        border-color: var(--c-primary); background: var(--c-slate-100); transform: translateY(-5px);
        box-shadow: 0 20px 40px rgba(37, 99, 235, 0.08);
    }

    .receiver-name { display: block; font-weight: 900; font-size: 1.15rem; margin-bottom: 5px; }

    /* Payment Section */
    .payment-premium-box {
        background: #fcfcfc; border-radius: 30px; padding: 40px; border: 1px solid #f1f5f9;
        display: flex; flex-direction: column; gap: 30px;
    }

    .midtrans-badge {
        display: flex; align-items: center; gap: 20px;
    }

    .midtrans-logo-v6 { height: 35px; }

    .payment-methods-showcase {
        display: flex; flex-wrap: wrap; gap: 15px; opacity: 0.6;
    }

    .payment-methods-showcase img { height: 18px; filter: grayscale(1); transition: 0.3s; }
    .payment-methods-showcase img:hover { filter: grayscale(0); transform: scale(1.1); }

    /* Summary Sidebar */
    .checkout-summary-pro {
        background: var(--c-slate-900); border-radius: var(--c-radius);
        padding: 50px; color: white; position: sticky; top: 120px;
        box-shadow: 0 50px 100px -20px rgba(15, 23, 42, 0.2);
    }

    .summary-heading-pro {
        font-size: 1.6rem; font-weight: 950; margin-bottom: 40px;
        display: flex; justify-content: space-between; align-items: center;
    }

    .pro-item-v6 {
        display: flex; gap: 20px; margin-bottom: 25px;
    }

    .item-icon-v6 {
        width: 60px; height: 60px; background: white; border-radius: 16px;
        padding: 8px; flex-shrink: 0;
    }
    .item-icon-v6 img { width: 100%; height: 100%; object-fit: contain; }

    .item-info-v6 { flex: 1; min-width: 0; }
    .name-text-v6 { font-weight: 800; font-size: 0.95rem; margin-bottom: 3px; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

    .summary-total-v6 {
        margin-top: 40px; padding-top: 40px; border-top: 1px solid rgba(255,255,255,0.1);
    }

    .total-val-v6 { font-size: 2.8rem; font-weight: 950; letter-spacing: -2px; }

    .btn-checkout-pro {
        width: 100%; height: 80px; background: white; color: var(--c-slate-900);
        border-radius: 20px; font-weight: 950; font-size: 1.1rem;
        display: flex; align-items: center; justify-content: center; gap: 15px;
        transition: 0.4s cubic-bezier(0.165, 0.84, 0.44, 1); border: none;
    }

    .btn-checkout-pro:hover:not(:disabled) {
        background: var(--c-primary); color: white; transform: translateY(-8px);
        box-shadow: 0 20px 40px rgba(37, 99, 235, 0.3);
    }

    @media (max-width: 991px) {
        .checkout-summary-pro { position: static; margin-top: 50px; }
    }

    @media (max-width: 768px) {
        .checkout-scene { padding: 40px 0 80px; }
        .checkout-step-card { padding: 25px 20px; border-radius: 20px; margin-bottom: 25px; }
        .checkout-summary-pro { padding: 30px 20px; border-radius: 20px; margin-top: 30px; }
        .step-label { font-size: 1.3rem; }
        .page-title-v6 { font-size: 2rem; }
        .payment-premium-box { padding: 25px 20px; border-radius: 20px; gap: 20px; }
        .midtrans-badge { flex-direction: column; align-items: flex-start; gap: 10px; }
        .summary-heading-pro { font-size: 1.4rem; margin-bottom: 25px; }
        .total-val-v6 { font-size: 2.2rem; }
        .btn-checkout-pro { height: 65px; font-size: 1rem; border-radius: 16px; }
    }
</style>
@endsection

@section('content')
<main class="checkout-scene">
    <div class="container animate__animated animate__fadeIn">
        <header class="page-header-v6">
            <nav class="page-breadcrumb mb-3">
                <a href="{{ route('home') }}" class="text-decoration-none text-muted">Beranda</a>
                <i class="lni lni-chevron-right text-xs"></i>
                <span class="text-blue">Penyelesaian Pesanan</span>
            </nav>
            <h1 class="page-title-v6">Checkout<br>Pembayaran</h1>
        </header>

        <div class="row g-lg-5">
            <div class="col-lg-7">
                {{-- STEP 1: ADDRESS --}}
                <article class="checkout-step-card">
                    <header class="step-card-header">
                        <div class="step-number">01</div>
                        <h2 class="step-label">Pilih Lokasi Pengiriman</h2>
                    </header>

                    <div class="address-selection-grid">
                        @foreach($addresses as $addr)
                        <label class="modern-address-item">
                            <input type="radio" name="address_id" class="address-input-hidden" value="{{ $addr->id }}" {{ $loop->first ? 'checked' : '' }} onchange="$('#sel_addr_id').val(this.value)">
                            <div class="address-card-v6">
                                <span class="receiver-name">{{ $addr->nama_penerima }}</span>
                                <span class="text-muted small fw-800 d-block mb-3">+{{ $addr->no_hp }}</span>
                                <p class="small text-muted mb-0">{{ $addr->alamat_lengkap }}</p>
                            </div>
                        </label>
                        @endforeach

                        <button class="btn border-dashed border-2 rounded-4 p-4 d-flex flex-column align-items-center justify-content-center text-muted" style="border-style: dashed !important;" onclick="$('#formAddressModal').modal('show')">
                            <i class="lni lni-plus fs-2 mb-2"></i>
                            <span class="fw-800 small text-uppercase">Tambah Alamat</span>
                        </button>
                    </div>
                </article>

                {{-- STEP 2: PAYMENT --}}
                <article class="checkout-step-card">
                    <header class="step-card-header">
                        <div class="step-number">02</div>
                        <h2 class="step-label">Metode Pembayaran</h2>
                    </header>

                    <div class="payment-premium-box">
                        <div class="midtrans-badge">
                            <img src="https://midtrans.com/assets/img/logo-midtrans-color.png" class="midtrans-logo-v6" alt="Midtrans Official">
                            <div class="flex-grow-1">
                                <h4 class="fw-950 mb-0" style="font-size: 1.1rem; letter-spacing: -0.5px;">Midtrans Secure Gate</h4>
                                <p class="small text-muted mb-0">Pembayaran otomatis & instan melalui multi-channel.</p>
                            </div>
                        </div>

                        <div class="payment-methods-showcase">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/5/5c/Bank_Central_Asia.svg" alt="BCA">
                            <img src="https://upload.wikimedia.org/wikipedia/id/f/fa/Bank_Mandiri_logo.svg" alt="Mandiri">
                            <img src="https://upload.wikimedia.org/wikipedia/id/5/55/BNI_logo.svg" alt="BNI">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Gopay_logo.svg" alt="Gopay">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/7/72/Logo_dana_blue.svg" alt="DANA">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/a/a2/Logo_QRIS.svg" alt="QRIS">
                        </div>
                    </div>
                </article>
            </div>

            {{-- SIDEBAR SUMMARY --}}
            <aside class="col-lg-5">
                <div class="checkout-summary-pro">
                    <h3 class="summary-heading-pro">
                        Ringkasan
                        <span class="opacity-25 fs-5 fw-500">Items</span>
                    </h3>

                    <div class="items-loop-v6">
                        @if($product)
                        <div class="pro-item-v6">
                            <div class="item-icon-v6">
                                <img src="{{ asset('storage/'.$product->image) }}" alt="{{ $product->name }}">
                            </div>
                            <div class="item-info-v6">
                                <span class="name-text-v6">{{ $product->name }}</span>
                                <span class="opacity-50 small fw-800">{{ $quantity }} Units</span>
                            </div>
                            <div class="item-price-v6 fw-950 text-nowrap">Rp {{ number_format($product->price * $quantity, 0, ',', '.') }}</div>
                        </div>
                        @php $totalPay = $product->price * $quantity; @endphp
                        @else
                            @foreach($items as $item)
                            <div class="pro-item-v6">
                                <div class="item-icon-v6">
                                    <img src="{{ asset('storage/'.$item->product->image) }}" alt="{{ $item->product->name }}">
                                </div>
                                <div class="item-info-v6">
                                    <span class="name-text-v6">{{ $item->product->name }}</span>
                                    <span class="opacity-50 small fw-800">{{ $item->jumlah }} Units</span>
                                </div>
                                <div class="item-price-v6 fw-950">Rp {{ number_format($item->harga * $item->jumlah, 0, ',', '.') }}</div>
                            </div>
                            @endforeach
                            @php $totalPay = $items->sum(fn($i) => $i->harga * $i->jumlah); @endphp
                        @endif
                    </div>

                    <div class="summary-total-v6">
                        <span class="small opacity-50 fw-800 text-uppercase letter-spacing-1 d-block mb-1">TOTAL PEMBAYARAN</span>
                        <div class="total-val-v6 mb-5">Rp {{ number_format($totalPay, 0, ',', '.') }}</div>

                        <input type="hidden" id="sel_addr_id" value="{{ $addresses->first()->id ?? '' }}">
                        <input type="hidden" id="c_ids" value="{{ $items ? $items->pluck('id')->join(',') : '' }}">
                        <input type="hidden" id="d_pid" value="{{ $product ? $product->id : '' }}">
                        <input type="hidden" id="d_qty" value="{{ $quantity }}">

                        <button id="btnProPay" onclick="startProPayment()" class="btn-checkout-pro {{ $addresses->isEmpty() ? 'disabled' : '' }}" {{ $addresses->isEmpty() ? 'disabled' : '' }}>
                            BAYAR SEKARANG <i class="lni lni-shield ms-2"></i>
                        </button>
                    </div>

                    <div class="text-center mt-5 opacity-25 small">
                        <i class="lni lni-lock-alt me-1"></i> Transaksi Terenkripsi & Aman
                    </div>
                </div>
            </aside>
        </div>
    </div>
</main>

{{-- MODAL ADD ADDRESS CUSTOM --}}
<div class="modal fade" id="formAddressModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 overflow-hidden" style="border-radius: 30px;">
            <div class="modal-body p-5">
                <h3 class="fw-950 letter-spacing-minus-1 mb-4">Alamat Baru</h3>
                <form id="proAddressForm">
                    @csrf
                    <div class="row g-4">
                        <div class="col-md-6">
                            <label class="small fw-950 text-muted opacity-75 mb-2">PROVINSI</label>
                            <select id="provinsi" name="province_id" class="form-select form-select-lg bg-light border-0 rounded-4" required>
                                <option value="">Pilih Provinsi...</option>
                                @foreach($provinces as $p)
                                    <option value="{{ $p->id }}">{{ $p->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="small fw-950 text-muted opacity-75 mb-2">KOTA / KABUPATEN</label>
                            <select id="kota" name="regency_id" class="form-select form-select-lg bg-light border-0 rounded-4" required disabled></select>
                        </div>
                        <div class="col-md-6">
                            <label class="small fw-950 text-muted opacity-75 mb-2">KECAMATAN</label>
                            <select id="kecamatan" name="district_id" class="form-select form-select-lg bg-light border-0 rounded-4" required disabled></select>
                        </div>
                        <div class="col-md-6">
                            <label class="small fw-950 text-muted opacity-75 mb-2">KELURAHAN / DESA</label>
                            <select id="kelurahan" name="village_id" class="form-select form-select-lg bg-light border-0 rounded-4" required disabled></select>
                        </div>
                        <div class="col-md-6">
                            <label class="small fw-950 text-muted opacity-75 mb-2">PENERIMA</label>
                            <input type="text" name="nama_penerima" class="form-control form-control-lg bg-light border-0 rounded-4" value="{{ auth()->user()->name }}" required>
                        </div>
                        <div class="col-md-6">
                            <label class="small fw-950 text-muted opacity-75 mb-2">WHATSAPP</label>
                            <input type="text" name="nomor_telepon" class="form-control form-control-lg bg-light border-0 rounded-4" value="{{ auth()->user()->phone }}" required>
                        </div>
                        <div class="col-12">
                            <label class="small fw-950 text-muted opacity-75 mb-2">ALAMAT LENGKAP</label>
                            <textarea name="alamat_lengkap" class="form-control form-control-lg bg-light border-0 rounded-4" rows="3" placeholder="Nama Jalan, No. Rumah, RT/RW, dsb" required></textarea>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary w-100 py-4 mt-5 rounded-4 fw-950">SIMPAN ALAMAT</button>
                </form>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="{{ config('services.midtrans.client_key') }}"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    function startProPayment() {
        const addrId = $('#sel_addr_id').val();
        if(!addrId) return Swal.fire({ icon: 'warning', title: 'Alamat Belum Dipilih', text: 'Tentukan lokasi pengiriman Anda.', confirmButtonColor: '#2563eb' });

        const btn = $('#btnProPay');
        const origText = btn.html();
        btn.html('<span class="spinner-border spinner-border-sm me-2"></span>SECURITY CHECK...').prop('disabled', true);

        fetch("{{ route('checkout.store') }}", {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            body: JSON.stringify({
                address_id: addrId,
                cart_item_ids: $('#c_ids').val(),
                direct_product_id: $('#d_pid').val(),
                quantity: $('#d_qty').val()
            })
        })
        .then(r => r.json())
        .then(data => {
            if(data.snap_token) {
                snap.pay(data.snap_token, {
                    onSuccess: function(res) {
                        fetch("/order/update-status/" + data.order_id, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                            body: JSON.stringify({ payment_result: res })
                        }).then(() => window.location.href = data.redirect_url);
                    },
                    onClose: () => { btn.html(origText).prop('disabled', false); }
                });
            }
        });
    }

    $(document).ready(function() {
        // --- INDOREGION LOGIC ---
        function loadWilayah(url, target, nextTargets) {
            $(target).prop('disabled', false).empty().append('<option value="">Memuat data...</option>');
            $.each(nextTargets, function (i, t) { $(t).prop('disabled', true).empty(); });
            $.get(url, function (data) {
                $(target).empty().append('<option value="">Pilih...</option>');
                $.each(data, function (k, v) { $(target).append('<option value="' + v.id + '">' + v.name + '</option>'); });
            });
        }

        $('#provinsi').on('change', function () { loadWilayah('/api/regencies/' + $(this).val(), '#kota', ['#kecamatan', '#kelurahan']); });
        $('#kota').on('change', function () { loadWilayah('/api/districts/' + $(this).val(), '#kecamatan', ['#kelurahan']); });
        $('#kecamatan').on('change', function () { loadWilayah('/api/villages/' + $(this).val(), '#kelurahan', []); });

        $('#proAddressForm').on('submit', function(e) {
            e.preventDefault();
            fetch("{{ route('address.store') }}", { method: 'POST', body: new FormData(this), headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(r => r.json()).then(res => { if(res.success) window.location.reload(); });
        });
    });
</script>
@endsection