<?php
// Start session at the beginning
session_start();

// Include database configuration and Product model
require_once(__DIR__ . '/../config/db_config.php');
require_once(__DIR__ . '/../models/Product.php');

// Initialize Product object
$productObj = new Product();

// Get all active products with error handling
try {
    $products = $productObj->getAllProducts();
    if (!is_array($products)) {
        $products = [];
    }
} catch (Exception $e) {
    error_log("Dashboard error: " . $e->getMessage());
    $products = [];
}

// Ambil riwayat pembelian user
$user_orders = [];
if (isset($_SESSION['user_id'])) {
    $db = getDbConnection();
    $stmt = $db->prepare("SELECT * FROM orders WHERE user_id = :user_id ORDER BY created_at DESC");
    $stmt->bindParam(':user_id', $_SESSION['user_id']);
    $stmt->execute();
    $user_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to format price to Rupiah
function formatRupiah($price) {
    return 'Rp ' . number_format($price, 0, ',', '.');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dashboard 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">
</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>
      <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="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>
            <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>

  <!-- Hero Section -->
  <section class="bg-success bg-opacity-10 py-5 text-center">
    <h1 class="display-4 fw-bold text-success mb-3">Selamat Datang di Bakso Alam</h1>
    <p class="lead text-success mb-4">Nikmati berbagai produk terbaik untuk kebutuhan Anda. Belanja mudah, aman, dan cepat!</p>
    <img src="/banner.jpg" alt="Banner" class="mx-auto rounded-4 shadow-lg img-fluid" style="max-height:300px;object-fit:cover;width:100%;max-width:700px;" onerror="this.style.display='none'">
  </section>

  <!-- Produk Section -->
  <section class="container py-5 flex-grow-1">
    <h2 class="h3 fw-bold text-secondary mb-4">Produk Pilihan</h2>
    <div class="row g-4">
      <?php if (!empty($products)): ?>
        <?php foreach ($products as $product): ?>
          <div class="col-12 col-sm-6 col-md-4 col-lg-3 d-flex">
            <div class="card flex-fill shadow-sm border-0">
            <?php if (!empty($product['image'])): ?>
                <img src="/web-baso/<?php echo htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" class="card-img-top img-fluid p-3" style="height:180px;object-fit:contain;background:#f8f9fa;">
            <?php else: ?>
                <div class="d-flex align-items-center justify-content-center" style="height:180px;background:#f8f9fa;">
                  <span class="text-muted">No Image</span>
              </div>
            <?php endif; ?>
              <div class="card-body d-flex flex-column">
                <h5 class="card-title mb-1"><?php echo htmlspecialchars($product['name']); ?></h5>
                <p class="card-text small text-muted mb-2"><?php echo htmlspecialchars($product['description']); ?></p>
                <span class="fw-bold text-success mb-3"><?php echo formatRupiah($product['price']); ?></span>
                <div class="mt-auto d-flex gap-2">
                  <button class="btn btn-success flex-fill add-to-cart" data-product="<?php echo htmlspecialchars($product['name']); ?>" data-price="<?php echo $product['price']; ?>">
                    <i class="fas fa-cart-plus me-2"></i>Keranjang
              </button>
                  <button class="btn btn-warning flex-fill buy-now" data-product="<?php echo htmlspecialchars($product['name']); ?>" data-price="<?php echo $product['price']; ?>">
                Beli
              </button>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php else: ?>
        <div class="col-12 text-center py-5">
          <p class="text-muted">Tidak ada produk yang tersedia saat ini.</p>
        </div>
      <?php endif; ?>
    </div>
  </section>

  <footer class="bg-white border-top py-4 mt-auto">
    <div class="container d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
      <div class="text-secondary">&copy; <?php echo date('Y'); ?> Bakso Alam. All rights reserved.</div>
    </div>
  </footer>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script>
    // Cek login dari PHP ke JS
    const isLoggedIn = <?php echo isset($_SESSION['user_id']) ? 'true' : 'false'; ?>;
    // Initialize cart data
    let cartItems = [];
    let cartCount = 0;
    
    // Load cart data from localStorage on page load
    window.addEventListener('DOMContentLoaded', function() {
      // Load cart data from localStorage if available
      const savedCartItems = localStorage.getItem('cartItems');
      const savedCartCount = localStorage.getItem('cartCount');
      
      if (savedCartItems) {
        cartItems = JSON.parse(savedCartItems);
      }
      
      if (savedCartCount) {
        cartCount = parseInt(savedCartCount);
        document.getElementById('cart-count').textContent = cartCount;
      }
      // Tambahkan event pada ikon keranjang
      const cartIcon = document.querySelector('a[href="cart.php"]');
      if (cartIcon) {
        cartIcon.addEventListener('click', function(e) {
          if (!isLoggedIn) {
            e.preventDefault();
            window.location.href = 'login.php';
          }
        });
      }
    });
    
    // Add click event listeners to all "add to cart" buttons
    document.querySelectorAll('.add-to-cart').forEach(button => {
      button.addEventListener('click', function() {
        if (!isLoggedIn) {
          window.location.href = 'login.php';
          return;
        }
        const product = this.getAttribute('data-product');
        const price = parseInt(this.getAttribute('data-price'));
        
        // Add item to cart
        cartItems.push({
          product: product,
          price: price
        });
        
        // Update cart count
        cartCount++;
        document.getElementById('cart-count').textContent = cartCount;
        
        // Save to localStorage
        localStorage.setItem('cartItems', JSON.stringify(cartItems));
        localStorage.setItem('cartCount', cartCount.toString());
        
        // Show SweetAlert2 success message
        Swal.fire({
          icon: 'success',
          title: 'Berhasil!',
          text: 'Produk berhasil ditambahkan ke keranjang!',
          confirmButtonColor: '#22c55e'
        });
      });
    });
    
    // Add click event listeners to "buy now" buttons
    document.querySelectorAll('.buy-now').forEach(button => {
      button.addEventListener('click', function() {
        if (!isLoggedIn) {
          window.location.href = 'login.php';
          return;
        }
        const product = this.getAttribute('data-product');
        const price = parseInt(this.getAttribute('data-price'));
        const data = [{ product, price }];
        try {
          sessionStorage.setItem('buyNowItem', JSON.stringify(data));
          console.log('Set buyNowItem:', data);
        } catch (e) {
          alert('Gagal menyimpan data checkout.');
          return;
        }
        window.location.href = 'checkout.php';
      });
    });
  </script>
</body>
</html>
