<?php
include "db.php";

/* Categories */
$categories = $pdo->query("SELECT * FROM categories")->fetchAll();

/* Selected category */
$catId = $_GET['category'] ?? '';

/* Products */
if ($catId) {
  $stmt = $pdo->prepare("SELECT * FROM products WHERE category_id=?");
  $stmt->execute([$catId]);
  $products = $stmt->fetchAll();
} else {
  $products = $pdo->query("SELECT * FROM products")->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Products</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- LORA FONT -->
<link href="https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600;700&display=swap" rel="stylesheet">

<style>
*{box-sizing:border-box}

body{
  margin:0;
  font-family:'Lora', serif;
  background:#EDF6E8;
  color:#1f2937;
}

/* PAGE */
.page{
  max-width:1400px;
  margin:auto;
  padding:30px 20px;
}

/* LAYOUT */
.layout{
  display:grid;
  grid-template-columns:260px 1fr;
  gap:28px;
}

/* SIDEBAR */
.sidebar{
  background:#fff;
  padding:22px;
  border-radius:16px;
  box-shadow:0 8px 22px rgba(0,0,0,0.08);
}

.sidebar h3{
  margin-bottom:14px;
  font-size:18px;
  color:#2F6B2F;
}

.sidebar a{
  display:block;
  padding:12px 14px;
  margin-bottom:8px;
  border-radius:10px;
  text-decoration:none;
  color:#2F6B2F;
  border:1px solid #A7D48C;
}

.sidebar a.active{
  background:#6FB23F;
  color:#fff;
  font-weight:600;
}

/* MOBILE FILTER */
.mobile-filter{
  display:none;
  margin-bottom:20px;
}

.mobile-filter select{
  width:100%;
  padding:12px;
  border-radius:10px;
  border:1px solid #A7D48C;
  font-family:'Lora', serif;
}

/* MAIN */
.main h2{
  margin-bottom:20px;
  font-size:28px;
  color:#2F6B2F;
}

/* GRID */
.grid{
  display:grid;
  grid-template-columns:repeat(auto-fill, minmax(260px,1fr));
  gap:28px;
}

/* CARD */
.card{
  background:#fff;
  border-radius:18px;
  box-shadow:0 10px 26px rgba(0,0,0,0.1);
  overflow:hidden;
  transition:0.25s;
}

.card:hover{transform:translateY(-6px)}

.card img{
  width:100%;
  max-height:220px;
  object-fit:contain;
  padding:18px;
  background:#F7FBF4;
}

.card-body{
  padding:18px;
  text-align:center;
}

.card-body h4{
  margin-bottom:12px;
  font-size:17px;
  font-weight:600;
}

/* VARIANT */
.variant-select{
  width:100%;
  padding:10px;
  border-radius:8px;
  border:1px solid #cbd5e1;
  font-family:'Lora', serif;
}

/* PRICE */
.price{
  margin-top:10px;
  font-size:19px;
  font-weight:700;
  color:#E6B800;
}

/* ACTION */
.actions{margin-top:16px}

.cart-btn{
  width:100%;
  padding:13px;
  border-radius:10px;
  border:none;
  font-weight:600;
  cursor:pointer;
  background:#F2C94C;
}

.cart-btn:disabled{
  background:#d1d5db;
  cursor:not-allowed;
}

/* TOAST */
#toast{
  position:fixed;
  bottom:26px;
  right:26px;
  background:#2F6B2F;
  color:#fff;
  padding:14px 22px;
  border-radius:10px;
  opacity:0;
  transform:translateY(20px);
  transition:0.3s;
  z-index:9999;
}

#toast.show{
  opacity:1;
  transform:translateY(0);
}

/* RESPONSIVE */
@media(max-width:900px){
  .layout{grid-template-columns:1fr}
  .sidebar{display:none}
  .mobile-filter{display:block}
}
</style>
</head>

<body>

<?php include "header.php"; ?>

<div class="page">

<!-- MOBILE CATEGORY DROPDOWN -->
<div class="mobile-filter">
  <select onchange="filterCategory(this.value)">
    <option value="">All Products</option>
    <?php foreach($categories as $c){ ?>
      <option value="<?= $c['id'] ?>" <?= $catId==$c['id']?'selected':'' ?>>
        <?= $c['category_name'] ?>
      </option>
    <?php } ?>
  </select>
</div>

<div class="layout">

<!-- SIDEBAR -->
<aside class="sidebar">
  <h3>Categories</h3>
  <a href="products.php" class="<?= !$catId?'active':'' ?>">All</a>
  <?php foreach($categories as $c){ ?>
    <a href="products.php?category=<?= $c['id'] ?>"
       class="<?= $catId==$c['id']?'active':'' ?>">
      <?= $c['category_name'] ?>
    </a>
  <?php } ?>
</aside>

<!-- PRODUCTS -->
<main class="main">
<h2>Our Products</h2>

<div class="grid">
<?php foreach($products as $p){

  $stmt = $pdo->prepare("SELECT * FROM product_variants WHERE product_id=?");
  $stmt->execute([$p['id']]);
  $vars = $stmt->fetchAll();
?>
<div class="card">
  <img src="assets/images/products/<?= $p['image'] ?>">

  <div class="card-body">
    <h4><?= $p['product_name'] ?></h4>

    <select class="variant-select" onchange="onVariantChange(this)">
      <?php foreach($vars as $v){ ?>
        <option value="<?= $v['price'] ?>">
          <?= $v['weight'] ?> - &#8377;<?= $v['price'] ?>
        </option>
      <?php } ?>
    </select>

    <div class="price">&#8377;<?= $vars[0]['price'] ?></div>

    <div class="actions">
      <button class="cart-btn"
        onclick="addToCart('<?= $p['id'] ?>','<?= $p['product_name'] ?>',this)">
        Add to Cart
      </button>
    </div>
  </div>
</div>
<?php } ?>
</div>
</main>

</div>
</div>

<div id="toast">Added to cart</div>

<script>
const addedMap = {};

function filterCategory(id){
  window.location = id ? "products.php?category="+id : "products.php";
}

function resetButton(sel){
  let btn = sel.closest(".card-body").querySelector(".cart-btn");
  btn.disabled = false;
  btn.innerText = "Add to Cart";
}

function onVariantChange(sel){
  sel.closest(".card-body").querySelector(".price").innerHTML =
    "&#8377;" + sel.value;
  resetButton(sel);
}

function getVariant(btn){
  let s = btn.closest(".card-body").querySelector("select");
  return {
    key: s.options[s.selectedIndex].text,
    weight: s.options[s.selectedIndex].text.split("-")[0].trim(),
    price: s.value
  };
}

function showToast(msg){
  let t = document.getElementById("toast");
  t.innerText = msg;
  t.classList.add("show");
  setTimeout(()=>t.classList.remove("show"),2000);
}

function addToCart(pid,name,btn){
  let v = getVariant(btn);
  let key = pid + "_" + v.key;
  if(addedMap[key]) return;

  let img = btn.closest(".card").querySelector("img").src;

  let fd = new FormData();
  fd.append("product_id",pid);
  fd.append("product_name",name);
  fd.append("weight",v.weight);
  fd.append("price",v.price);
  fd.append("image",img);

  fetch("cart_handler.php",{
    method:"POST",
    headers:{ "X-Requested-With":"XMLHttpRequest" },
    body:fd
  })
  .then(r=>r.text())
  .then(c=>{
    document.querySelector(".cart-count").innerText = c;
    addedMap[key] = true;
    btn.disabled = true;
    btn.innerText = "Added";
    showToast("Added to cart 🛒");
  });
}
</script>

<?php include "footer.php"; ?>
</body>
</html>
