<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../db.php";

$status = "";
$errors = [];

/* Load categories */
$categories = $pdo->query("SELECT id, category_name FROM categories ORDER BY category_name ASC")->fetchAll();

/* Handle Submit */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $product_name = trim($_POST['product_name']);
    $category_id  = $_POST['category_id'];
    $description  = trim($_POST['description']);

    $ingredients  = trim($_POST['ingredients']);
    $why_choose_us = trim($_POST['why_choose_us']);
    $benefits     = trim($_POST['benefits']);
    $shelf_life   = trim($_POST['shelf_life']);
    $packaging    = trim($_POST['packaging']);
    $origin       = trim($_POST['origin']);

    $sizes_json = $_POST['sizes_json'] ?? '';
    $price_variants_json = $_POST['price_variants_json'] ?? '';

    if (!$product_name)  $errors[] = "Product name is required.";
    if (!$category_id)   $errors[] = "Category required.";
    if (!$description)   $errors[] = "Description required.";
    if (!$sizes_json)    $errors[] = "Add at least one product size.";
    if (!$price_variants_json) $errors[] = "Add prices for sizes.";

    /* MULTIPLE IMAGE UPLOAD */
    $uploadedImages = [];
    $uploadDir = __DIR__ . '/../uploads/products/';
    $dbFolder = 'uploads/products/';

    if (!is_dir($uploadDir)) mkdir($uploadDir, 0775, true);

    function uploadImg($fileIndex, $inputName, &$uploadedImages, $uploadDir, $dbFolder){
        if (!isset($_FILES[$inputName]['error'][$fileIndex]) || $_FILES[$inputName]['error'][$fileIndex] !== UPLOAD_ERR_OK) return;

        $name = $_FILES[$inputName]['name'][$fileIndex];
        $tmp  = $_FILES[$inputName]['tmp_name'][$fileIndex];
        $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) return;

        $new = uniqid("prod_").".$ext";
        if (move_uploaded_file($tmp, $uploadDir.$new)) {
            $uploadedImages[] = $dbFolder.$new;
        }
    }

    if (!empty($_FILES['main_image']['name'][0])) {
        for ($i = 0; $i < count($_FILES['main_image']['name']); $i++) {
            uploadImg($i, 'main_image', $uploadedImages, $uploadDir, $dbFolder);
        }
    } else {
        $errors[] = "Main image is required.";
    }

    if (!empty($_FILES['other_images']['name'][0])) {
        for ($i = 0; $i < count($_FILES['other_images']['name']); $i++) {
            uploadImg($i, 'other_images', $uploadedImages, $uploadDir, $dbFolder);
        }
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare("
            INSERT INTO products 
            (product_name, category_id, description, ingredients, why_choose_us, benefits, shelf_life,
             packaging, origin, sizes, price_variants, images)
            VALUES 
            (?,?,?,?,?,?,?,?,?,?,?,?)
        ");
        $stmt->execute([
            $product_name,$category_id,$description,$ingredients,$why_choose_us,$benefits,
            $shelf_life,$packaging,$origin,$sizes_json,$price_variants_json,
            json_encode($uploadedImages)
        ]);

        $status = "Product added successfully!";
        $_POST = [];
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Product</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

<style>
:root{
    --primary:#0b4f27;
    --primary-dark:#083a1d;
    --bg:#f3f4f6;
    --card:#ffffff;
    --text:#1f2937;
    --muted:#6b7280;
}

body{
    font-family:'Poppins',sans-serif;
    background:var(--bg);
    color:var(--text);
    padding:20px;
}

.container{max-width:1100px;margin:auto;}

.card{
    background:var(--card);
    padding:25px;
    border-radius:14px;
    margin-bottom:20px;
    box-shadow:0 8px 20px rgba(0,0,0,.06);
}

h2{color:var(--primary);margin-bottom:15px;}

label{
    font-weight:500;
    margin-top:14px;
    display:block;
}

input,textarea,select{
    width:100%;
    padding:10px 12px;
    margin-top:6px;
    border-radius:8px;
    border:1px solid #d1d5db;
    background:#fff;
    font-size:14px;
}

textarea{min-height:90px;}

.btn{
    background:var(--primary);
    color:#fff;
    padding:10px 16px;
    border:none;
    border-radius:8px;
    cursor:pointer;
    margin-top:15px;
    font-weight:600;
}

.btn:hover{background:var(--primary-dark);}

.btn.remove{
    background:#dc3545;
}

.alert{
    padding:12px;
    border-radius:8px;
    margin-bottom:12px;
}

.alert.error{
    background:#fee2e2;
    color:#7f1d1d;
}

.alert.ok{
    background:#dcfce7;
    color:#065f46;
}

.size-box{
    border:1px dashed #9ca3af;
    padding:14px;
    border-radius:10px;
    margin-bottom:12px;
    background:#f9fafb;
}
</style>
</head>

<body>

<div class="container">

<div class="card">
<h2>Add Product</h2>

<?php if ($errors): ?>
<div class="alert error"><ul><?php foreach($errors as $e) echo "<li>$e</li>"; ?></ul></div>
<?php endif; ?>

<?php if ($status): ?>
<div class="alert ok"><?= $status ?></div>
<?php endif; ?>

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

<label>Product Name *</label>
<input type="text" name="product_name" value="<?= htmlspecialchars($_POST['product_name'] ?? '') ?>" required>

<label>Category *</label>
<select name="category_id" required>
<option value="">Select</option>
<?php foreach($categories as $c): ?>
<option value="<?= $c['id'] ?>" <?= (($_POST['category_id'] ?? '')==$c['id'])?'selected':'' ?>>
<?= htmlspecialchars($c['category_name']) ?>
</option>
<?php endforeach; ?>
</select>

<label>Description *</label>
<textarea name="description" required><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>

<h3 style="margin-top:25px;">Product Sizes & Prices</h3>
<div id="sizesContainer"></div>
<button type="button" class="btn" onclick="addSize()">+ Add Size</button>

<input type="hidden" name="sizes_json" id="sizes_json">
<input type="hidden" name="price_variants_json" id="price_variants_json">

<label>Main Image *</label>
<input type="file" name="main_image[]" accept="image/*" required>

<label>Other Images</label>
<div id="otherImageBox"></div>
<button type="button" class="btn" onclick="addOtherImage()">+ Add Another Image</button>

<label>Ingredients</label>
<textarea name="ingredients"><?= htmlspecialchars($_POST['ingredients'] ?? '') ?></textarea>

<label>Why Choose Us</label>
<textarea name="why_choose_us"><?= htmlspecialchars($_POST['why_choose_us'] ?? '') ?></textarea>

<label>Benefits</label>
<textarea name="benefits"><?= htmlspecialchars($_POST['benefits'] ?? '') ?></textarea>

<label>Shelf Life</label>
<input type="text" name="shelf_life" value="<?= htmlspecialchars($_POST['shelf_life'] ?? '') ?>">

<label>Packaging</label>
<input type="text" name="packaging" value="<?= htmlspecialchars($_POST['packaging'] ?? '') ?>">

<label>Origin</label>
<input type="text" name="origin" value="<?= htmlspecialchars($_POST['origin'] ?? '') ?>">

<button class="btn">Save Product</button>

</form>
</div>

</div>

<script>
function addOtherImage(){
    let d=document.createElement("div");
    d.innerHTML=`<input type="file" name="other_images[]" accept="image/*" style="margin-top:10px;">`;
    document.getElementById("otherImageBox").appendChild(d);
}

function addSize(){
    let d=document.createElement("div");
    d.className="size-box";
    d.innerHTML=`
      <label>Size</label><input type="text" class="size">
      <label>Price With Garlic</label><input type="number" class="price_with">
      <label>Price Without Garlic</label><input type="number" class="price_without">
      <button type="button" class="btn remove" onclick="this.parentNode.remove()">Remove</button>
    `;
    document.getElementById("sizesContainer").appendChild(d);
}

document.querySelector("form").addEventListener("submit",function(e){
    let boxes=document.querySelectorAll(".size-box");
    if(!boxes.length){alert("Add at least one size");e.preventDefault();return;}
    let sizes=[],prices={};
    boxes.forEach(b=>{
        let s=b.querySelector(".size").value.trim();
        if(!s) return;
        sizes.push(s);
        prices[s]={with:+b.querySelector(".price_with").value||0,without:+b.querySelector(".price_without").value||0};
    });
    document.getElementById("sizes_json").value=JSON.stringify(sizes);
    document.getElementById("price_variants_json").value=JSON.stringify(prices);
});
</script>

</body>
</html>
