<?php
// ============================================================
// FILE: debug_midtrans.php — Test koneksi Midtrans API
// Akses: http://localhost/budijaya_ecommerce/debug_midtrans.php
// HAPUS setelah selesai debug!
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/midtrans.php';

$result = null;
$error  = null;
$raw    = null;
$curlInfo = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Test payload minimal
    $payload = [
        'transaction_details' => [
            'order_id'     => 'TEST-' . time(),
            'gross_amount' => 10000,
        ],
        'item_details' => [[
            'id'       => 'TEST01',
            'price'    => 10000,
            'quantity' => 1,
            'name'     => 'Test Produk',
        ]],
        'customer_details' => [
            'first_name' => 'Test',
            'phone'      => '08123456789',
        ],
        'enabled_payments' => ['gopay', 'qris', 'bca_va'],
        'expiry' => [
            'start_time' => date('Y-m-d H:i:s O'),
            'unit'       => 'hours',
            'duration'   => 1,
        ],
    ];

    // Panggil API secara manual agar bisa tangkap raw response
    $auth = base64_encode(MIDTRANS_SERVER_KEY . ':');
    $ch = curl_init(MIDTRANS_API_URL);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Basic ' . $auth,
        ],
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);

    $raw      = curl_exec($ch);
    $curlErr  = curl_error($ch);
    $curlInfo = curl_getinfo($ch);
    curl_close($ch);

    if ($curlErr) {
        $error = 'cURL Error: ' . $curlErr;
    } else {
        $data = json_decode($raw, true);
        if (!empty($data['token'])) {
            $result = $data;
        } else {
            $error = $data['error_messages'][0]
                  ?? $data['message']
                  ?? 'Unknown error dari Midtrans';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Debug Midtrans</title>
  <style>
    body { font-family: 'Segoe UI', 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; }
    pre { background: #0F172A; padding: 1rem; border-radius: 8px; overflow-x: auto; font-size: .8rem; color: #94A3B8; }
    button { background: #8B5E3C; color: white; border: none; padding: .75rem 2rem; border-radius: 8px; font-size: 1rem; font-weight: 700; cursor: pointer; margin-top: 1rem; }
    button:hover { background: #6B4526; }
    .label { font-size: .75rem; color: #64748B; text-transform: uppercase; letter-spacing: .05em; margin-bottom: .25rem; }
    .val { font-size: .95rem; }
    .warn { background: #451a03; border: 1px solid #92400E; border-radius: 8px; padding: .75rem 1rem; color: #FCD34D; font-size: .82rem; margin-top: 1.5rem; }
  </style>
</head>
<body>
<h2>🔍 Debug Koneksi Midtrans</h2>

<!-- Info Config -->
<div class="card info">
  <div class="label">Konfigurasi Saat Ini</div>
  <div class="val">
    Mode: <strong><?= MIDTRANS_IS_PRODUCTION ? '🔴 PRODUCTION' : '🟢 SANDBOX' ?></strong><br>
    Server Key: <strong><?= substr(MIDTRANS_SERVER_KEY, 0, 20) ?>...</strong><br>
    Client Key: <strong><?= substr(MIDTRANS_CLIENT_KEY, 0, 20) ?>...</strong><br>
    API URL: <strong><?= MIDTRANS_API_URL ?></strong><br>
    cURL tersedia: <strong><?= function_exists('curl_init') ? '✓ Ya' : '✗ Tidak!' ?></strong><br>
    OpenSSL: <strong><?= extension_loaded('openssl') ? '✓ Ya' : '✗ Tidak!' ?></strong>
  </div>
</div>

<?php if ($_SERVER['REQUEST_METHOD'] !== 'POST'): ?>
  <form method="POST">
    <button type="submit">🚀 Test Koneksi ke Midtrans API</button>
  </form>

<?php elseif ($result): ?>
  <!-- SUKSES -->
  <div class="card ok">
    <div class="label">✅ Berhasil! Snap Token didapat</div>
    <div class="val" style="word-break:break-all">
      Token: <strong><?= $result['token'] ?></strong>
    </div>
    <div style="margin-top:.5rem; color:#94A3B8; font-size:.85rem">
      HTTP Status: <?= $curlInfo['http_code'] ?>
    </div>
  </div>

  <div class="card ok">
    <div class="label">✅ Konfigurasi Midtrans BENAR</div>
    <p style="color:#6EE7B7">
      Koneksi ke Midtrans API berhasil. Snap popup seharusnya bisa terbuka.<br><br>
      Kemungkinan Snap tidak muncul karena:<br>
      1. Script Snap JS belum ter-load (cek Console browser)<br>
      2. Popup diblokir browser (cek popup blocker)<br>
      3. Ada error JS di halaman checkout
    </p>
  </div>

  <!-- Test Snap langsung -->
  <div class="card info">
    <div class="label">Test Snap Popup Langsung</div>
    <p style="color:#94A3B8; font-size:.85rem">Klik tombol di bawah untuk test buka Snap dengan token ini:</p>
    <button onclick="testSnap()">💳 Buka Snap Popup</button>
  </div>

  <script src="<?= MIDTRANS_SNAP_URL ?>" data-client-key="<?= MIDTRANS_CLIENT_KEY ?>"></script>
  <script>
  function testSnap() {
    if (typeof snap === 'undefined') {
      alert('ERROR: snap.js gagal dimuat!\nCek Console browser untuk detail.\nKemungkinan masalah CORS atau SSL.');
      return;
    }
    snap.pay('<?= $result['token'] ?>', {
      onSuccess: r => alert('✅ Pembayaran sukses!\n' + JSON.stringify(r, null, 2)),
      onPending: r => alert('⏳ Menunggu pembayaran\n' + JSON.stringify(r, null, 2)),
      onError:   r => alert('❌ Error: ' + JSON.stringify(r, null, 2)),
      onClose:   () => alert('Popup ditutup tanpa bayar'),
    });
  }

  // Auto-test apakah snap.js ter-load
  window.addEventListener('load', () => {
    const status = document.createElement('div');
    status.className = 'card ' + (typeof snap !== 'undefined' ? 'ok' : 'err');
    status.innerHTML = typeof snap !== 'undefined'
      ? '<div class="label">✅ snap.js ter-load dengan benar</div>'
      : '<div class="label">❌ snap.js GAGAL dimuat — ini penyebab Snap tidak muncul!</div><p style="color:#F87171">Cek Console browser. Kemungkinan: koneksi internet mati, atau browser memblokir script dari sandbox.midtrans.com</p>';
    document.body.appendChild(status);
  });
  </script>

<?php else: ?>
  <!-- ERROR -->
  <div class="card err">
    <div class="label">❌ Gagal terhubung ke Midtrans</div>
    <div class="val" style="color:#F87171"><?= htmlspecialchars($error) ?></div>
    <div style="margin-top:.5rem; color:#94A3B8; font-size:.85rem">
      HTTP Status: <?= $curlInfo['http_code'] ?? 'N/A' ?>
    </div>
  </div>

  <?php if ($curlInfo['http_code'] == 401): ?>
    <div class="card err">
      <div class="label">Penyebab: Server Key Salah (HTTP 401)</div>
      <p style="color:#F87171">
        Server Key tidak dikenali Midtrans. Pastikan:<br>
        1. Copy key dari tab <strong>SANDBOX</strong> (bukan Production)<br>
        2. Tidak ada spasi di awal/akhir key<br>
        3. Key diawali <code>SB-Mid-server-</code>
      </p>
    </div>
  <?php elseif ($curlInfo['http_code'] == 0): ?>
    <div class="card err">
      <div class="label">Penyebab: Tidak bisa terhubung ke internet</div>
      <p style="color:#F87171">
        cURL tidak bisa reach Midtrans API. Kemungkinan:<br>
        1. Firewall/antivirus memblokir koneksi keluar dari XAMPP<br>
        2. Tidak ada koneksi internet<br>
        3. SSL certificate bermasalah
      </p>
    </div>
  <?php endif; ?>

  <pre><?= htmlspecialchars($raw ?: '(tidak ada response)') ?></pre>
<?php endif; ?>

<?php if ($curlInfo): ?>
  <div class="card info" style="margin-top:1rem">
    <div class="label">Detail cURL</div>
    <pre><?= htmlspecialchars(json_encode([
      'http_code'    => $curlInfo['http_code'],
      'total_time'   => $curlInfo['total_time'] . 's',
      'url'          => $curlInfo['url'],
      'ssl_verify'   => $curlInfo['ssl_verify_result'],
    ], JSON_PRETTY_PRINT)) ?></pre>
  </div>
<?php endif; ?>

<div class="warn">⚠️ Hapus <code>debug_midtrans.php</code> setelah selesai debug!</div>
</body>
</html>