<?php

// Start session at the beginning
session_start();
require_once(__DIR__ . '/../config/db_config.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Keranjang Belanja - Bakso Alam</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">
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body class="bg-light d-flex flex-column min-vh-100">
  <!-- Navbar -->
  <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>
      <div class="collapse navbar-collapse">
        <ul class="navbar-nav ms-auto mb-2 mb-lg-0 gap-3">
          <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"><a href="cart.php" class="nav-link position-relative"><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="nav-link btn btn-success text-white ms-2">Logout</a></li>
      <?php else: ?>
            <li class="nav-item"><a href="login.php" class="nav-link btn btn-success text-white ms-2">Sign in</a></li>
      <?php endif; ?>
        </ul>
      </div>
    </div>
  </nav>

  <!-- Header -->
  <div class="text-center py-5 px-4">
    <h1 class="display-5 fw-bold text-success">Keranjang Belanja</h1>
    <p class="mt-2 text-success">Produk yang telah ditambahkan ke keranjang</p>
  </div>

  <!-- Cart Container -->
  <div class="container pb-5 flex-grow-1">
    <div class="row g-4">
    <!-- Cart Items -->
      <div class="col-lg-8">
        <div id="cart-items-container" class="bg-white rounded shadow p-4 mb-4">
          <h2 class="h4 fw-bold mb-4 pb-4 border-bottom text-secondary">Daftar Barang</h2>
        <!-- Empty Cart Message (shown when cart is empty) -->
          <div id="empty-cart-message" class="d-none text-center py-5">
            <i class="fas fa-shopping-cart fa-3x text-secondary mb-3"></i>
            <p class="text-muted mb-2">Keranjang belanja Anda kosong.</p>
            <a href="dashboard.php" class="btn btn-success">Kembali Berbelanja</a>
        </div>
        <!-- Cart Items List (dynamically populated with JavaScript) -->
          <div id="cart-items-list" class=""></div>
      </div>
    </div>
    <!-- Cart Summary -->
      <div class="col-lg-4">
        <div id="cart-summary" class="bg-white rounded shadow p-4 sticky-top" style="top:100px;">
          <h2 class="h4 fw-bold mb-4 pb-4 border-bottom text-secondary">Ringkasan Belanja</h2>
          <div class="mb-3 d-flex justify-content-between">
            <span>Total Item:</span>
            <span id="total-items">0</span>
          </div>
          <div class="mb-3 d-flex justify-content-between fw-semibold">
            <span>Total Harga:</span>
            <span id="total-price">Rp 0</span>
          </div>
          <div class="mb-3">
            <button id="checkout-button" class="btn btn-success w-100">Lanjutkan ke Pembayaran</button>
          </div>
          <div>
            <a href="dashboard.php" class="btn btn-outline-secondary w-100">Kembali Berbelanja</a>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // Cek login dari PHP ke JS
    const isLoggedIn = <?php echo isset($_SESSION['user_id']) ? 'true' : 'false'; ?>;
    const userId = <?php echo isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 'null'; ?>;
    const cartKey = userId ? `cartItems_user_${userId}` : 'cartItems_guest';
    const cartCountKey = userId ? `cartCount_user_${userId}` : 'cartCount_guest';
    // Debug log untuk memastikan key yang dibaca benar
    console.log('userId:', userId, 'cartKey:', cartKey, 'cart:', localStorage.getItem(cartKey));
    let cartItems = [];
    let cartCount = 0;
    let productStocks = {};
    // Function to format price to Rupiah
    function formatRupiah(price) {
      return 'Rp ' + price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }
    // Ambil stok produk dari backend
    function fetchProductStocks() {
      return fetch('check_products.php')
        .then(res => res.text())
        .then(html => {
          // Parse HTML table to get product name and stock
          const parser = new DOMParser();
          const doc = parser.parseFromString(html, 'text/html');
          const rows = doc.querySelectorAll('table tr');
          let stocks = {};
          rows.forEach((row, idx) => {
            if (idx === 0) return; // skip header
            const cells = row.querySelectorAll('td');
            if (cells.length >= 4) {
              const name = cells[1].textContent.trim();
              const stock = parseInt(cells[3].textContent.trim());
              stocks[name] = stock;
            }
          });
          return stocks;
        });
    }
    // Load cart data from localStorage on page load
    window.addEventListener('DOMContentLoaded', function() {
      // Cek hanya key aktif (cartKey) untuk menentukan apakah keranjang kosong
      const savedCartItems = localStorage.getItem(cartKey);
      if (!savedCartItems || savedCartItems === '[]') {
        document.getElementById('cart-items-list').innerHTML = '';
        document.getElementById('empty-cart-message').classList.remove('d-none');
        document.getElementById('cart-summary').classList.add('d-none');
        document.getElementById('cart-count').textContent = 0;
        return;
      }
      // Lanjutkan proses jika keranjang tidak kosong
      cartItems = JSON.parse(savedCartItems);
      const savedCartCount = localStorage.getItem(cartCountKey);
      if (savedCartCount) {
        cartCount = parseInt(savedCartCount);
        document.getElementById('cart-count').textContent = cartCount;
      } else {
        document.getElementById('cart-count').textContent = 0;
      }
      // Ambil stok produk
      fetchProductStocks().then(stocks => {
        productStocks = stocks;
        displayCartItems();
      });
    });
    // Function to display cart items
    function displayCartItems() {
      const cartItemsList = document.getElementById('cart-items-list');
      const emptyCartMessage = document.getElementById('empty-cart-message');
      const cartSummary = document.getElementById('cart-summary');
      const totalItemsElement = document.getElementById('total-items');
      const totalPriceElement = document.getElementById('total-price');
      cartItemsList.innerHTML = '';
      if (cartItems.length === 0) {
        emptyCartMessage.classList.remove('d-none');
        cartSummary.classList.add('d-none');
      } else {
        emptyCartMessage.classList.add('d-none');
        cartSummary.classList.remove('d-none');
        let totalItems = 0;
        let totalPrice = 0;
        const groupedItems = {};
        cartItems.forEach(item => {
          if (!groupedItems[item.product]) {
            groupedItems[item.product] = {
              product: item.product,
              price: item.price,
              quantity: 1
            };
          } else {
            groupedItems[item.product].quantity += 1;
          }
        });
        // Batasi qty sesuai stok
        let changed = false;
        Object.keys(groupedItems).forEach(prod => {
          const stock = productStocks[prod] ?? 0;
          if (groupedItems[prod].quantity > stock) {
            groupedItems[prod].quantity = stock;
            changed = true;
          }
        });
        if (changed) {
          // Update cartItems dan localStorage jika ada yang melebihi stok
          cartItems = [];
          Object.values(groupedItems).forEach(item => {
            for (let i = 0; i < item.quantity; i++) {
              cartItems.push({ product: item.product, price: item.price });
            }
          });
          cartCount = cartItems.length;
          localStorage.setItem(cartKey, JSON.stringify(cartItems));
          localStorage.setItem(cartCountKey, cartCount.toString());
          document.getElementById('cart-count').textContent = cartCount;
        }
        Object.values(groupedItems).forEach(item => {
          const itemTotal = item.price * item.quantity;
          totalItems += item.quantity;
          totalPrice += itemTotal;
          const itemElement = document.createElement('div');
          itemElement.className = 'd-flex flex-column sm:flex-row items-center justify-content-between gap-4 py-4 border-bottom last:border-bottom-0';
          // Ambil path gambar dari item.image, fallback ke assets/baso-1.jpeg
          const imgPath = item.image && !item.image.startsWith('assets/') ? 'assets/' + item.image : (item.image || 'assets/baso-1.jpeg');
          itemElement.innerHTML = `
            <div class="d-flex items-center w-full sm:w-auto">
              <input type="checkbox" class="select-item mr-3 accent-green-600" data-product="${item.product}" checked>
              <img src="/web-baso/${imgPath}" alt="${item.product}" class="w-20 h-20 object-contain rounded-xl bg-gray-100 mr-4">
              <div>
                <h3 class="font-semibold text-gray-800">${item.product}</h3>
                <p class="text-gray-500 text-sm">${formatRupiah(item.price)} × ${item.quantity}</p>
              </div>
            </div>
            <div class="d-flex items-center gap-2 w-full sm:w-auto justify-content-end">
              <span class="font-semibold text-green-700 mr-2 min-w-[80px] text-right">${formatRupiah(itemTotal)}</span>
              <div class="d-flex items-center border rounded-lg overflow-hidden bg-gray-50">
                <button class="decrease-quantity px-3 py-1 text-lg text-gray-700 hover:bg-gray-200 transition" data-product="${item.product}">-</button>
                <span class="px-3">${item.quantity}</span>
                <button class="increase-quantity px-3 py-1 text-lg text-gray-700 hover:bg-gray-200 transition" data-product="${item.product}">+</button>
              </div>
              <button class="remove-item ml-2 text-red-500 hover:text-red-700 transition" data-product="${item.product}">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          `;
          cartItemsList.appendChild(itemElement);
        });
        totalItemsElement.textContent = totalItems;
        totalPriceElement.textContent = formatRupiah(totalPrice);
        addCartItemEventListeners();
      }
    }
    // Function to add event listeners to cart item buttons
    function addCartItemEventListeners() {
      document.querySelectorAll('.decrease-quantity').forEach(button => {
        button.addEventListener('click', function() {
          const product = this.getAttribute('data-product');
          const index = cartItems.findIndex(item => item.product === product);
          if (index !== -1) {
            cartItems.splice(index, 1);
            cartCount--;
            localStorage.setItem(cartKey, JSON.stringify(cartItems));
            localStorage.setItem(cartCountKey, cartCount.toString());
            document.getElementById('cart-count').textContent = cartCount;
            displayCartItems();
          }
        });
      });
      document.querySelectorAll('.increase-quantity').forEach(button => {
        button.addEventListener('click', function() {
          const product = this.getAttribute('data-product');
          const existingItem = cartItems.find(item => item.product === product);
          // Batasi penambahan sesuai stok
          const stock = productStocks[product] ?? 0;
          const grouped = {};
          cartItems.forEach(item => {
            if (!grouped[item.product]) grouped[item.product] = 1;
            else grouped[item.product]++;
          });
          if (grouped[product] >= stock) {
            Swal.fire({
              icon: 'warning',
              title: 'Stok Habis',
              text: `Stok produk "${product}" hanya tersedia ${stock}!`,
              confirmButtonColor: '#22c55e'
            });
            return;
          }
          if (existingItem) {
            cartItems.push({
              product: existingItem.product,
              price: existingItem.price
            });
            cartCount++;
            localStorage.setItem(cartKey, JSON.stringify(cartItems));
            localStorage.setItem(cartCountKey, cartCount.toString());
            document.getElementById('cart-count').textContent = cartCount;
            displayCartItems();
          }
        });
      });
      document.querySelectorAll('.remove-item').forEach(button => {
        button.addEventListener('click', function() {
          const product = this.getAttribute('data-product');
          const previousCount = cartItems.length;
          cartItems = cartItems.filter(item => item.product !== product);
          const removedCount = previousCount - cartItems.length;
          cartCount -= removedCount;
          localStorage.setItem(cartKey, JSON.stringify(cartItems));
          localStorage.setItem(cartCountKey, cartCount.toString());
          document.getElementById('cart-count').textContent = cartCount;
          displayCartItems();
        });
      });
      const checkoutButton = document.getElementById('checkout-button');
      if (checkoutButton) {
        checkoutButton.addEventListener('click', function() {
          // Ambil produk yang dicentang
          const checkedProducts = Array.from(document.querySelectorAll('.select-item:checked')).map(cb => cb.getAttribute('data-product'));
          if (checkedProducts.length === 0) {
            alert('Pilih minimal satu produk untuk checkout!');
            return;
          }
          // Gabungkan dan hitung quantity
          const grouped = {};
          cartItems.forEach(item => {
            if (checkedProducts.includes(item.product)) {
              const key = item.product + '|' + item.price;
              if (!grouped[key]) {
                grouped[key] = { ...item, quantity: 1 };
              } else {
                grouped[key].quantity += 1;
              }
            }
          });
          sessionStorage.setItem('checkoutItems', JSON.stringify(Object.values(grouped)));
          window.location.href = 'checkout.php';
        });
      }
    }
  </script>
</body>
</html> 