<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once(__DIR__ . '/../config/db_config.php');
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout</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">

<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 d-flex align-items-center gap-2" href="#">
      <img src="/logo.png" alt="Logo" class="rounded-circle bg-light object-fit-cover" style="height:40px;width:40px;object-fit:cover;" onerror="this.style.display='none'">
      <span class="fw-bold text-success">Bakso Alam</span>
    </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>
    <?php if (isset($_SESSION['user_id'])): ?>
          <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>
    <?php endif; ?>
    <?php if (isset($_SESSION['user_id'])): ?>
          <li class="nav-item"><a href="logout.php" class="btn btn-success text-white ms-2">Logout</a></li>
    <?php else: ?>
          <li class="nav-item"><a href="login.php" class="btn btn-success text-white ms-2">Sign in</a></li>
    <?php endif; ?>
      </ul>
    </div>
  </div>
</nav>

  <div class="container py-5 flex-grow-1">
    <div class="row justify-content-center">
      <div class="col-12 col-md-10 col-lg-8">
        <div class="bg-white rounded-4 shadow p-4">
          <h2 class="h4 fw-bold text-success mb-4">Informasi Pengiriman</h2>
          <form id="checkout-form" method="POST" action="process_payment.php">
        <input type="hidden" name="items" id="items-hidden">
        <input type="hidden" name="gross_amount" id="gross-amount-hidden">
        <!-- Ringkasan Pesanan -->
            <div class="mb-4">
              <div class="fw-bold text-secondary mb-2">Ringkasan Pesanan</div>
              <div id="order-summary" class="table-responsive"></div>
        </div>
            <div class="mb-3">
              <label for="customer-name" class="form-label fw-semibold">Nama Lengkap</label>
              <input type="text" name="customer_name" id="customer-name" required class="form-control">
        </div>
            <div class="mb-3">
              <label for="customer-phone" class="form-label fw-semibold">No Handphone</label>
              <input type="text" name="customer_phone" id="customer-phone" required class="form-control">
        </div>
            <div class="mb-3">
              <label for="customer-email" class="form-label fw-semibold">Email</label>
              <input type="email" name="customer_email" id="customer-email" required class="form-control">
        </div>
            <div class="mb-3">
              <label for="customer-address" class="form-label fw-semibold">Alamat</label>
              <textarea name="customer_address" id="customer-address" required class="form-control"></textarea>
        </div>
            <div class="mb-3">
              <label for="shipping-method" class="form-label fw-semibold">Pengiriman</label>
              <select id="shipping-method" name="shipping_label" class="form-select">
            <option value="gojek">gojek (Rp 15.000)</option>
            <option value="jne">JNE (Rp 25.000)</option>
          </select>
        </div>
            <div class="mb-4">
              <div class="fw-bold text-secondary mb-2 mt-4">Metode Pembayaran</div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="payment_method" id="payment-dana" value="dana" required>
                <label class="form-check-label fw-semibold" for="payment-dana">E-wallet DANA</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="payment_method" id="payment-mandiri" value="mandiri" required>
                <label class="form-check-label fw-semibold" for="payment-mandiri">transfer bank Mandiri</label>
          </div>
        </div>
            <div class="d-grid mt-4">
              <button type="submit" id="pay-button" class="btn btn-success btn-lg">Bayar Sekarang</button>
            </div>
            <div id="payment-error" class="mt-3 text-danger"></div>
          </form>
        </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>
    function formatRupiah(price) {
      return 'Rp ' + price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }
    let cartItems = [];
    let totalAmount = 0;
    let shippingCost = 15000;
    let shippingLabel = 'gojek';
    // Ambil data dari localStorage buyNowItem jika mode buynow
    if (window.location.search.includes('buynow=1') && localStorage.getItem('buyNowItem')) {
      cartItems = JSON.parse(localStorage.getItem('buyNowItem'));
    } else if (sessionStorage.getItem('checkoutItems')) {
      cartItems = JSON.parse(sessionStorage.getItem('checkoutItems'));
    }
    // Render ringkasan pesanan
    function renderOrderSummary(items, shippingCost, shippingLabel) {
      let html = '';
      let itemsTotal = 0;
      if (!items || items.length === 0) {
        html = '<div class="text-red-600">Keranjang kosong. Silakan pilih produk terlebih dahulu.</div>';
        document.getElementById('order-summary').innerHTML = html;
        document.getElementById('pay-button').disabled = true;
        document.getElementById('pay-button').classList.add('opacity-50');
        return;
      } else {
        document.getElementById('pay-button').disabled = false;
        document.getElementById('pay-button').classList.remove('opacity-50');
      }
      html += `
        <table style="width:100%; border-collapse:collapse; margin-bottom:12px;">
          <thead>
            <tr style="background:#f3f4f6;">
              <th style="text-align:left; padding:8px; border-bottom:2px solid #e5e7eb;">Produk</th>
              <th style="text-align:center; padding:8px; border-bottom:2px solid #e5e7eb;">Qty</th>
              <th style="text-align:right; padding:8px; border-bottom:2px solid #e5e7eb;">Harga</th>
              <th style="text-align:right; padding:8px; border-bottom:2px solid #e5e7eb;">Subtotal</th>
            </tr>
          </thead>
          <tbody>
      `;
      items.forEach(item => {
        const qty = item.quantity || 1;
        const subtotal = item.price * qty;
        itemsTotal += subtotal;
        html += `
          <tr>
            <td style="padding:8px; border-bottom:1px solid #e5e7eb;">${item.product}</td>
            <td style="text-align:center; padding:8px; border-bottom:1px solid #e5e7eb;">${qty}</td>
            <td style="text-align:right; padding:8px; border-bottom:1px solid #e5e7eb;">${formatRupiah(item.price)}</td>
            <td style="text-align:right; padding:8px; border-bottom:1px solid #e5e7eb;">${formatRupiah(subtotal)}</td>
          </tr>
        `;
      });
      html += `
          </tbody>
          <tfoot>
            <tr>
              <td colspan="3" style="text-align:right; font-weight:600; padding:8px; border-top:2px solid #e5e7eb;">Ongkir (${shippingLabel})</td>
              <td style="text-align:right; padding:8px; border-top:2px solid #e5e7eb;">${formatRupiah(shippingCost)}</td>
            </tr>
            <tr>
              <td colspan="3" style="text-align:right; font-weight:bold; padding:8px;">Total</td>
              <td style="text-align:right; font-weight:bold; padding:8px;">${formatRupiah(itemsTotal + shippingCost)}</td>
            </tr>
          </tfoot>
        </table>
      `;
      document.getElementById('order-summary').innerHTML = html;
      totalAmount = itemsTotal + shippingCost;
    }
    document.addEventListener('DOMContentLoaded', function() {
      renderOrderSummary(cartItems, shippingCost, shippingLabel);
      document.getElementById('checkout-form').addEventListener('submit', function(e) {
        if (!cartItems || cartItems.length === 0) {
          e.preventDefault();
          alert('Keranjang kosong. Silakan pilih produk terlebih dahulu.');
          window.location.href = 'dashboard.php';
          return false;
        }
        document.getElementById('items-hidden').value = JSON.stringify(cartItems);
        document.getElementById('gross-amount-hidden').value = totalAmount;
      });
      document.getElementById('shipping-method').addEventListener('change', function() {
        if (this.value === 'bekasi') {
          shippingCost = 15000;
          shippingLabel = 'Bekasi';
        } else if (this.value === 'jne') {
          shippingCost = 25000;
          shippingLabel = 'jne'; // harus huruf kecil!
        } else if (this.value === 'gojek') {
          shippingCost = 15000;
          shippingLabel = 'gojek';
        } else if (this.value === 'grab') {
          shippingCost = 18000;
          shippingLabel = 'Grab';
        } else if (this.value === 'sicepat') {
          shippingCost = 20000;
          shippingLabel = 'SiCepat';
        }
        renderOrderSummary(cartItems, shippingCost, shippingLabel);
      });
    });
  </script>
  <script>
    // Update badge angka keranjang di checkout.php agar sinkron dengan dashboard.php
    function updateCartBadge() {
      var userId = typeof USER_ID !== 'undefined' && USER_ID ? USER_ID : null;
      var cartKey = userId ? `cartItems_user_${userId}` : 'cartItems_guest';
      var cart = JSON.parse(localStorage.getItem(cartKey) || '[]');
      var total = cart.length;
      var cartCountElem = document.getElementById('cart-count');
      if (cartCountElem) cartCountElem.textContent = total;
    }
    document.addEventListener('DOMContentLoaded', updateCartBadge);
    window.addEventListener('focus', updateCartBadge);
  </script>
</body>
</html> 