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

include "../db.php";

$id = intval($_GET['id']);
if ($id <= 0) die("Invalid Product ID");

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

/* Fetch Product */
$stmt = $pdo->prepare("SELECT * FROM products WHERE id=?");
$stmt->execute([$id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) die("Product Not Found!");

$sizes_db = json_decode($product['sizes'], true) ?? [];
$prices_db = json_decode($product['price_variants'], true) ?? [];
$existing_images = json_decode($product['images'], true) ?? [];

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $pname = trim($_POST['product_name']);
    $cat = $_POST['category_id'];
    $desc = trim($_POST['description']);
    $ing = trim($_POST['ingredients']);
    $why = trim($_POST['why_choose_us']);
    $ben = trim($_POST['benefits']);
    $life = trim($_POST['shelf_life']);
    $pack = trim($_POST['packaging']);
    $origin = trim($_POST['origin']);

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

    if (!$pname) $errors[] = "Product name required";
    if (!$cat) $errors[] = "Category required";
    if (!$desc) $errors[] = "Description required";

    $uploadDir = __DIR__ . '/../uploads/products/';
    $dbFolder = 'uploads/products/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0775, true);

    $uploaded = $existing_images;

    function uploadImg($i,$field,&$arr,$dir,$db){
        if (!isset($_FILES[$field]['error'][$i]) || $_FILES[$field]['error'][$i] !== UPLOAD_ERR_OK) return;
        $name = $_FILES[$field]['name'][$i];
        $tmp = $_FILES[$field]['tmp_name'][$i];
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if (!in_array($ext,['jpg','jpeg','png','gif','webp'])) return;
        $new = uniqid("prod_").".$ext";
        move_uploaded_file($tmp,$dir.$new);
        $arr[] = $db.$new;
    }

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

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

    if (!$errors){
        $sql = "UPDATE products SET 
        product_name=?, category_id=?, description=?, ingredients=?, why_choose_us=?, benefits=?,
        shelf_life=?, packaging=?, origin=?, sizes=?, price_variants=?, images=? 
        WHERE id=?";

        $pdo->prepare($sql)->execute([
            $pname,$cat,$desc,$ing,$why,$ben,$life,$pack,$origin,
            $sizes_json,$prices_json,json_encode($uploaded),$id
        ]);

        echo "<script>
            alert('Product Updated Successfully!');
            window.parent.loadPage(null,'view_products.php');
        </script>";
        exit;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit 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;
    box-shadow:0 8px 20px rgba(0,0,0,.06);
}

h3{
    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;
    font-size:14px;
}

textarea{min-height:90px;}

.preview{
    width:70px;
    height:70px;
    object-fit:cover;
    border-radius:8px;
    border:1px solid #e5e7eb;
    margin:5px;
}

.btn{
    padding:10px 16px;
    border-radius:8px;
    border:none;
    font-weight:600;
    cursor:pointer;
    margin-top:15px;
}

.btn-success{background:var(--primary);color:#fff;}
.btn-success:hover{background:var(--primary-dark);}
.btn-secondary{background:#6b7280;color:#fff;}
.btn-danger{background:#dc3545;color:#fff;}
.btn-info{background:#0d6efd;color:#fff;}

.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">

<h3>Edit Product</h3>

<?php if($errors): ?>
<div style="background:#fee2e2;color:#7f1d1d;padding:12px;border-radius:8px;">
    <ul><?php foreach($errors as $e) echo "<li>$e</li>"; ?></ul>
</div>
<?php endif; ?>

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

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

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

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

<label>Existing Images</label><br>
<?php foreach($existing_images as $img): ?>
<img src="../<?= htmlspecialchars($img) ?>" class="preview">
<?php endforeach; ?>

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

<label>Add More Images</label>
<div id="otherImageBox"></div>
<button type="button" class="btn btn-info" onclick="addOtherImage()">+ Add More</button>

<hr>

<h4 style="color:var(--primary);">Sizes & Price Variants</h4>
<div id="sizesContainer"></div>
<button type="button" class="btn btn-info" 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>Ingredients</label>
<textarea name="ingredients"><?= htmlspecialchars($product['ingredients']) ?></textarea>

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

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

<div style="display:flex;gap:10px;">
    <div style="flex:1">
        <label>Shelf Life</label>
        <input type="text" name="shelf_life" value="<?= htmlspecialchars($product['shelf_life']) ?>">
    </div>
    <div style="flex:1">
        <label>Packaging</label>
        <input type="text" name="packaging" value="<?= htmlspecialchars($product['packaging']) ?>">
    </div>
    <div style="flex:1">
        <label>Origin</label>
        <input type="text" name="origin" value="<?= htmlspecialchars($product['origin']) ?>">
    </div>
</div>

<button class="btn btn-success">Update Product</button>
<button type="button" class="btn btn-secondary" onclick="window.parent.loadPage(null,'view_products.php')">Cancel</button>

</form>
</div>
</div>

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

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

let sizesDB = <?= json_encode($sizes_db) ?>;
let pricesDB = <?= json_encode($prices_db) ?>;
sizesDB.forEach(s => addSize(s, pricesDB[s]?.with, pricesDB[s]?.without));

document.querySelector("form").onsubmit=function(){
    let sizes=[], price={};
    document.querySelectorAll(".size-box").forEach(b=>{
        let s=b.querySelector(".size").value.trim();
        if(!s) return;
        sizes.push(s);
        price[s]={with:parseFloat(b.querySelector(".price_with").value||0),
                  without:parseFloat(b.querySelector(".price_without").value||0)};
    });
    document.getElementById("sizes_json").value=JSON.stringify(sizes);
    document.getElementById("price_variants_json").value=JSON.stringify(price);
}
</script>

</body>
</html>
