<?php
require '../config.php';
session_start();
require '../pelanggan/navbar.php';

if (!isset($_SESSION['user_id'])) {
  header("Location: login.php");
  exit;
}

$user_id = $_SESSION['user_id'];
$ongkir = 20000;

// Ambil data dari POST (dari checkout)
$total_harga = isset($_POST['total_harga']) ? (int)$_POST['total_harga'] : 0;
$kode_diskon = trim($_POST['kode_diskon'] ?? '');
$metode_pembayaran = $_POST['metode_pembayaran'] ?? '';

// Cek apakah sudah ada transaksi status 'menunggu' untuk user
$trx = mysqli_query($conn, "SELECT * FROM transaksi WHERE pengguna_id = $user_id AND status = 'menunggu' ORDER BY id DESC LIMIT 1");
if (mysqli_num_rows($trx) == 0 && $total_harga > 0 && $metode_pembayaran) {
  // Ambil data keranjang sebelum membuat transaksi
  $keranjang = mysqli_query($conn, "
    SELECT k.*, p.harga, up.stok AS stok_ukuran
    FROM keranjang k
    JOIN produk p ON k.produk_id = p.id
    JOIN ukuran_produk up ON k.ukuran_id = up.id
    WHERE k.pengguna_id = $user_id
  ");

  $keranjang_items = [];
  while ($item = mysqli_fetch_assoc($keranjang)) {
    $keranjang_items[] = $item;
  }

  // Pastikan keranjang tidak kosong
  if (count($keranjang_items) > 0) {
    // Insert transaksi baru
    $grand_total = $total_harga + $ongkir;
    $result = mysqli_query($conn, "INSERT INTO transaksi (pengguna_id, total_harga, ongkos_kirim, metode_pembayaran, status, dibuat_pada) VALUES ($user_id, $grand_total, $ongkir, '$metode_pembayaran', 'menunggu', NOW())");

    if ($result) {
      $transaksi_id = mysqli_insert_id($conn);

      // Insert detail transaksi untuk setiap item di keranjang
      foreach ($keranjang_items as $item) {
        $produk_id = $item['produk_id'];
        $ukuran_id = $item['ukuran_id'];
        $jumlah = $item['jumlah'];
        $subtotal = $item['harga'] * $jumlah;

        // Simpan detail transaksi
        mysqli_query($conn, "INSERT INTO transaksi_detail (transaksi_id, produk_id, ukuran_id, jumlah, subtotal) VALUES ($transaksi_id, $produk_id, $ukuran_id, $jumlah, $subtotal)");

        // Kurangi stok
        mysqli_query($conn, "UPDATE ukuran_produk SET stok = stok - $jumlah WHERE id = $ukuran_id");
      }

      // Hapus keranjang user setelah transaksi dan detail berhasil dibuat
      mysqli_query($conn, "DELETE FROM keranjang WHERE pengguna_id = $user_id");
    }
  }
}
// Ambil transaksi status menunggu terbaru
$trx = mysqli_query($conn, "SELECT * FROM transaksi WHERE pengguna_id = $user_id AND status = 'menunggu' ORDER BY id DESC LIMIT 1");
$transaksi = mysqli_fetch_assoc($trx);

// Data bank
$rekeningInfo = [
  'mandiri' => [
    'nama' => 'Mandiri',
    'no' => '137-00-9876543-1',
    'an' => 'Toko ABC',
    'logo' => '../assets/mandiri.png'
  ],
  'bca' => [
    'nama' => 'BCA',
    'no' => '7391516859',
    'an' => 'Albi Putra Mutdriansyah',
    'logo' => '../assets/bca.png'
  ],
  'bri' => [
    'nama' => 'BRI',
    'no' => '0987654321',
    'an' => 'Toko ABC',
    'logo' => '../assets/bri.png'
  ],
  'gopay' => [
    'nama' => 'GoPay',
    'no' => '081314215856',
    'an' => 'Albi',
    'logo' => '../assets/gopay.png'
  ]
];
$bank = $rekeningInfo[$transaksi['metode_pembayaran']] ?? null;

?>
<!DOCTYPE html>
<html lang="id">

<head>
  <meta charset="UTF-8">
  <title>Pembayaran</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      background-color: #f8f8f8;
      color: #333;
      font-family: Arial, sans-serif;
    }

    .main-container {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      padding: 30px;
      margin-top: 40px;
      margin-bottom: 40px;
    }

    h3 {
      color: #222;
      border-bottom: 1px solid #eee;
      padding-bottom: 15px;
      margin-bottom: 30px;
    }

    .timer {
      font-size: 1.3rem;
      font-weight: bold;
      color: #e74c3c;
    }

    .bank-logo {
      width: 60px;
      height: 30px;
      object-fit: contain;
    }

    .va-number {
      font-size: 1.5rem;
      letter-spacing: 2px;
      color: #e67e22;
      font-weight: bold;
    }

    .petunjuk {
      background: #fffbe7;
      border-radius: 10px;
      padding: 15px;
      margin-top: 20px;
    }

    .btn-selesai {
      font-size: 1.1rem;
      font-weight: 500;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-md-8 col-lg-7">
        <div class="main-container">
          <h3 class="fw-semibold">Pembayaran</h3>
          <div class="mb-2">Total Pembayaran:</div>
          <div class="mb-3 fs-4 fw-bold text-primary">Rp<?= number_format($transaksi['total_harga']) ?></div>
          <div class="mb-2">Bayar Dalam:</div>
          <div class="timer mb-2" id="timer">05:00</div>
          <div class="mb-2">Bank yang dipilih:</div>
          <?php if ($bank): ?>
            <div class="d-flex align-items-center gap-3 mb-2">
              <img src="<?= $bank['logo'] ?>" class="bank-logo" alt="<?= $bank['nama'] ?>">
              <div class="fw-semibold">Bank <?= $bank['nama'] ?></div>
            </div>
            <div class="mb-2">No. Rek/VA:</div>
            <div class="va-number mb-2" id="va-number"><?= $bank['no'] ?></div>
            <div class="mb-2">a.n. <?= $bank['an'] ?></div>
            <button class="btn btn-outline-secondary btn-sm mb-3" onclick="copyVA()">Salin</button>
          <?php endif; ?>
          <div class="petunjuk">
            <b>Petunjuk Transfer mBanking</b>
            <ol class="mb-0 mt-2">
              <li>Pilih m-Transfer &gt; <?= $bank ? $bank['nama'] : '-' ?> Virtual Account.</li>
              <li>Masukkan nomor Virtual Account <b><?= $bank ? $bank['no'] : '-' ?></b> dan pilih Send.</li>
              <li>Periksa informasi di layar, pastikan nama dan total tagihan benar.</li>
              <li>Masukkan PIN dan konfirmasi pembayaran.</li>
              <li>Jika gagal, ulangi transaksi atau gunakan metode lain.</li>
            </ol>
          </div>
          <form action="upload_bukti.php" method="GET" class="mt-4 d-flex flex-column gap-2">
            <button type="submit" class="btn btn-success w-100 btn-selesai">Selesaikan Pembayaran</button>
            <a href="checkout.php" class="btn btn-outline-dark w-100">Cancel</a>
          </form>
        </div>
      </div>
    </div>
  </div>
  <?php include '../footer.php'; ?>
  <script>
    // Timer 5 menit
    let timeLeft = 300;
    const timerDiv = document.getElementById('timer');
    const interval = setInterval(() => {
      let min = Math.floor(timeLeft / 60);
      let sec = timeLeft % 60;
      timerDiv.textContent = `${min.toString().padStart(2,'0')}:${sec.toString().padStart(2,'0')}`;
      if (timeLeft <= 0) {
        clearInterval(interval);
        timerDiv.textContent = 'Waktu Habis';
        // TODO: AJAX update status transaksi ke "Menunggu"
        // window.location.reload();
      }
      timeLeft--;
    }, 1000);
    // Copy VA
    function copyVA() {
      const va = document.getElementById('va-number').textContent;
      navigator.clipboard.writeText(va);
      alert('Nomor rekening/VA berhasil disalin!');
    }
  </script>
</body>

</html>