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

include "../db.php";

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

$message = "";

/* Product image folder */
$uploadDir = "../assets/images/products/";

/* Auto-create folder */
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

if (isset($_POST['save_product'])) {

    $product_name = trim($_POST['product_name']);
    $category_id  = $_POST['category_id'];
    $product_tag  = $_POST['product_tag']; // NEW

    /* Image */
    $fileName = $_FILES['image']['name'];
    $fileTmp  = $_FILES['image']['tmp_name'];
    $fileSize = $_FILES['image']['size'];
    $ext      = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    $allowed = ['jpg','jpeg','png','webp'];

    if ($product_name == "" || $category_id == "") {
        $message = "All fields required";
    }
    elseif (!in_array($ext, $allowed)) {
        $message = "Only JPG, PNG, WEBP images allowed";
    }
    elseif ($fileSize > 2 * 1024 * 1024) {
        $message = "Image size max 2MB";
    }
    else {

        $newImg = time() . "_" . rand(1000,9999) . "." . $ext;
        $target = $uploadDir . $newImg;

        if (move_uploaded_file($fileTmp, $target)) {

            /* INSERT PRODUCT (WITH TAG) */
            $stmt = $pdo->prepare(
                "INSERT INTO products 
                 (product_name, category_id, image, product_tag)
                 VALUES (?,?,?,?)"
            );
            $stmt->execute([
                $product_name,
                $category_id,
                $newImg,
                $product_tag
            ]);

            $pid = $pdo->lastInsertId();

            /* INSERT VARIANTS */
            foreach ($_POST['weight'] as $i => $w) {
                if ($w != "" && $_POST['price'][$i] != "") {
                    $stmt = $pdo->prepare(
                        "INSERT INTO product_variants 
                         (product_id, weight, price)
                         VALUES (?,?,?)"
                    );
                    $stmt->execute([$pid, $w, $_POST['price'][$i]]);
                }
            }

            $message = "Product added successfully";
        } else {
            $message = "Image upload failed";
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Product</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
*{box-sizing:border-box}
body{
  margin:0;
  font-family:'Segoe UI', sans-serif;
  background:#f5f6fa;
}
.container{
  max-width:650px;
  margin:30px auto;
  padding:15px;
}
.card{
  background:#fff;
  padding:25px;
  border-radius:12px;
  box-shadow:0 10px 25px rgba(0,0,0,0.08);
}
h2{text-align:center}
input,select,button{
  width:100%;
  padding:12px;
  margin-top:12px;
  border-radius:8px;
}
input,select{border:1px solid #ddd}
.variant{
  display:flex;
  gap:10px;
  margin-top:10px;
}
.variant input{flex:1}
.add{
  background:#000;
  color:#fff;
  border:none;
}
.save{
  background:#d3ae3b;
  border:none;
  font-weight:600;
}
.msg{
  text-align:center;
  margin-bottom:10px;
  font-weight:600;
  color:green;
}
.error{color:red}
@media(max-width:600px){
  .variant{flex-direction:column}
}
</style>
</head>

<body>

<div class="container">
<div class="card">

<h2>Add Product</h2>

<?php if($message): ?>
<div class="msg <?php echo (strpos($message,'failed')!==false || strpos($message,'Only')!==false) ? 'error':''; ?>">
  <?= $message ?>
</div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data">

<input type="text" name="product_name" placeholder="Product Name" required>

<select name="category_id" required>
  <option value="">Select Category</option>
  <?php foreach($cats as $c){ ?>
    <option value="<?= $c['id'] ?>"><?= $c['category_name'] ?></option>
  <?php } ?>
</select>

<!-- 🔥 PRODUCT TAG -->
<select name="product_tag">
  <option value="none">Normal Product</option>
  <option value="best">Best Selling</option>
  <option value="top">Top Rated</option>
  <option value="recommended">Recommended</option>
</select>

<input type="file" name="image" accept="image/*" required>

<h4>Weight Based Pricing</h4>

<div id="variants">
  <div class="variant">
    <input type="text" name="weight[]" placeholder="500g / 1kg" required>
    <input type="number" name="price[]" placeholder="₹ Price" required>
  </div>
</div>

<button type="button" class="add" onclick="addVariant()">+ Add More</button>
<button class="save" name="save_product">Save Product</button>

</form>

</div>
</div>

<script>
function addVariant(){
  document.getElementById("variants").insertAdjacentHTML("beforeend",`
    <div class="variant">
      <input type="text" name="weight[]" placeholder="Weight">
      <input type="number" name="price[]" placeholder="Price">
    </div>
  `);
}
</script>

</body>
</html>
