<?php
// ============================================================
// FILE: checkout.php â€” Checkout + Midtrans Snap
// Tanpa WA. Alamat terpisah 7 field. Tombol langsung checkout.
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/midtrans.php';
require_once __DIR__ . '/includes/rajaongkir.php';

$pdo = db();
$sid = session_id();

// â”€â”€ Ambil keranjang â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
$stmt = $pdo->prepare("
    SELECT k.id AS kid, k.jumlah,
           p.id AS produk_id, p.nama, p.harga, p.satuan, p.stok, p.berat_per_m,
           (k.jumlah * p.harga) AS subtotal,
           (SELECT nama_file FROM produk_foto WHERE produk_id=p.id ORDER BY urutan ASC LIMIT 1) AS foto
    FROM keranjang k JOIN produk p ON k.produk_id=p.id
    WHERE k.session_id=? ORDER BY k.created_at ASC
");
$stmt->execute([$sid]);
$items = $stmt->fetchAll();

if (empty($items)) {
    setFlash('warning', 'Keranjang kosong.');
    redirect(BASE_URL . '/katalog.php');
}

$grandTotal = array_sum(array_column($items, 'subtotal'));
$beratTotal = hitungBeratKeranjang($items);

// â”€â”€ POST: proses checkout â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
$errors    = [];
$snapToken = null;
$post = [
    'nama'=>'','no_hp'=>'',
    'alamat_jalan'=>'','alamat_rt'=>'','alamat_rw'=>'',
    'alamat_kelurahan'=>'','alamat_kecamatan'=>'',
    'alamat_kota'=>'','alamat_provinsi'=>'','alamat_kodepos'=>'',
    'catatan'=>'',
    'kota_tujuan_id'=>'','kota_tujuan_nama'=>'',
    'kurir'=>'jne','layanan_kurir'=>'','ongkir'=>0,
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach (array_keys($post) as $k) {
        $post[$k] = trim($_POST[$k] ?? '');
    }
    $post['ongkir'] = max(0, (int)($_POST['ongkir'] ?? 0));

    // Validasi
    if (!$post['nama'])          $errors[] = 'Nama lengkap wajib diisi.';
    if (!$post['no_hp'])         $errors[] = 'Nomor HP wajib diisi.';
    if (!$post['alamat_jalan'])  $errors[] = 'Nama jalan / alamat lengkap wajib diisi.';
    if (!$post['alamat_kelurahan']) $errors[] = 'Kelurahan/desa wajib dipilih dari dropdown.';
    if (!$post['alamat_kecamatan']) $errors[] = 'Kecamatan wajib dipilih dari dropdown.';
    if (!$post['alamat_kota'])   $errors[] = 'Kota/kabupaten wajib dipilih dari dropdown.';
    if (!$post['alamat_provinsi']) $errors[] = 'Provinsi wajib dipilih dari dropdown.';
    if (!$post['kota_tujuan_id'])  $errors[] = 'Pilih kota tujuan dan cek ongkir terlebih dahulu.';
    if (!$post['layanan_kurir'])   $errors[] = 'Pilih layanan pengiriman.';

    foreach ($items as $it) {
        if ((float)$it['stok'] <= 0)
            $errors[] = "<strong>{$it['nama']}</strong> stoknya habis.";
        elseif ((float)$it['jumlah'] > (float)$it['stok'])
            $errors[] = "<strong>{$it['nama']}</strong>: stok tersedia hanya "
                       . number_format($it['stok'],2) . ' ' . $it['satuan'] . '.';
    }

    if (empty($errors)) {
        $pdo->beginTransaction();
        try {
            $kode   = generateKodePesanan();
            $userId = $_SESSION['user_id'] ?? null;

            // Gabung alamat lengkap untuk keperluan tampilan
            $alamatLengkap = implode(', ', array_filter([
                $post['alamat_jalan'],
                'RT ' . $post['alamat_rt'] . ' RW ' . $post['alamat_rw'],
                'Kel. ' . $post['alamat_kelurahan'],
                'Kec. ' . $post['alamat_kecamatan'],
                $post['alamat_kota'],
                $post['alamat_provinsi'],
                $post['alamat_kodepos'],
            ]));

            $totalDenganOngkir = $grandTotal + $post['ongkir'];

            $pdo->prepare("
                INSERT INTO pesanan (
                    kode_pesanan, user_id, nama_pembeli, no_hp,
                    alamat_jalan, alamat_rt, alamat_rw, alamat_kelurahan,
                    alamat_kecamatan, alamat_kota, alamat_provinsi, alamat_kodepos,
                    catatan, total_harga, ongkir, kurir, layanan_kurir,
                    kota_tujuan_id, kota_tujuan_nama, status
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'pending')
            ")->execute([
                $kode, $userId, $post['nama'], $post['no_hp'],
                $post['alamat_jalan'], $post['alamat_rt'], $post['alamat_rw'],
                $post['alamat_kelurahan'], $post['alamat_kecamatan'],
                $post['alamat_kota'], $post['alamat_provinsi'], $post['alamat_kodepos'],
                $post['catatan'], $totalDenganOngkir,
                $post['ongkir'], $post['kurir'], $post['layanan_kurir'],
                $post['kota_tujuan_id'], $post['kota_tujuan_nama'],
            ]);
            $pesananId = (int)$pdo->lastInsertId();

            // Insert items + kurangi stok
            $stmtItem = $pdo->prepare("
                INSERT INTO pesanan_item (pesanan_id,produk_id,nama_produk,harga_satuan,jumlah,subtotal)
                VALUES (?,?,?,?,?,?)
            ");
            $stmtStok = $pdo->prepare("UPDATE produk SET stok=stok-? WHERE id=? AND stok>=?");
            foreach ($items as $it) {
                $stmtItem->execute([$pesananId,$it['produk_id'],$it['nama'],$it['harga'],$it['jumlah'],$it['subtotal']]);
                $stmtStok->execute([$it['jumlah'],$it['produk_id'],$it['jumlah']]);
                if ($stmtStok->rowCount() === 0)
                    throw new \RuntimeException("Stok {$it['nama']} tidak mencukupi.");
            }

            // Buat Midtrans Snap Token
            $pesananRow = $pdo->prepare("SELECT * FROM pesanan WHERE id=? LIMIT 1");
            $pesananRow->execute([$pesananId]);
            $pesananRow = $pesananRow->fetch();
            // Inject alamat lengkap sementara untuk Midtrans payload
            $pesananRow['alamat'] = $alamatLengkap;

            $itemsRow = $pdo->prepare("SELECT * FROM pesanan_item WHERE pesanan_id=?");
            $itemsRow->execute([$pesananId]);
            $itemsRow = $itemsRow->fetchAll();

            // Tambah ongkir sebagai item di Midtrans
            if ($post['ongkir'] > 0) {
                $itemsRow[] = [
                    'produk_id'    => 'ONGKIR',
                    'nama_produk'  => 'Ongkos Kirim ' . strtoupper($post['kurir']) . ' ' . $post['layanan_kurir'],
                    'harga_satuan' => $post['ongkir'],
                    'jumlah'       => 1,
                    'subtotal'     => $post['ongkir'],
                ];
            }

            $payload   = midtransBuildPayload($pesananRow, $itemsRow);
            $snapData  = midtransCreateTransaction($payload);
            $snapToken = $snapData['token'];
            $snapOrderId = $payload['transaction_details']['order_id'];

            $pdo->prepare("
                INSERT INTO pembayaran (pesanan_id, midtrans_order_id, midtrans_token, midtrans_status)
                VALUES (?, ?, ?, 'pending')
            ")->execute([$pesananId, $snapOrderId, $snapToken]);

            $pdo->prepare("DELETE FROM keranjang WHERE session_id=?")->execute([$sid]);
            $pdo->commit();
            $_SESSION['last_kode_pesanan'] = $kode;

        } catch (\Exception $ex) {
            $pdo->rollBack();
            $errors[] = 'Gagal memproses: ' . $ex->getMessage();
        }
    }
}

$pageTitle  = 'Checkout';
$activePage = '';
include __DIR__ . '/includes/header.php';
?>

<div class="container py-4">

  <!-- Stepper -->
  <div class="ck-stepper mb-5">
    <div class="ck-step <?= $snapToken ? 'ck-step--done' : 'ck-step--active' ?>">
      <div class="ck-step-bubble"><?= $snapToken ? '<i class="bi bi-check-lg"></i>' : '2' ?></div>
      <div class="ck-step-label">Data Pemesan</div>
    </div>
    <div class="ck-step-line <?= $snapToken ? 'ck-step-line--done' : '' ?>"></div>
    <div class="ck-step <?= $snapToken ? 'ck-step--active' : '' ?>">
      <div class="ck-step-bubble">3</div>
      <div class="ck-step-label">Pembayaran</div>
    </div>
    <div class="ck-step-line"></div>
    <div class="ck-step">
      <div class="ck-step-bubble">4</div>
      <div class="ck-step-label">Selesai</div>
    </div>
  </div>

  <?php if (!empty($errors)): ?>
    <div class="alert alert-danger alert-dismissible fade show mb-4">
      <strong><i class="bi bi-exclamation-triangle-fill me-2"></i>Mohon perbaiki:</strong>
      <ul class="mb-0 mt-1 ps-3">
        <?php foreach ($errors as $e): ?><li><?= $e ?></li><?php endforeach; ?>
      </ul>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <?php if ($snapToken): ?>
  <!-- â”€â”€ Tampilan setelah order dibuat, Snap siap dibuka â”€â”€â”€â”€ -->
  <div class="row justify-content-center">
    <div class="col-lg-6 text-center">
      <div class="ck-snap-ready-card">
        <div class="ck-snap-icon"><i class="bi bi-shield-lock-fill"></i></div>
        <h4 class="fw-bold mb-2">Pesanan Siap Dibayar</h4>
        <p class="text-muted mb-4">
          Kode: <strong class="text-primary"><?= e($_SESSION['last_kode_pesanan'] ?? '') ?></strong><br>
          Pilih metode pembayaran di popup yang akan muncul.
        </p>
        <button class="btn btn-primary-brand btn-lg w-100 mb-3" id="pay-button" onclick="bayarSekarang()">
          <i class="bi bi-lock-fill me-2"></i>Bayar Sekarang
        </button>
        <a href="<?= BASE_URL ?>/tracking.php?kode=<?= urlencode($_SESSION['last_kode_pesanan'] ?? '') ?>"
           class="btn btn-outline-secondary w-100">
          <i class="bi bi-search me-1"></i>Cek Status Pesanan
        </a>
        <div class="ck-pay-methods-preview mt-4">
          <small class="text-muted d-block mb-2">Metode pembayaran yang tersedia:</small>
          <div class="d-flex flex-wrap gap-2 justify-content-center">
            <?php foreach(['BCA','BNI','BRI','GoPay','QRIS','ShopeePay','Visa'] as $m): ?>
              <span class="ck-pay-badge"><?= $m ?></span>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <?php else: ?>
  <!-- â”€â”€ Form Checkout â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ -->
  <form method="POST" id="frmCheckout" novalidate>
    <div class="row g-4">

      <!-- KIRI: Form -->
      <div class="col-lg-7">

        <!-- Data Pemesan -->
        <div class="ck-card mb-4">
          <h5 class="ck-form-title">
            <i class="bi bi-person-fill me-2 text-primary"></i>Data Pemesan
          </h5>
          <div class="row g-3">
            <div class="col-md-6">
              <label class="ck-label" for="iNama">Nama Lengkap <span class="text-danger">*</span></label>
              <input type="text" id="iNama" name="nama" class="form-control ck-input"
                     value="<?= e($post['nama']) ?>" placeholder="Nama sesuai KTP" required autofocus>
            </div>
            <div class="col-md-6">
              <label class="ck-label" for="iHp">Nomor HP <span class="text-danger">*</span></label>
              <input type="tel" id="iHp" name="no_hp" class="form-control ck-input"
                     value="<?= e($post['no_hp']) ?>" placeholder="08xxxxxxxxxx" required>
            </div>
          </div>
        </div>

        <!-- Alamat Pengiriman â€” Dropdown Otomatis -->
        <div class="ck-card mb-4">
          <h5 class="ck-form-title">
            <i class="bi bi-geo-alt-fill me-2 text-danger"></i>Alamat Pengiriman
          </h5>

          <!-- Step indicator -->
          <div class="wilayah-step mb-3">
            <span class="wilayah-step-item" id="ws1"><i class="bi bi-circle me-1"></i>Provinsi</span>
            <span class="wilayah-step-arrow">â€º</span>
            <span class="wilayah-step-item" id="ws2"><i class="bi bi-circle me-1"></i>Kab/Kota</span>
            <span class="wilayah-step-arrow">â€º</span>
            <span class="wilayah-step-item" id="ws3"><i class="bi bi-circle me-1"></i>Kecamatan</span>
            <span class="wilayah-step-arrow">â€º</span>
            <span class="wilayah-step-item" id="ws4"><i class="bi bi-circle me-1"></i>Kelurahan</span>
            <span class="wilayah-step-arrow">â€º</span>
            <span class="wilayah-step-item" id="ws5"><i class="bi bi-circle me-1"></i>Detail</span>
          </div>

          <!-- 1. Provinsi -->
          <div class="mb-3">
            <label class="ck-label" for="wProvinsi">
              Provinsi <span class="text-danger">*</span>
            </label>
            <select id="wProvinsi" class="form-select ck-input"
                    data-value="<?= e($post['alamat_provinsi_id'] ?? '') ?>"
                    onchange="wilayahOnProvinsi(this.value)" required>
              <option value="">Memuat provinsi...</option>
            </select>
          </div>

          <!-- 2. Kabupaten/Kota -->
          <div class="mb-3">
            <label class="ck-label" for="wKabupaten">
              Kabupaten / Kota <span class="text-danger">*</span>
            </label>
            <select id="wKabupaten" class="form-select ck-input" disabled
                    data-value="<?= e($post['alamat_kabupaten_id'] ?? '') ?>"
                    onchange="wilayahOnKabupaten(this.value)" required>
              <option value="">â€” Pilih Provinsi dulu â€”</option>
            </select>
          </div>

          <!-- 3. Kecamatan -->
          <div class="mb-3">
            <label class="ck-label" for="wKecamatan">
              Kecamatan <span class="text-danger">*</span>
            </label>
            <select id="wKecamatan" class="form-select ck-input" disabled
                    data-value="<?= e($post['alamat_kecamatan_id'] ?? '') ?>"
                    onchange="wilayahOnKecamatan(this.value)" required>
              <option value="">â€” Pilih Kab/Kota dulu â€”</option>
            </select>
          </div>

          <!-- 4. Kelurahan/Desa -->
          <div class="mb-3">
            <label class="ck-label" for="wKelurahan">
              Kelurahan / Desa <span class="text-danger">*</span>
            </label>
            <select id="wKelurahan" class="form-select ck-input" disabled
                    data-value="<?= e($post['alamat_kelurahan_id'] ?? '') ?>"
                    onchange="wilayahOnKelurahan(this.value)" required>
              <option value="">â€” Pilih Kecamatan dulu â€”</option>
            </select>
          </div>

          <!-- 5. Detail Jalan -->
          <div class="mb-3">
            <label class="ck-label" for="iJalan">
              Nama Jalan / Gang / Blok / Nomor Rumah
              <span class="text-danger">*</span>
            </label>
            <input type="text" id="iJalan" name="alamat_jalan" class="form-control ck-input"
                   value="<?= e($post['alamat_jalan']) ?>"
                   placeholder="Contoh: Jl. Mawar No. 12 atau Gang Kenanga Blok B3" required>
          </div>

          <!-- 6. RT / RW / Kode Pos -->
          <div class="row g-3 mb-0">
            <div class="col-4">
              <label class="ck-label" for="iRt">RT</label>
              <input type="text" id="iRt" name="alamat_rt" class="form-control ck-input"
                     value="<?= e($post['alamat_rt']) ?>" placeholder="001" maxlength="5">
            </div>
            <div class="col-4">
              <label class="ck-label" for="iRw">RW</label>
              <input type="text" id="iRw" name="alamat_rw" class="form-control ck-input"
                     value="<?= e($post['alamat_rw']) ?>" placeholder="003" maxlength="5">
            </div>
            <div class="col-4">
              <label class="ck-label" for="iKodepos">Kode Pos</label>
              <input type="text" id="iKodepos" name="alamat_kodepos" class="form-control ck-input"
                     value="<?= e($post['alamat_kodepos']) ?>" placeholder="17123" maxlength="10">
            </div>
          </div>

          <!-- Hidden fields â€” nilai teks dikirim ke server -->
          <input type="hidden" name="alamat_provinsi"     id="hProvinsi">
          <input type="hidden" name="alamat_provinsi_id"  id="hProvinsiId">
          <input type="hidden" name="alamat_kota"         id="hKabupaten">
          <input type="hidden" name="alamat_kabupaten_id" id="hKabupatenId">
          <input type="hidden" name="alamat_kecamatan"    id="hKecamatan">
          <input type="hidden" name="alamat_kecamatan_id" id="hKecamatanId">
          <input type="hidden" name="alamat_kelurahan"    id="hKelurahan">
          <input type="hidden" name="alamat_kelurahan_id" id="hKelurahanId">

          <div class="ck-hint mt-2">
            <i class="bi bi-info-circle me-1"></i>
            Pilih dari dropdown secara berurutan. Ongkir otomatis terisi setelah pilih Kab/Kota.
          </div>
        </div>

        <!-- Catatan -->
        <div class="ck-card mb-4">
          <h5 class="ck-form-title">
            <i class="bi bi-chat-left-text me-2"></i>Catatan Tambahan
            <span class="ck-opt ms-1">(opsional)</span>
          </h5>
          <textarea id="iCatatan" name="catatan" class="form-control ck-input" rows="2"
                    placeholder="Catatan ukuran, warna finishing, atau jadwal kirim yang diinginkan..."><?= e($post['catatan']) ?></textarea>
        </div>

        <!-- Ongkir Binderbyte -->
        <div class="ck-card mb-4">
          <h5 class="ck-form-title">
            <i class="bi bi-truck-front-fill me-2 text-primary"></i>Ongkos Kirim
            <span class="badge bg-primary-subtle text-primary border border-primary-subtle ms-2" style="font-size:.7rem">
              Dari <?= KOTA_ASAL_NAMA ?>
            </span>
          </h5>

          <!-- Search lokasi tujuan -->
          <div class="mb-3 position-relative">
            <label class="ck-label">Cari Kota / Kecamatan Tujuan <span class="text-danger">*</span></label>
            <input type="text" id="iSearchLokasi" class="form-control ck-input"
                   placeholder="Ketik nama kota atau kecamatan..." autocomplete="off"
                   oninput="searchLokasi(this.value)">
            <div id="lokasiDropdown" class="ck-lokasi-dropdown d-none"></div>
            <div id="lokasiTerpilih" class="ck-lokasi-terpilih d-none mt-2">
              <i class="bi bi-geo-alt-fill text-success me-1"></i>
              <span id="lokasiTerpilihLabel"></span>
              <button type="button" class="btn btn-sm btn-link text-danger p-0 ms-2"
                      onclick="resetLokasi()">Ganti</button>
            </div>
          </div>

          <div class="row g-2 mb-3">
            <div class="col-md-6">
              <label class="ck-label">Ekspedisi</label>
              <select id="iKurir" class="form-select ck-input" onchange="resetOngkir()">
                <?php foreach (roGetKurirTersedia() as $code => $nama): ?>
                  <option value="<?= $code ?>"><?= $nama ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6 d-flex align-items-end">
              <button type="button" class="btn btn-primary-brand w-100" id="btnCekOngkir"
                      onclick="cekOngkir()" disabled>
                <i class="bi bi-calculator me-1"></i>Cek Ongkir
              </button>
            </div>
          </div>

          <div id="ongkirLoading" class="d-none text-center py-2">
            <span class="spinner-border spinner-border-sm text-primary me-2"></span>
            <small class="text-muted">Menghitung ongkir...</small>
          </div>
          <div id="ongkirError" class="alert alert-danger py-2 small d-none"></div>
          <div id="ongkirHasil" class="d-none">
            <div class="ck-label mb-2">Pilih Layanan Pengiriman:</div>
            <div id="ongkirList" class="d-flex flex-column gap-2"></div>
          </div>

          <input type="hidden" name="kota_tujuan_id"   id="hKotaId">
          <input type="hidden" name="kota_tujuan_nama" id="hKotaNama">
          <input type="hidden" name="kurir"            id="hKurir" value="jne">
          <input type="hidden" name="layanan_kurir"    id="hLayanan">
          <input type="hidden" name="ongkir"           id="hOngkir" value="0">
        </div>

      </div><!-- /col kiri -->

      <!-- KANAN: Ringkasan -->
      <div class="col-lg-5">
        <div class="ck-summary" style="position:sticky;top:90px">
          <h5 class="ck-form-title">
            <i class="bi bi-receipt me-2 text-primary"></i>Ringkasan Pesanan
          </h5>

          <div class="ck-order-items">
            <?php foreach ($items as $it):
              $foto = $it['foto']
                ? UPLOAD_URL.'/produk/'.e($it['foto'])
                : 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=120&q=60';
            ?>
              <div class="ck-oi-row">
                <div class="ck-oi-img">
                  <img src="<?= $foto ?>" alt="<?= e($it['nama']) ?>" loading="lazy">
                  <span class="ck-oi-qty-badge"><?= number_format($it['jumlah'],2) ?></span>
                </div>
                <div class="ck-oi-info">
                  <div class="ck-oi-nama"><?= e($it['nama']) ?></div>
                  <div class="ck-oi-detail">
                    <?= number_format($it['jumlah'],2) ?> <?= e($it['satuan']) ?>
                    &times; <?= formatRupiah($it['harga']) ?>
                  </div>
                </div>
                <div class="ck-oi-sub"><?= formatRupiah($it['subtotal']) ?></div>
              </div>
            <?php endforeach; ?>
          </div>

          <div class="ck-sum-divider mt-3 mb-3"></div>
          <div class="ck-sum-row ck-sum-muted">
            <span>Subtotal Produk</span>
            <span><?= formatRupiah($grandTotal) ?></span>
          </div>
          <div class="ck-sum-row ck-sum-muted">
            <span>Ongkos Kirim</span>
            <span id="sumOngkir" class="fst-italic text-muted">Belum dipilih</span>
          </div>
          <div class="ck-sum-divider mt-3 mb-3"></div>
          <div class="ck-sum-row ck-sum-total">
            <strong>Total Pembayaran</strong>
            <strong class="ck-grand-total" id="sumTotal"><?= formatRupiah($grandTotal) ?></strong>
          </div>

          <!-- Metode bayar -->
          <div class="ck-pay-methods-preview mt-3 mb-4">
            <small class="text-muted d-block mb-2">Metode pembayaran:</small>
            <div class="d-flex flex-wrap gap-1">
              <?php foreach(['BCA VA','BNI VA','BRI VA','GoPay','QRIS','ShopeePay','Kartu Kredit'] as $m): ?>
                <span class="ck-pay-badge"><?= $m ?></span>
              <?php endforeach; ?>
            </div>
          </div>

          <button type="submit" class="btn-ck-primary w-100 mb-3" id="btnSubmit">
            <i class="bi bi-lock-fill me-2"></i>Buat Pesanan & Bayar
          </button>
          <a href="<?= BASE_URL ?>/keranjang.php" class="btn btn-outline-secondary w-100">
            <i class="bi bi-arrow-left me-1"></i>Kembali ke Keranjang
          </a>

          <div class="ck-secure-note mt-3">
            <i class="bi bi-shield-check-fill text-success me-1"></i>
            Pembayaran aman via Midtrans â€” PCI DSS Certified
          </div>
        </div>
      </div>

    </div><!-- /row -->
  </form>
  <?php endif; ?>

</div><!-- /container -->

<style>
.ck-card { background:#fff; border:1.5px solid #EDD9C4; border-radius:16px; padding:1.5rem; }
.ck-snap-ready-card {
  background:#fff; border:1.5px solid #EDD9C4; border-radius:20px; padding:2.5rem;
  text-align:center; box-shadow:0 4px 24px rgba(139,94,60,.1);
}
.ck-snap-icon {
  width:72px;height:72px;background:linear-gradient(135deg,#8B5E3C,#6B4526);
  border-radius:50%;display:inline-flex;align-items:center;justify-content:center;
  font-size:2rem;color:#fff;margin-bottom:1rem;
  box-shadow:0 8px 24px rgba(139,94,60,.3);
}
.ck-secure-note {
  font-size:.78rem;color:#64748B;text-align:center;padding:.5rem;
  background:#F0FFF4;border-radius:8px;
}
</style>

<script>
const BASE    = '<?= BASE_URL ?>';
const BERAT   = <?= $beratTotal ?>;
const SUBTOTAL= <?= $grandTotal ?>;
const fmt = n => 'Rp ' + parseInt(n).toLocaleString('id-ID');

let searchTimeout = null;

function searchLokasi(q) {
  clearTimeout(searchTimeout);
  const dd = document.getElementById('lokasiDropdown');
  if (q.length < 2) { dd.classList.add('d-none'); return; }
  searchTimeout = setTimeout(() => {
    fetch(BASE + '/ongkir.php?action=search&q=' + encodeURIComponent(q))
      .then(r => r.json())
      .then(res => {
        dd.innerHTML = '';
        if (!res.success || !res.data?.length) {
          dd.innerHTML = '<div class="ck-lokasi-item text-muted small p-2">Tidak ditemukan</div>';
        } else {
          res.data.slice(0, 10).forEach(loc => {
            const item = document.createElement('div');
            item.className = 'ck-lokasi-item';
            item.textContent = loc.label;
            item.onclick = () => pilihLokasi(loc.id, loc.label);
            dd.appendChild(item);
          });
        }
        dd.classList.remove('d-none');
      }).catch(() => dd.classList.add('d-none'));
  }, 350);
}

function pilihLokasi(id, label) {
  document.getElementById('hKotaId').value   = id;
  document.getElementById('hKotaNama').value = label;
  document.getElementById('lokasiDropdown').classList.add('d-none');
  document.getElementById('iSearchLokasi').classList.add('d-none');
  document.getElementById('lokasiTerpilih').classList.remove('d-none');
  document.getElementById('lokasiTerpilihLabel').textContent = label;
  document.getElementById('btnCekOngkir').disabled = false;
  resetOngkir();
}

function resetLokasi() {
  document.getElementById('hKotaId').value   = '';
  document.getElementById('hKotaNama').value = '';
  document.getElementById('iSearchLokasi').value = '';
  document.getElementById('iSearchLokasi').classList.remove('d-none');
  document.getElementById('lokasiTerpilih').classList.add('d-none');
  document.getElementById('btnCekOngkir').disabled = true;
  resetOngkir();
}

function resetOngkir() {
  document.getElementById('ongkirHasil').classList.add('d-none');
  document.getElementById('ongkirError').classList.add('d-none');
  document.getElementById('hLayanan').value = '';
  document.getElementById('hOngkir').value  = '0';
  document.getElementById('sumOngkir').textContent = 'Belum dipilih';
  document.getElementById('sumOngkir').className   = 'fst-italic text-muted';
  document.getElementById('sumTotal').textContent  = fmt(SUBTOTAL);
}

function cekOngkir() {
  const destId   = document.getElementById('hKotaId').value;
  const destNama = document.getElementById('hKotaNama').value;
  const kurir    = document.getElementById('iKurir').value;
  if (!destId) { alert('Pilih kota / kecamatan tujuan dulu.'); return; }

  document.getElementById('ongkirLoading').classList.remove('d-none');
  document.getElementById('ongkirHasil').classList.add('d-none');
  document.getElementById('ongkirError').classList.add('d-none');

  const fd = new FormData();
  fd.append('action', 'cek');
  fd.append('destination_id', destId);
  fd.append('berat', BERAT);
  fd.append('kurir', kurir);

  fetch(BASE + '/ongkir.php', {method:'POST', body:fd})
    .then(r => r.json())
    .then(res => {
      document.getElementById('ongkirLoading').classList.add('d-none');
      if (!res.success || !res.services?.length) {
        const el = document.getElementById('ongkirError');
        el.textContent = res.error || 'Tidak ada layanan untuk rute ini.';
        el.classList.remove('d-none'); return;
      }
      document.getElementById('hKurir').value = kurir;
      const list = document.getElementById('ongkirList');
      list.innerHTML = '';
      res.services.forEach((s,i) => {
        const id   = 'svc_'+i;
        const card = document.createElement('label');
        card.className = 'ck-ongkir-card';
        card.setAttribute('for', id);
        card.innerHTML = `
          <input type="radio" id="${id}" name="_svc_radio" class="d-none"
                 onchange="pilihLayanan('${s.service}','${s.cost}','${s.kurir_code}',event)">
          <div class="ck-ongkir-card-inner">
            <div>
              <span class="ck-ongkir-badge">${s.kurir}</span>
              <strong class="ms-2">${s.service}</strong>
              <span class="text-muted small ms-1">— ${s.description}</span>
            </div>
            <div class="text-end">
              <div class="fw-bold text-primary">${fmt(s.cost)}</div>
              <div class="text-muted" style="font-size:.75rem">Est. ${s.etd}</div>
            </div>
          </div>`;
        list.appendChild(card);
      });
      document.getElementById('ongkirHasil').classList.remove('d-none');
    })
    .catch(() => {
      document.getElementById('ongkirLoading').classList.add('d-none');
      document.getElementById('ongkirError').textContent = 'Gagal menghubungi server ongkir.';
      document.getElementById('ongkirError').classList.remove('d-none');
    });
}

function pilihLayanan(service, cost, kurir, e) {
  document.getElementById('hLayanan').value = service;
  document.getElementById('hOngkir').value  = cost;
  document.getElementById('hKurir').value   = kurir;
  document.getElementById('sumOngkir').textContent = fmt(cost);
  document.getElementById('sumOngkir').className   = 'fw-bold text-primary';
  document.getElementById('sumTotal').textContent  = fmt(SUBTOTAL + parseInt(cost));
  document.querySelectorAll('.ck-ongkir-card').forEach(c => c.classList.remove('selected'));
  e.target.closest('.ck-ongkir-card')?.classList.add('selected');
}

document.getElementById('frmCheckout')?.addEventListener('submit', () => {
  const btn = document.getElementById('btnSubmit');
  if (btn) { btn.disabled=true; btn.innerHTML='<span class="spinner-border spinner-border-sm me-2"></span>Memproses...'; }
});
</script>

<?php if ($snapToken): ?>
<script>
function muatSnapJS() {
  return new Promise((resolve, reject) => {
    if (typeof snap !== 'undefined') { resolve(); return; }
    const s = document.createElement('script');
    s.src = '<?= MIDTRANS_SNAP_URL ?>';
    s.setAttribute('data-client-key','<?= MIDTRANS_CLIENT_KEY ?>');
    s.onload = resolve; s.onerror = () => reject(new Error('Gagal memuat snap.js'));
    document.head.appendChild(s);
  });
}
function bayarSekarang() {
  const btn = document.getElementById('pay-button');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Memuat pembayaran...';
  muatSnapJS().then(() => {
    snap.pay('<?= $snapToken ?>', {
      onSuccess: r => location.href = BASE_URL + '/payment_finish.php?order_id=' + r.order_id + '&transaction_status=' + r.transaction_status,
      onPending: r => location.href = BASE_URL + '/payment_finish.php?order_id=' + r.order_id + '&transaction_status=pending',
      onError:   r => { btn.disabled=false; btn.innerHTML='<i class="bi bi-lock-fill me-2"></i>Coba Lagi'; alert('Pembayaran gagal: ' + (r.status_message||'')); },
      onClose:   ()=> { btn.disabled=false; btn.innerHTML='<i class="bi bi-lock-fill me-2"></i>Bayar Sekarang'; }
    });
  }).catch(() => { btn.disabled=false; btn.innerHTML='<i class="bi bi-lock-fill me-2"></i>Bayar Sekarang'; alert('Gagal memuat halaman pembayaran.'); });
}
window.addEventListener('load', () => setTimeout(bayarSekarang, 800));
const BASE_URL = '<?= BASE_URL ?>';
</script>
<?php endif; ?>

<style>
.ck-lokasi-dropdown {
  position:absolute; top:100%; left:0; right:0; z-index:999;
  background:#fff; border:1.5px solid #EDD9C4; border-radius:10px;
  box-shadow:0 4px 16px rgba(0,0,0,.1); max-height:240px; overflow-y:auto;
}
.ck-lokasi-item {
  padding:.5rem .75rem; cursor:pointer; font-size:.9rem; border-bottom:1px solid #f5ede4;
}
.ck-lokasi-item:hover { background:#fdf5ee; }
.ck-lokasi-terpilih { font-size:.9rem; color:#2d7a46; }
</style>

<script>const BASE_URL = '<?= BASE_URL ?>';</script>
<script src="<?= BASE_URL ?>/assets/js/wilayah.js"></script>
<script>
function updateWilayahStep(step) {
  const steps = ['ws1','ws2','ws3','ws4','ws5'];
  steps.forEach((id, i) => {
    const el = document.getElementById(id);
    if (!el) return;
    el.classList.remove('done','active');
    if (i < step - 1)     el.classList.add('done');
    else if (i === step - 1) el.classList.add('active');
  });
}
const _origProv = wilayahOnProvinsi;
window.wilayahOnProvinsi = async function(id, r) { updateWilayahStep(id ? 2 : 1); return _origProv(id, r); };
const _origKab = wilayahOnKabupaten;
window.wilayahOnKabupaten = async function(id, r) { updateWilayahStep(id ? 3 : 2); return _origKab(id, r); };
const _origKec = wilayahOnKecamatan;
window.wilayahOnKecamatan = async function(id, r) { updateWilayahStep(id ? 4 : 3); return _origKec(id, r); };
const _origKel = wilayahOnKelurahan;
window.wilayahOnKelurahan = function(id) { updateWilayahStep(id ? 5 : 4); return _origKel(id); };
</script>
<?php include __DIR__ . '/includes/footer.php'; ?>