<?php
include "auth.php";
include "db.php";

$id = $_GET['id'];


$result = $conn->query("SELECT * FROM products WHERE id=$id");
$product = $result->fetch_assoc();


$colorsResult = $conn->query("SELECT * FROM product_colors WHERE product_id=$id");


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

    $name = $_POST['name'];
    $price = $_POST['price'];
    $category = $_POST['category'];
    $stock = $_POST['stock'];
    $description = $_POST['description'];

   
    $conn->query("
        UPDATE products SET
        name='$name',
        price='$price',
        category='$category',
        stock='$stock',
        description='$description'
        WHERE id=$id
    ");

    

   
    $conn->query("DELETE FROM product_colors WHERE product_id=$id");

    if (!empty($_POST['colors'])) {

        foreach ($_POST['colors'] as $color) {

            if (!empty($color)) {

                $color = trim($color);

                $conn->query("
                    INSERT INTO product_colors (product_id, color)
                    VALUES ('$id', '$color')
                ");
            }
        }
    }

    

    if (!empty($_FILES['images']['name'][0])) {

        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {

            $image_name = time() . "_" . $_FILES['images']['name'][$key];

            move_uploaded_file($tmp_name, "../uploads/" . $image_name);

            $conn->query("
                INSERT INTO product_images (product_id, image_path)
                VALUES ('$id', '$image_name')
            ");
        }
    }

    header("Location: products.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description"
content="Maria Curtains offers quality curtains, sheers, curtain rods, mats and home décor in Thika, Kenya. Affordable prices, custom fitting and professional installation.">
  
<title>Edit Product</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">


   <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Playfair+Display:wght@500;600;700&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Playfair+Display:wght@500;600;700&display=swap" rel="stylesheet">

<link rel="stylesheet" href="admin.css">
</head>

<body>

<div class="admin-container">
<button class="menu-toggle" id="menu-toggle">
    <i class="fa-solid fa-bars"></i>
</button>

  <aside class="sidebar" id="sidebar">

    <h2 class="logo">Maria Admin</h2>

   <nav>
      <a href="dashboard.php">Dashboard</a>
      <a href="addproducts.php">Add Product</a>
      <a href="add_offer.php">Add Offer</a>
      <a href="offers.php">Offers</a>
      <a href="products.php" class="active">Products</a>
      <a href="categoriesadmin.php">Categories</a>
      <a href="settings.php">Settings</a>
      <a href="logout.php" class="logout">Logout</a>
    </nav>

  </aside>

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

    <h2>Edit Product</h2>

    <input type="text" name="name" value="<?= $product['name'] ?>" placeholder="Product Name">

    <input type="number" name="price" value="<?= $product['price'] ?>" placeholder="Price">

    <select name="category">
      <option <?= $product['category']=="Curtains"?"selected":"" ?>>Curtains</option>
      <option <?= $product['category']=="Sheers"?"selected":"" ?>>Sheers</option>
      <option <?= $product['category']=="Rods"?"selected":"" ?>>Rods</option>
      <option <?= $product['category']=="Mats"?"selected":"" ?>>Mats</option>
      <option <?= $product['category']=="Pillows"?"selected":"" ?>>Pillows</option>
      <option <?= $product['category']=="Accessories"?"selected":"" ?>>Accessories</option>
      <option <?= $product['category']=="Others"?"selected":"" ?>>Others</option>
    </select>

    <input type="number" name="stock" value="<?= $product['stock'] ?>" placeholder="Stock">

    <textarea name="description"><?= $product['description'] ?></textarea>

    
    <h4>Product Colors</h4>

    <div id="color-container">

      <?php while($color = $colorsResult->fetch_assoc()): ?>

        <input type="text" name="colors[]" value="<?= $color['color'] ?>">

      <?php endwhile; ?>

      
      <input type="text" name="colors[]" placeholder="Add color (e.g. Red)">

    </div>

    <button type="button" onclick="addColorField()">
      + Add Another Color
    </button>

    
    <h4>Product Images</h4>

    <div class="image-grid">

      <?php
      $imgs = $conn->query("SELECT * FROM product_images WHERE product_id=$id");
      while($img = $imgs->fetch_assoc()):
      ?>

        <div class="img-box">

          <img src="../uploads/<?= $img['image_path'] ?>" width="90">

          <a href="delete-image.php?id=<?= $img['id'] ?>&pid=<?= $id ?>"
             onclick="return confirm('Delete this image?')">
            Delete
          </a>

        </div>

      <?php endwhile; ?>

    </div>

    <input type="file" name="images[]" multiple>

    <button type="submit" name="update">
      Update Product
    </button>

  </form>

</div>


<script>
function addColorField() {
    const container = document.getElementById("color-container");

    const input = document.createElement("input");
    input.type = "text";
    input.name = "colors[]";
    input.placeholder = "Add color (e.g. Blue)";

    container.appendChild(input);
}
 
const menuToggle = document.getElementById("menu-toggle");
const sidebar = document.getElementById("sidebar");
const icon = menuToggle.querySelector("i");

menuToggle.addEventListener("click", function(){

    sidebar.classList.toggle("active");

    if(sidebar.classList.contains("active")){

        icon.classList.remove("fa-bars");
        icon.classList.add("fa-xmark");

    }else{

        icon.classList.remove("fa-xmark");
        icon.classList.add("fa-bars");

    }

});


</script>

</body>
</html>