<?php
// ============================================================
// FILE: payment_finish.php — Halaman Return dari Midtrans Snap
// Dipanggil setelah user selesai/tutup halaman pembayaran Snap.
// Midtrans mengirim: order_id, transaction_status via GET.
// Status FINAL tetap dari webhook (midtrans_notification.php).
// ============================================================
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();

$orderId           = trim($_GET['order_id']           ?? '');
$transactionStatus = trim($_GET['transaction_status'] ?? '');

// Cari pesanan berdasarkan midtrans_order_id
$stmt = $pdo->prepare("
    SELECT p.*, pay.midtrans_order_id, pay.midtrans_status, pay.payment_type
    FROM pembayaran pay
    JOIN pesanan p ON p.id = pay.pesanan_id
    WHERE pay.midtrans_order_id = ?
    LIMIT 1
");
$stmt->execute([$orderId]);
$pesanan = $stmt->fetch();

// Jika order_id tidak ditemukan, coba dari session
if (!$pesanan) {
    $kodeSession = $_SESSION['last_kode_pesanan'] ?? '';
    if ($kodeSession) {
        $stmt2 = $pdo->prepare("
            SELECT p.*, pay.midtrans_order_id, pay.midtrans_status, pay.payment_type
            FROM pesanan p
            LEFT JOIN pembayaran pay ON pay.pesanan_id = p.id
            WHERE p.kode_pesanan = ? LIMIT 1
        ");
        $stmt2->execute([$kodeSession]);
        $pesanan = $stmt2->fetch();
    }
}

// Tentukan tampilan berdasarkan status
$statusType = 'pending'; // pending | success | error
if ($transactionStatus === 'settlement' || $transactionStatus === 'capture') {
    $statusType = 'success';
} elseif (in_array($transactionStatus, ['deny', 'cancel', 'expire', 'failure'])) {
    $statusType = 'error';
}

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

<div class="container py-5">
  <div class="row justify-content-center">
    <div class="col-lg-6">

      <?php if ($statusType === 'success'): ?>
      <!-- ══ SUKSES ══════════════════════════════════════════ -->
      <div class="pf-card text-center">
        <div class="pf-icon pf-icon--success mx-auto mb-4">
          <i class="bi bi-check-circle-fill"></i>
        </div>
        <h3 class="fw-bold mb-1">Pembayaran Berhasil! 🎉</h3>
        <p class="text-muted mb-4">Terima kasih! Pesanan Anda sudah kami terima dan sedang diproses.</p>

        <?php if ($pesanan): ?>
          <div class="pf-detail mb-4">
            <div class="pf-detail-row">
              <span>Kode Pesanan</span>
              <strong><code><?= e($pesanan['kode_pesanan']) ?></code></strong>
            </div>
            <div class="pf-detail-row">
              <span>Total Dibayar</span>
              <strong class="text-success"><?= formatRupiah($pesanan['total_harga']) ?></strong>
            </div>
            <?php if ($pesanan['payment_type']): ?>
            <div class="pf-detail-row">
              <span>Metode</span>
              <strong><?= e(str_replace('_', ' ', strtoupper($pesanan['payment_type']))) ?></strong>
            </div>
            <?php endif; ?>
          </div>
        <?php endif; ?>

        <div class="d-grid gap-2">
          <a href="<?= BASE_URL ?>/tracking.php<?= $pesanan ? '?kode='.urlencode($pesanan['kode_pesanan']) : '' ?>"
             class="btn btn-primary-brand btn-lg">
            <i class="bi bi-search me-2"></i>Pantau Status Pesanan
          </a>
          <a href="<?= BASE_URL ?>" class="btn btn-outline-secondary">
            <i class="bi bi-house me-2"></i>Kembali ke Beranda
          </a>
        </div>

        <div class="mt-4 p-3 bg-light rounded text-start">
          <p class="small mb-1"><i class="bi bi-clock text-primary me-2"></i>
            Tim kami akan memproses pesanan Anda segera.
          </p>
          <p class="small mb-0"><i class="bi bi-clock text-primary me-2"></i>
            Estimasi proses pesanan: 1–2 hari kerja.
          </p>
        </div>
      </div>

      <?php elseif ($statusType === 'error'): ?>
      <!-- ══ GAGAL ════════════════════════════════════════════ -->
      <div class="pf-card text-center">
        <div class="pf-icon pf-icon--error mx-auto mb-4">
          <i class="bi bi-x-circle-fill"></i>
        </div>
        <h3 class="fw-bold mb-1">Pembayaran Gagal</h3>
        <p class="text-muted mb-4">
          Pembayaran Anda <?= $transactionStatus === 'expire' ? 'sudah kadaluarsa' : 'dibatalkan atau ditolak' ?>.
          Pesanan belum diproses.
        </p>

        <?php if ($pesanan): ?>
          <div class="pf-detail mb-4">
            <div class="pf-detail-row">
              <span>Kode Pesanan</span>
              <code><?= e($pesanan['kode_pesanan']) ?></code>
            </div>
          </div>
          <p class="small text-muted">
            Pesanan tetap tersimpan. Anda bisa coba bayar lagi atau hubungi kami.
          </p>
        <?php endif; ?>

        <div class="d-grid gap-2">
          <?php if ($pesanan): ?>
            <a href="<?= BASE_URL ?>/tracking.php?kode=<?= urlencode($pesanan['kode_pesanan']) ?>"
               class="btn btn-primary-brand btn-lg">
              <i class="bi bi-arrow-clockwise me-2"></i>Coba Bayar Lagi
            </a>
          <?php endif; ?>
          <a href="<?= BASE_URL ?>/chat.php?kode=<?= $pesanan ? urlencode($pesanan['kode_pesanan']) : '' ?>"
             class="btn btn-outline-primary">
            <i class="bi bi-chat-dots me-2"></i>Hubungi Kami
          </a>
          <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-outline-secondary">
            Kembali Belanja
          </a>
        </div>
      </div>

      <?php else: ?>
      <!-- ══ PENDING ══════════════════════════════════════════ -->
      <div class="pf-card text-center">
        <div class="pf-icon pf-icon--pending mx-auto mb-4">
          <i class="bi bi-hourglass-split"></i>
        </div>
        <h3 class="fw-bold mb-1">Menunggu Pembayaran</h3>
        <p class="text-muted mb-4">
          Pesanan Anda sudah dibuat. Selesaikan pembayaran sesuai instruksi yang dikirim
          (Virtual Account / QRIS / e-wallet).
        </p>

        <?php if ($pesanan): ?>
          <div class="pf-detail mb-4">
            <div class="pf-detail-row">
              <span>Kode Pesanan</span>
              <strong><code><?= e($pesanan['kode_pesanan']) ?></code></strong>
            </div>
            <div class="pf-detail-row">
              <span>Total Tagihan</span>
              <strong><?= formatRupiah($pesanan['total_harga']) ?></strong>
            </div>
            <div class="pf-detail-row">
              <span>Batas Waktu</span>
              <strong class="text-warning">24 jam</strong>
            </div>
          </div>
        <?php endif; ?>

        <div class="alert alert-warning text-start small mb-4">
          <i class="bi bi-info-circle me-2"></i>
          Jika sudah membayar via Virtual Account atau QRIS, status akan <strong>otomatis diperbarui</strong>
          dalam beberapa menit. Tidak perlu konfirmasi manual.
        </div>

        <div class="d-grid gap-2">
          <a href="<?= BASE_URL ?>/tracking.php<?= $pesanan ? '?kode='.urlencode($pesanan['kode_pesanan']) : '' ?>"
             class="btn btn-primary-brand btn-lg">
            <i class="bi bi-search me-2"></i>Pantau Status Pesanan
          </a>
          <a href="<?= BASE_URL ?>" class="btn btn-outline-secondary">
            Kembali ke Beranda
          </a>
        </div>
      </div>
      <?php endif; ?>

    </div>
  </div>
</div>

<style>
.pf-card {
  background: white;
  border-radius: 20px;
  padding: 2.5rem 2rem;
  box-shadow: 0 4px 32px rgba(139,94,60,.12);
  border: 1px solid rgba(212,168,83,.2);
}
.pf-icon {
  width: 80px; height: 80px;
  border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  font-size: 2.5rem;
}
.pf-icon--success { background: #DCFCE7; color: #16A34A; }
.pf-icon--error   { background: #FEE2E2; color: #DC2626; }
.pf-icon--pending { background: #FEF9C3; color: #D97706; }
.pf-detail {
  background: #F8F5F0;
  border-radius: 12px;
  padding: 1rem;
  text-align: left;
}
.pf-detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: .4rem 0;
  border-bottom: 1px solid #EDD9C4;
  font-size: .9rem;
}
.pf-detail-row:last-child { border-bottom: none; }
.pf-detail-row span { color: #92756A; }
</style>

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