<?php
// Ambil order_id dan method dari query string
$order_id = isset($_GET['order_id']) ? htmlspecialchars($_GET['order_id']) : '';
$method = isset($_GET['method']) ? htmlspecialchars($_GET['method']) : '';

// Data rekening/VA
$dana_number = '085956631642';
//$dana_name = 'Nama Anda'; // tidak perlu lagi
$mandiri_number = '1670007936411';
//$mandiri_name = 'Nama Anda'; // tidak perlu lagi

$payment_info = '';
if ($method === 'dana') {
    $payment_info = "<b>Transfer ke DANA:</b><br>Nomor: <span class='font-mono'>$dana_number</span>";
} elseif ($method === 'mandiri') {
    $payment_info = "<b>Transfer ke Mandiri:</b><br>Nomor Rekening: <span class='font-mono'>$mandiri_number</span>";
} else {
    $payment_info = 'Metode pembayaran tidak valid.';
}

// Cek expired dari database
require_once __DIR__ . '/../models/Order.php';
$orderObj = new Order();
$is_expired = false;
if ($order_id && $orderObj->getOrderByOrderCode($order_id)) {
    $expire_minutes = 1;
    $created_at = strtotime($orderObj->created_at);
    if (time() - $created_at > $expire_minutes * 60 && $orderObj->status === 'pending') {
        $orderObj->updateStatus('expired');
        $is_expired = true;
    } elseif ($orderObj->status === 'expired') {
        $is_expired = true;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instruksi Pembayaran</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-light d-flex flex-column min-vh-100">
  <!-- Navbar sederhana dengan badge keranjang -->
  <nav class="navbar navbar-expand-lg navbar-light bg-white shadow sticky-top px-4 py-3">
    <div class="container-fluid">
      <a class="navbar-brand fw-bold text-success" href="#">Baso Alam</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ms-auto mb-2 mb-lg-0 gap-2 align-items-lg-center">
          <li class="nav-item"><a href="dashboard.php" class="nav-link">Home</a></li>
          <li class="nav-item"><a href="cek_transaction.php" class="nav-link">Transaksi</a></li>
          <li class="nav-item"><a href="tentang_kami.php" class="nav-link">Tentang Kami</a></li>
          <li class="nav-item"><a href="https://wa.me/6285956631642" target="_blank" rel="noopener" class="nav-link d-flex align-items-center gap-1"><i class="fab fa-whatsapp"></i> Kontak Kami</a></li>
          <li class="nav-item position-relative">
            <a href="cart.php" class="nav-link"><i class="fas fa-shopping-cart"></i><span id="cart-count" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">0</span></a>
          </li>
        </ul>
    </div>
    </div>
  </nav>
  <div class="container py-5 flex-grow-1">
    <div class="row justify-content-center">
      <div class="col-12 col-md-8 col-lg-6">
        <div class="bg-white rounded-4 shadow p-4 text-center">
          <h2 class="h4 fw-bold text-success mb-4">Instruksi Pembayaran</h2>
      <?php if ($is_expired): ?>
            <div class="text-danger fw-bold my-4">Waktu pembayaran habis, pesanan dibatalkan. Silakan pesan ulang.</div>
            <a href="dashboard.php" class="btn btn-secondary mt-3">Kembali ke Beranda</a>
      <?php else: ?>
            <div id="timer-box" class="mb-3 text-danger fw-bold">Sisa waktu pembayaran: <span id="timer">01:00</span></div>
            <div id="expired-message" class="d-none text-danger fw-bold my-3"></div>
            <div class="mb-3 fs-5 text-secondary">
          <?php echo $payment_info; ?>
        </div>
            <div class="mb-3 text-muted">Sertakan kode order berikut saat transfer:<br><span class="fw-bold text-primary fs-6"><?php echo $order_id; ?></span></div>
            <form action="payment_success.php" method="get" class="mb-2">
          <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
              <button type="submit" class="btn btn-success w-100">Saya Sudah Transfer</button>
        </form>
            <a href="dashboard.php" class="btn btn-outline-secondary w-100 mt-2" id="back-to-dashboard">Kembali ke Beranda</a>
      <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
  var USER_ID = <?php echo isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 'null'; ?>;
</script>
<script>
  // Ambil order_id dari PHP
  var ORDER_ID = "<?php echo $order_id; ?>";
  var TIMER_KEY = "timer_start_" + ORDER_ID;
  var now = Date.now();
  var startTime = localStorage.getItem(TIMER_KEY);

  // Jika belum ada waktu mulai, set sekarang
  if (!startTime) {
    startTime = now;
    localStorage.setItem(TIMER_KEY, startTime);
  } else {
    startTime = parseInt(startTime);
  }

  // Timer 5 menit
  let duration = 1 * 60; // 1 menit dalam detik
  let timerDisplay = document.getElementById('timer');
  let expiredMsg = document.getElementById('expired-message');
  let timerBox = document.getElementById('timer-box');
  let instruksiBox = document.querySelector('.bg-white.rounded-2xl.shadow-lg.p-8.text-center');

  function updateTimer() {
    let elapsed = Math.floor((Date.now() - startTime) / 1000);
    let remaining = duration - elapsed;
    if (remaining < 0) remaining = 0;
    let minutes = Math.floor(remaining / 60);
    let seconds = remaining % 60;
    timerDisplay.textContent =
      (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
    if (remaining === 0) {
      clearInterval(interval);
      timerBox.style.display = 'none';
      expiredMsg.classList.remove('hidden');
      expiredMsg.textContent = 'Waktu pembayaran habis, pesanan dibatalkan. Silakan pesan ulang.';
      // Sembunyikan instruksi dan tombol
      if (instruksiBox) {
        // Sembunyikan form konfirmasi transfer
        let form = instruksiBox.querySelector('form');
        if (form) form.style.display = 'none';
        // Sembunyikan tombol 'Kembali ke Beranda'
        let backBtn = document.getElementById('back-to-dashboard');
        if (backBtn) backBtn.style.display = 'none';
      }
      // Hapus waktu timer dari localStorage
      localStorage.removeItem(TIMER_KEY);
      // Update status order di backend
      fetch('expire_order.php?order_id=' + encodeURIComponent(ORDER_ID))
        .then(res => {
          if (!res.ok) throw new Error('Gagal update status order');
        })
        .catch(err => {
          expiredMsg.textContent += '\n(Gagal update status pesanan di server)';
        });
      // Redirect otomatis setelah 5 detik
      setTimeout(function() {
        window.location.href = 'dashboard.php';
      }, 5000);
    }
  }

  updateTimer();
  let interval = setInterval(updateTimer, 1000);
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  // Hapus semua kemungkinan key keranjang
  var userId = typeof USER_ID !== 'undefined' && USER_ID ? USER_ID : null;
  localStorage.removeItem('cartItems');
  localStorage.removeItem('cartCount');
  localStorage.removeItem('cartItems_user_' + userId);
  localStorage.removeItem('cartCount_user_' + userId);
  localStorage.removeItem('cartItems_guest');
  localStorage.removeItem('cartCount_guest');
  sessionStorage.removeItem('checkoutItems');
  localStorage.removeItem('buyNowItem');
  // Update badge keranjang jika ada
  var cartCountElem = document.getElementById('cart-count');
  if (cartCountElem) cartCountElem.textContent = '0';
});
</script>
</body>
</html> 