<?php
// ============================================================
// FILE: debug_rajaongkir.php — Test RajaOngkir + Cari ID Kota
// Akses: http://localhost/budijaya_ecommerce/debug_rajaongkir.php
// HAPUS setelah selesai!
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/rajaongkir.php';

$cities  = [];
$error   = '';
$tested  = false;
$cariQ   = trim($_GET['cari'] ?? '');
$testRes = null;

// ── Test koneksi + ambil semua kota ──────────────────────────
$r = roRequest('city');
if ($r['success']) {
    $cities = $r['data'];
    $tested = true;
} else {
    $error = $r['error'];
    $tested = true;
}

// ── Filter pencarian ──────────────────────────────────────────
$filtered = $cariQ
    ? array_filter($cities, fn($c) =>
        stripos($c['city_name'], $cariQ) !== false ||
        stripos($c['type'],      $cariQ) !== false
      )
    : [];

// ── Test ongkir ke Jakarta (ID 152) untuk verifikasi ─────────
if (isset($_GET['test_ongkir'])) {
    $testRes = roCekOngkir(152, 5000, 'jne');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Debug RajaOngkir</title>
  <style>
    body { font-family:monospace; background:#0F172A; color:#E2E8F0; padding:2rem; }
    h2 { color:#C49A6C; }
    .card { background:#1E293B; border-radius:10px; padding:1.5rem; margin:1rem 0; }
    .ok   { border-left:4px solid #10B981; }
    .err  { border-left:4px solid #EF4444; }
    .info { border-left:4px solid #60A5FA; }
    input[type=text] {
      padding:.6rem 1rem; border-radius:8px; border:none;
      background:#0F172A; color:#E2E8F0; font-size:1rem;
      width:300px; margin-right:.5rem;
    }
    button {
      background:#8B5E3C; color:white; border:none;
      padding:.6rem 1.5rem; border-radius:8px; cursor:pointer; font-size:.9rem;
    }
    table { width:100%; border-collapse:collapse; margin-top:1rem; }
    th { background:#0F172A; padding:.5rem .75rem; text-align:left; color:#C49A6C; font-size:.8rem; }
    td { padding:.4rem .75rem; font-size:.82rem; border-bottom:1px solid #1E293B; }
    tr:hover td { background:rgba(255,255,255,.03); }
    .copy-id {
      background:#8B5E3C; color:white; border:none;
      padding:.15rem .5rem; border-radius:4px; cursor:pointer;
      font-size:.72rem;
    }
    .warn { background:#451a03; border:1px solid #92400E; border-radius:8px;
            padding:.75rem 1rem; color:#FCD34D; font-size:.82rem; margin-top:1.5rem; }
    pre { background:#0F172A; padding:.75rem; border-radius:6px; font-size:.75rem; overflow-x:auto; }
  </style>
</head>
<body>
<h2>🔍 Debug RajaOngkir — Budi Jaya</h2>

<!-- Config -->
<div class="card info">
  <b>Konfigurasi</b><br>
  API Key: <code><?= substr(RAJAONGKIR_API_KEY, 0, 8) ?>...<?= substr(RAJAONGKIR_API_KEY, -6) ?></code><br>
  Plan: <code><?= RAJAONGKIR_PLAN ?></code><br>
  API URL: <code><?= RAJAONGKIR_BASE_URL ?></code><br>
  Kota Asal saat ini: <code><?= KOTA_ASAL_NAMA ?> (ID: <?= KOTA_ASAL_ID ?>)</code>
</div>

<!-- Status koneksi -->
<?php if ($tested): ?>
  <?php if ($error): ?>
    <div class="card err">
      <b>❌ Gagal terhubung ke RajaOngkir</b><br>
      <span style="color:#F87171"><?= htmlspecialchars($error) ?></span>
    </div>
  <?php else: ?>
    <div class="card ok">
      <b>✅ Koneksi OK — <?= count($cities) ?> kota ditemukan</b>
    </div>
  <?php endif; ?>
<?php endif; ?>

<?php if (!$error && !empty($cities)): ?>

<!-- Cari kota -->
<div class="card info">
  <b>🔎 Cari ID Kota Toko Anda</b>
  <p style="color:#94A3B8;font-size:.85rem;margin:.5rem 0 1rem">
    Ketik nama kota toko (misal: Bekasi, Jakarta, Surabaya) untuk cari ID-nya.
  </p>
  <form method="GET">
    <input type="text" name="cari" value="<?= htmlspecialchars($cariQ) ?>"
           placeholder="Ketik nama kota...">
    <button type="submit">Cari</button>
    <?php if ($cariQ): ?>
      <a href="?" style="color:#94A3B8;margin-left:.75rem;font-size:.85rem">Reset</a>
    <?php endif; ?>
  </form>

  <?php if ($cariQ && empty($filtered)): ?>
    <p style="color:#F87171;margin-top:1rem">Tidak ditemukan kota "<b><?= htmlspecialchars($cariQ) ?></b>"</p>
  <?php endif; ?>

  <?php if (!empty($filtered)): ?>
    <table>
      <tr>
        <th>ID Kota</th>
        <th>Tipe</th>
        <th>Nama Kota</th>
        <th>Provinsi</th>
        <th>Aksi</th>
      </tr>
      <?php foreach ($filtered as $ct): ?>
        <tr>
          <td><code style="color:#D4A853;font-size:1rem"><?= $ct['city_id'] ?></code></td>
          <td><?= $ct['type'] ?></td>
          <td><b><?= htmlspecialchars($ct['city_name']) ?></b></td>
          <td><?= htmlspecialchars($ct['province'] ?? '') ?></td>
          <td>
            <button class="copy-id" onclick="
              navigator.clipboard.writeText('<?= $ct['city_id'] ?>');
              this.textContent='✓ Disalin!';
              setTimeout(()=>this.textContent='Copy ID',1500)
            ">Copy ID</button>
          </td>
        </tr>
      <?php endforeach; ?>
    </table>

    <!-- Panduan set config -->
    <?php $first = reset($filtered); ?>
    <div style="margin-top:1rem;padding:1rem;background:#0F172A;border-radius:8px">
      <p style="color:#C49A6C;margin:0 0 .5rem;font-size:.85rem">
        Setelah dapat ID, update di <code>includes/config.php</code>:
      </p>
      <pre>define('KOTA_ASAL_ID',   '<?= $first['city_id'] ?>');   // <?= $first['type'].' '.$first['city_name'] ?>

define('KOTA_ASAL_NAMA', '<?= $first['city_name'] ?>');</pre>
    </div>
  <?php endif; ?>
</div>

<!-- Test ongkir -->
<div class="card info">
  <b>🚚 Test Ongkir (dari kota asal ke Jakarta)</b>
  <p style="color:#94A3B8;font-size:.85rem;margin:.5rem 0 1rem">
    Test kirim 5kg JNE ke Jakarta Pusat (ID 152).
  </p>
  <a href="?cari=<?= urlencode($cariQ) ?>&test_ongkir=1">
    <button type="button">Test Ongkir Sekarang</button>
  </a>
  <?php if ($testRes): ?>
    <div style="margin-top:1rem">
      <?php if ($testRes['success'] && !empty($testRes['services'])): ?>
        <div style="color:#10B981;margin-bottom:.5rem">✅ Berhasil! RajaOngkir berfungsi normal.</div>
        <table>
          <tr><th>Layanan</th><th>Harga</th><th>Estimasi</th></tr>
          <?php foreach ($testRes['services'] as $s): ?>
            <tr>
              <td><?= $s['kurir'] ?> <?= $s['service'] ?></td>
              <td>Rp <?= number_format($s['cost'],0,',','.') ?></td>
              <td><?= $s['etd'] ?></td>
            </tr>
          <?php endforeach; ?>
        </table>
      <?php else: ?>
        <div style="color:#F87171">❌ <?= htmlspecialchars($testRes['error']) ?></div>
        <p style="color:#94A3B8;font-size:.8rem">
          Kemungkinan: ID kota asal (<?= KOTA_ASAL_ID ?>) belum benar. Cari ID yang tepat di atas.
        </p>
      <?php endif; ?>
    </div>
  <?php endif; ?>
</div>

<?php endif; ?>

<div class="warn">⚠️ Hapus <code>debug_rajaongkir.php</code> dari server setelah selesai!</div>
</body>
</html>