<?php
// ============================================================
// FILE: tracking.php — Lacak Status Pesanan
// Alur pembayaran: via Midtrans (otomatis, tanpa upload manual)
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

$pdo     = db();
$pesanan = null;
$items   = [];
$bayar   = null;

$kode = trim($_GET['kode'] ?? $_POST['kode'] ?? '');
$hp   = trim($_GET['hp']   ?? $_POST['hp']   ?? '');

if ($kode || $hp) {
    if ($kode) {
        $stmt = $pdo->prepare("SELECT * FROM pesanan WHERE kode_pesanan=? LIMIT 1");
        $stmt->execute([$kode]);
    } else {
        $stmt = $pdo->prepare("SELECT * FROM pesanan WHERE no_hp=? ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$hp]);
    }
    $pesanan = $stmt->fetch();

    if ($pesanan) {
        $si = $pdo->prepare("SELECT * FROM pesanan_item WHERE pesanan_id=? ORDER BY id ASC");
        $si->execute([$pesanan['id']]);
        $items = $si->fetchAll();

        $sb = $pdo->prepare("SELECT * FROM pembayaran WHERE pesanan_id=? LIMIT 1");
        $sb->execute([$pesanan['id']]);
        $bayar = $sb->fetch();
    }
}

// Langkah tracking — disesuaikan alur Midtrans (tidak ada "upload bukti")
$langkahDef = [
    'pending'      => ['ikon' => 'clock-history',       'label' => 'Menunggu Pembayaran',     'urutan' => 0],
    'dibayar'      => ['ikon' => 'hourglass-split',     'label' => 'Pembayaran Diproses',     'urutan' => 1],
    'diverifikasi' => ['ikon' => 'check-circle-fill',   'label' => 'Pembayaran Dikonfirmasi', 'urutan' => 2],
    'diproses'     => ['ikon' => 'gear-wide-connected', 'label' => 'Pesanan Disiapkan',       'urutan' => 3],
    'selesai'      => ['ikon' => 'house-check-fill',    'label' => 'Selesai & Diterima',      'urutan' => 4],
];

$statusPesanan  = $pesanan['status'] ?? 'pending';
$currentUrutan  = $langkahDef[$statusPesanan]['urutan'] ?? 0;
$isBatalkan     = $statusPesanan === 'dibatalkan';

// Metode pembayaran yang ditampilkan
$paymentTypeLabel = '';
if ($bayar && $bayar['payment_type']) {
    $map = [
        'bca_va' => 'Virtual Account BCA', 'bni_va' => 'Virtual Account BNI',
        'bri_va' => 'Virtual Account BRI', 'permata_va' => 'Virtual Account Permata',
        'other_va' => 'Virtual Account', 'gopay' => 'GoPay',
        'shopeepay' => 'ShopeePay', 'qris' => 'QRIS',
        'credit_card' => 'Kartu Kredit',
    ];
    $paymentTypeLabel = $map[$bayar['payment_type']] ?? strtoupper(str_replace('_', ' ', $bayar['payment_type']));
}

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

<div class="container py-5">

  <!-- Hero -->
  <div class="text-center mb-5">
    <div class="trk-hero-icon"><i class="bi bi-search"></i></div>
    <h2 class="section-title mt-3 mb-2">Lacak Pesanan Anda</h2>
    <p class="text-muted">Masukkan kode pesanan atau nomor HP untuk melihat status terkini.</p>
  </div>

  <!-- Form pencarian -->
  <div class="row justify-content-center mb-5">
    <div class="col-lg-5 col-md-7">
      <div class="trk-search-card">
        <form method="GET" id="frmCari">
          <div class="mb-3">
            <label class="ck-label" for="iKode">
              <i class="bi bi-receipt me-1 text-primary"></i>Kode Pesanan
            </label>
            <input type="text" id="iKode" name="kode" class="form-control ck-input"
                   placeholder="BJ-20250628-0001" value="<?= e($kode) ?>">
          </div>
          <div class="trk-or">— atau —</div>
          <div class="mb-4">
            <label class="ck-label" for="iHP">
              <i class="bi bi-telephone me-1 text-primary"></i>Nomor HP
            </label>
            <input type="tel" id="iHP" name="hp" class="form-control ck-input"
                   placeholder="Nomor HP yang dipakai saat checkout" value="<?= e($hp) ?>">
          </div>
          <button type="submit" class="btn-ck-primary w-100">
            <i class="bi bi-search me-2"></i>Cari Pesanan
          </button>
        </form>
      </div>
    </div>
  </div>

  <!-- Hasil -->
  <?php if (($kode || $hp) && !$pesanan): ?>
    <div class="trk-not-found">
      <div class="trk-nf-icon"><i class="bi bi-inbox"></i></div>
      <h5>Pesanan Tidak Ditemukan</h5>
      <p class="text-muted">Cek kembali kode pesanan atau nomor HP Anda.</p>
    </div>

  <?php elseif ($pesanan): ?>
    <div class="row justify-content-center">
      <div class="col-lg-9">

        <!-- Header ringkas -->
        <div class="trk-header-card mb-4">
          <div>
            <div class="small text-muted mb-1">Kode Pesanan</div>
            <h4 class="font-monospace mb-1"><?= e($pesanan['kode_pesanan']) ?></h4>
            <div class="small text-muted">
              <?= date('d M Y, H:i', strtotime($pesanan['created_at'])) ?> WIB
            </div>
          </div>
          <div class="text-end">
            <?= statusBadge($pesanan['status']) ?>
            <div class="fw-bold fs-5 mt-1"><?= formatRupiah($pesanan['total_harga']) ?></div>
            <div class="small text-muted"><?= e($pesanan['nama_pembeli']) ?></div>
          </div>
        </div>

        <!-- Progress tracking -->
        <?php if (!$isBatalkan): ?>
          <div class="trk-progress-card mb-4">
            <div class="trk-steps">
              <?php foreach ($langkahDef as $status => $info):
                $urutan    = $info['urutan'];
                $isDone    = $urutan < $currentUrutan;
                $isCurrent = $urutan === $currentUrutan;
              ?>
                <div class="trk-step <?= $isDone ? 'trk-step--done' : ($isCurrent ? 'trk-step--current' : 'trk-step--future') ?>">
                  <div class="trk-bubble">
                    <?php if ($isDone): ?>
                      <i class="bi bi-check-lg"></i>
                    <?php else: ?>
                      <i class="bi bi-<?= $info['ikon'] ?>"></i>
                    <?php endif; ?>
                  </div>
                  <div class="trk-lbl"><?= $info['label'] ?></div>
                  <?php if ($isCurrent): ?>
                    <div class="trk-current-tag">Saat Ini</div>
                  <?php endif; ?>
                </div>
                <?php if ($urutan < 4): ?>
                  <div class="trk-line <?= $isDone ? 'trk-line--done' : '' ?>"></div>
                <?php endif; ?>
              <?php endforeach; ?>
            </div>
          </div>

          <!-- Panduan sesuai status -->
          <div class="trk-action-card mb-4">
            <?php if ($statusPesanan === 'pending'): ?>
              <div class="trk-action-icon trk-action-icon--warning">
                <i class="bi bi-credit-card-2-front-fill"></i>
              </div>
              <div class="flex-grow-1">
                <h6 class="mb-1">Menunggu Pembayaran</h6>
                <p class="small text-muted mb-3">
                  Pesanan sudah dibuat. Klik tombol di bawah untuk melanjutkan pembayaran
                  via Midtrans (VA Bank, QRIS, GoPay, dll).
                </p>
                <?php if ($bayar && $bayar['midtrans_token']): ?>
                  <!-- Snap token masih ada, bisa re-open -->
                  <button class="btn btn-warning btn-sm fw-bold" onclick="bukaPembayaran()">
                    <i class="bi bi-credit-card me-1"></i>Lanjutkan Pembayaran
                  </button>
                <?php else: ?>
                  <a href="<?= BASE_URL ?>/chat.php?kode=<?= urlencode($pesanan['kode_pesanan']) ?>"
                     class="btn btn-primary btn-sm">
                    <i class="bi bi-chat-dots me-1"></i>Hubungi Kami
                  </a>
                <?php endif; ?>
              </div>

            <?php elseif ($statusPesanan === 'dibayar'): ?>
              <div class="trk-action-icon trk-action-icon--info">
                <i class="bi bi-hourglass-split"></i>
              </div>
              <div>
                <h6 class="mb-1">Pembayaran Sedang Dikonfirmasi</h6>
                <p class="small text-muted mb-0">
                  Pembayaran Anda sedang diverifikasi oleh sistem Midtrans.
                  Status akan diperbarui otomatis dalam beberapa menit.
                </p>
              </div>

            <?php elseif ($statusPesanan === 'diverifikasi'): ?>
              <div class="trk-action-icon trk-action-icon--primary">
                <i class="bi bi-check-circle-fill"></i>
              </div>
              <div>
                <h6 class="mb-1">Pembayaran Dikonfirmasi ✓</h6>
                <p class="small text-muted mb-0">
                  Pembayaran diterima. Pesanan Anda sedang disiapkan oleh tim kami.
                  <?php if ($paymentTypeLabel): ?>
                    <span class="badge bg-primary-subtle text-primary border border-primary-subtle ms-1"><?= e($paymentTypeLabel) ?></span>
                  <?php endif; ?>
                </p>
              </div>

            <?php elseif ($statusPesanan === 'diproses'): ?>
              <div class="trk-action-icon trk-action-icon--secondary">
                <i class="bi bi-gear-wide-connected"></i>
              </div>
              <div>
                <h6 class="mb-1">Pesanan Sedang Disiapkan</h6>
                <p class="small text-muted mb-0">
                  Produk sedang disiapkan untuk pengiriman.
                  Tim kami akan menghubungi Anda untuk jadwal kirim.
                </p>
              </div>

            <?php elseif ($statusPesanan === 'selesai'): ?>
              <div class="trk-action-icon trk-action-icon--success">
                <i class="bi bi-house-check-fill"></i>
              </div>
              <div>
                <h6 class="mb-1">Pesanan Selesai! 🎉</h6>
                <p class="small text-muted mb-2">
                  Terima kasih telah berbelanja di Budi Jaya. Semoga memuaskan!
                </p>
                <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-primary btn-sm">
                  <i class="bi bi-shop me-1"></i>Belanja Lagi
                </a>
              </div>
            <?php endif; ?>
          </div>

        <?php else: ?>
          <!-- Dibatalkan -->
          <div class="alert alert-danger d-flex align-items-start gap-3 mb-4">
            <i class="bi bi-x-circle-fill fs-3 flex-shrink-0 mt-1"></i>
            <div>
              <h6 class="mb-1">Pesanan Dibatalkan</h6>
              <p class="mb-2 small">
                <?= $pesanan['catatan_admin']
                    ? e($pesanan['catatan_admin'])
                    : 'Pesanan dibatalkan karena pembayaran tidak diselesaikan dalam 24 jam.' ?>
              </p>
              <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-outline-danger btn-sm">
                <i class="bi bi-arrow-repeat me-1"></i>Buat Pesanan Baru
              </a>
            </div>
          </div>
        <?php endif; ?>

        <!-- Info pembayaran Midtrans (ringkas, tanpa upload) -->
        <?php if ($bayar && $bayar['midtrans_status']): ?>
          <div class="trk-bukti-card mb-4">
            <div class="trk-bukti-head">
              <i class="bi bi-shield-check me-2 text-success"></i>Informasi Pembayaran
              <?php if ($bayar['diverifikasi']): ?>
                <span class="badge bg-success ms-2">Terverifikasi</span>
              <?php else: ?>
                <span class="badge bg-warning text-dark ms-2">
                  <?= ucfirst($bayar['midtrans_status']) ?>
                </span>
              <?php endif; ?>
            </div>
            <div class="trk-bukti-body">
              <div class="trk-bukti-info w-100">
                <?php if ($paymentTypeLabel): ?>
                  <div class="d-flex justify-content-between py-1 border-bottom">
                    <span class="text-muted">Metode Bayar</span>
                    <strong><?= e($paymentTypeLabel) ?></strong>
                  </div>
                <?php endif; ?>
                <div class="d-flex justify-content-between py-1 border-bottom">
                  <span class="text-muted">Total Bayar</span>
                  <strong class="text-success"><?= formatRupiah($pesanan['total_harga']) ?></strong>
                </div>
                <?php if ($bayar['verified_at']): ?>
                  <div class="d-flex justify-content-between py-1">
                    <span class="text-muted">Dikonfirmasi</span>
                    <strong><?= date('d M Y, H:i', strtotime($bayar['verified_at'])) ?> WIB</strong>
                  </div>
                <?php endif; ?>
              </div>
            </div>
          </div>
        <?php endif; ?>

        <!-- Detail item pesanan -->
        <div class="trk-items-card mb-4">
          <div class="trk-items-head">
            <i class="bi bi-box-seam me-2"></i>Item yang Dipesan
          </div>
          <div class="trk-items-body">
            <?php foreach ($items as $it): ?>
              <div class="trk-item-row">
                <div class="trk-item-info">
                  <div class="fw-semibold"><?= e($it['nama_produk']) ?></div>
                  <div class="small text-muted">
                    <?= number_format($it['jumlah'], 2) ?> × <?= formatRupiah($it['harga_satuan']) ?>
                  </div>
                </div>
                <div class="fw-bold"><?= formatRupiah($it['subtotal']) ?></div>
              </div>
            <?php endforeach; ?>
            <div class="trk-item-total">
              <span>Total Produk</span>
              <span class="text-primary fw-bold fs-5"><?= formatRupiah($pesanan['total_harga']) ?></span>
            </div>
          </div>
        </div>

        <!-- Tombol kontak -->
        <div class="text-center">
          <p class="text-muted small mb-3">Ada pertanyaan tentang pesanan ini?</p>
          <a href="<?= BASE_URL ?>/chat.php?kode=<?= urlencode($pesanan['kode_pesanan']) ?>"
             class="btn btn-primary">
            <i class="bi bi-chat-dots me-2"></i>Chat dengan Admin
          </a>
        </div>

      </div>
    </div>
  <?php endif; ?>

</div>

<?php
// Jika ada token Midtrans tersimpan, siapkan re-open Snap
$snapToken = $bayar['midtrans_token'] ?? '';
if ($snapToken && $statusPesanan === 'pending'):
?>
<script src="<?= MIDTRANS_SNAP_URL ?>" data-client-key="<?= MIDTRANS_CLIENT_KEY ?>"></script>
<script>
function bukaPembayaran() {
  snap.pay('<?= e($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:   () => alert('Pembayaran gagal, silakan coba lagi.'),
    onClose:   () => {}
  });
}
</script>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>