<?php
session_start();
if(!isset($_SESSION['admin_id'])){
  header("Location: index.php");
  exit;
}

require_once "../db.php";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/* DELETE */
if(isset($_GET['delete'])){
  $id=(int)$_GET['delete'];
  $pdo->prepare("DELETE FROM product_variants WHERE product_id=?")->execute([$id]);
  $pdo->prepare("DELETE FROM products WHERE id=?")->execute([$id]);
  header("Location: manage_products.php");
  exit;
}

/* UPDATE */
if(isset($_POST['update'])){
  $id=$_POST['product_id'];

  $old=$pdo->prepare("SELECT image FROM products WHERE id=?");
  $old->execute([$id]);
  $img=$old->fetchColumn();

  if(!empty($_FILES['image']['name'])){
    $img=time()."_".$_FILES['image']['name'];
    move_uploaded_file(
      $_FILES['image']['tmp_name'],
      "../assets/images/products/".$img
    );
  }

  $pdo->prepare(
    "UPDATE products SET product_name=?,category_id=?,product_tag=?,image=? WHERE id=?"
  )->execute([
    $_POST['product_name'],
    $_POST['category_id'],
    $_POST['product_tag'],
    $img,
    $id
  ]);

  if(!empty($_POST['variant_id'])){
    foreach($_POST['variant_id'] as $k=>$vid){
      $pdo->prepare(
        "UPDATE product_variants SET weight=?,price=? WHERE id=?"
      )->execute([
        $_POST['weight'][$k],
        $_POST['price'][$k],
        $vid
      ]);
    }
  }

  header("Location: manage_products.php");
  exit;
}

/* FETCH */
$products=$pdo->query("
  SELECT p.*,c.category_name
  FROM products p
  LEFT JOIN categories c ON p.category_id=c.id
  ORDER BY p.id DESC
")->fetchAll();

$cats=$pdo->query("SELECT * FROM categories")->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Products</title>

<style>
:root{
  --primary:#16a34a;
  --danger:#dc2626;
  --bg:#f1f5f9;
}
*{box-sizing:border-box}
body{margin:0;font-family:system-ui;background:var(--bg)}

/* HEADER */
.header{
  position:sticky;
  top:0;
  background:#fff;
  padding:12px;
  box-shadow:0 4px 12px rgba(0,0,0,.1);
  z-index:10;
}
.header h2{margin:0;font-size:18px}
.search{margin-top:8px}
.search input{
  width:100%;
  padding:10px 14px;
  border-radius:12px;
  border:1px solid #cbd5e1;
}

/* LIST */
.list{padding:12px}
.card{
  background:#fff;
  border-radius:16px;
  padding:12px;
  display:flex;
  gap:12px;
  align-items:center;
  margin-bottom:12px;
  box-shadow:0 8px 20px rgba(0,0,0,.08);
}
.card img{
  width:60px;
  height:60px;
  object-fit:cover;
  border-radius:12px;
}
.card h4{margin:0;font-size:16px}
.card small{color:#64748b}

.actions{
  margin-left:auto;
  display:flex;
  gap:8px;
}
.btn{
  padding:6px 10px;
  border-radius:8px;
  border:none;
  color:#fff;
  font-size:13px;
}
.edit{background:#2563eb}
.delete{background:var(--danger)}

/* MODAL */
.modal{
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.5);
  display:none;
  align-items:flex-end;
}
.sheet{
  background:#fff;
  width:100%;
  border-radius:20px 20px 0 0;
  padding:16px;
}
.sheet img{
  height:70px;
  border-radius:12px;
  margin-bottom:10px;
}
.sheet input,.sheet select{
  width:100%;
  padding:12px;
  margin-bottom:10px;
  border-radius:10px;
  border:1px solid #cbd5e1;
}
.variants{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
}
.variants input{width:48%}
.save{
  background:var(--primary);
  color:#fff;
  width:100%;
  padding:14px;
  border:none;
  border-radius:14px;
  font-size:16px;
}
.close{
  background:#e5e7eb;
  border:none;
  padding:8px 14px;
  border-radius:10px;
  margin-bottom:10px;
}
</style>
</head>
<body>

<!-- HEADER -->
<div class="header">
  <h2>🛒 Products</h2>
  <div class="search">
    <input type="text" placeholder="Search product..." onkeyup="filter(this.value)">
  </div>
</div>

<!-- LIST -->
<div class="list" id="list">
<?php foreach($products as $p): ?>
<div class="card" data-name="<?= strtolower($p['product_name']) ?>">
  <img src="/assets/images/products/<?= $p['image'] ?>">
  <div>
    <h4><?= htmlspecialchars($p['product_name']) ?></h4>
    <small><?= htmlspecialchars($p['category_name']) ?></small>
  </div>

  <div class="actions">
    <button class="btn edit"
      onclick='openEdit(
        <?= json_encode($p) ?>,
        <?= json_encode(
          $pdo->query("SELECT * FROM product_variants WHERE product_id=".$p['id'])->fetchAll()
        ) ?>
      )'>Edit</button>

    <a class="btn delete"
       onclick="return confirm('Delete product?')"
       href="?delete=<?= $p['id'] ?>">Del</a>
  </div>
</div>
<?php endforeach; ?>
</div>

<!-- MODAL -->
<div class="modal" id="modal">
  <div class="sheet">
    <button class="close" onclick="closeEdit()">Close</button>

    <form method="post" enctype="multipart/form-data">
      <input type="hidden" name="product_id" id="pid">

      <img id="pimg">

      <input name="product_name" id="pname">
      <select name="category_id" id="pcat">
        <?php foreach($cats as $c): ?>
          <option value="<?= $c['id'] ?>"><?= $c['category_name'] ?></option>
        <?php endforeach; ?>
      </select>
      <input name="product_tag" id="ptag">
      <input type="file" name="image">

      <div class="variants" id="variants"></div>

      <button class="save" name="update">Update Product</button>
    </form>
  </div>
</div>

<script>
function filter(q){
  q=q.toLowerCase();
  document.querySelectorAll('.card').forEach(c=>{
    c.style.display=c.dataset.name.includes(q)?"flex":"none";
  });
}

function openEdit(p,vars){
  pid.value=p.id;
  pname.value=p.product_name;
  ptag.value=p.product_tag;
  pimg.src="/assets/images/products/"+p.image;
  pcat.value=p.category_id;

  variants.innerHTML="";
  vars.forEach(v=>{
    variants.innerHTML+=`
      <input type="hidden" name="variant_id[]" value="${v.id}">
      <input name="weight[]" value="${v.weight}" placeholder="Weight">
      <input name="price[]" value="${v.price}" placeholder="Price">
    `;
  });

  modal.style.display="flex";
}
function closeEdit(){modal.style.display="none";}
</script>

</body>
</html>
