<?php
session_start();

if (!isset($_SESSION["admin_id"])) {
    header("Location: login.php");
    exit;
}

require_once "../config/database.php";

$message = "";
$error = "";

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

    $name = trim($_POST["name"] ?? "");
    $category = trim($_POST["category"] ?? "");
    $custom_category = trim($_POST["custom_category"] ?? "");
    $price = trim($_POST["price"] ?? "");
    $description = trim($_POST["description"] ?? "");
    $product_code = trim($_POST["product_code"] ?? "");

    $colours = $_POST["colours"] ?? [];
    $variation_stocks = $_POST["variation_stock"] ?? [];

    if ($category === "Other" && !empty($custom_category)) {
    $category = $custom_category;
}
    if (
        empty($name) ||
        empty($category) ||
        empty($price) ||
        empty($product_code)
    ) {
        $error = "Please fill in all required fields.";

    } elseif (!is_numeric($price) || $price < 0) {
        $error = "Please enter a valid price.";

    } elseif (empty($colours)) {
        $error = "Please add at least one colour.";

    } elseif (count($colours) !== count($variation_stocks)) {
        $error = "Colour and stock information is incomplete.";

    } elseif (
        !isset($_FILES["variation_image"]) ||
        count($_FILES["variation_image"]["name"]) !== count($colours)
    ) {
        $error = "Please select a photo for each colour.";

    } else {

        $allowed_types = [
            "image/jpeg",
            "image/png",
            "image/webp"
        ];

        $upload_dir = "../assets/images/";

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $uploaded_files = [];
        $variation_data = [];
        $validation_failed = false;

        for ($i = 0; $i < count($colours); $i++) {

            $colour = trim($colours[$i]);
            $stock = trim($variation_stocks[$i]);

            if (
                $colour === "" ||
                $stock === "" ||
                !is_numeric($stock) ||
                $stock < 0
            ) {
                $error = "Please enter valid colour and stock information.";
                $validation_failed = true;
                break;
            }

            $file = $_FILES["variation_image"];

            if ($file["error"][$i] !== UPLOAD_ERR_OK) {
                $error = "Please select a valid photo for " .
                         htmlspecialchars($colour) . ".";
                $validation_failed = true;
                break;
            }

            if ($file["size"][$i] > 6 * 1024 * 1024) {
                $error = "Each image must be less than 6MB.";
                        $validation_failed = true;
                break;
            }

            $tmp_name = $file["tmp_name"][$i];

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime_type = finfo_file($finfo, $tmp_name);
            finfo_close($finfo);

            if (!in_array($mime_type, $allowed_types)) {
                $error = "Only JPG, PNG and WEBP images are allowed.";
                $validation_failed = true;
                break;
            }

            $extension = strtolower(
                pathinfo($file["name"][$i], PATHINFO_EXTENSION)
            );

            $image_name = uniqid("product_", true) . "." . $extension;
            $image_path = $upload_dir . $image_name;

            if (!move_uploaded_file($tmp_name, $image_path)) {
                $error = "Failed to upload product image.";
                $validation_failed = true;
                break;
            }

            $uploaded_files[] = $image_path;

            $variation_data[] = [
                "colour" => $colour,
                "stock" => (int)$stock,
                "image" => $image_name
            ];
        }

        if (!$validation_failed) {

            $total_stock = 0;

            foreach ($variation_data as $variation) {
                $total_stock += $variation["stock"];
            }

            $main_image = $variation_data[0]["image"];

            $conn->begin_transaction();

            try {

                $stmt = $conn->prepare(
                    "INSERT INTO products
                    (name, category, price, description, image, stock, product_code)
                    VALUES (?, ?, ?, ?, ?, ?, ?)"
                );

                $stmt->bind_param(
                    "ssdssis",
                    $name,
                    $category,
                    $price,
                    $description,
                    $main_image,
                    $total_stock,
                    $product_code
                );

                if (!$stmt->execute()) {
                    throw new Exception("Failed to save product.");
                }

                $product_id = $stmt->insert_id;

                $stmt->close();

                $variation_stmt = $conn->prepare(
                    "INSERT INTO product_variations
                    (product_id, colour, stock, image)
                    VALUES (?, ?, ?, ?)"
                );

                foreach ($variation_data as $variation) {

                    $variation_stmt->bind_param(
                        "isis",
                        $product_id,
                        $variation["colour"],
                        $variation["stock"],
                        $variation["image"]
                    );

                    if (!$variation_stmt->execute()) {
                        throw new Exception(
                            "Failed to save product variation."
                        );
                    }
                }

                $variation_stmt->close();

                $conn->commit();

                $message = "Product added successfully!";

            } catch (Exception $e) {

                $conn->rollback();

                foreach ($uploaded_files as $file_path) {
                    if (file_exists($file_path)) {
                        unlink($file_path);
                    }
                }

                $error = $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Add Product - Muthu Jewellers</title>

    <style>

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            color: #111;
        }

        header {
            background: #111;
            color: white;
            padding: 18px 25px;
        }

        header h2 {
            color: white;
        }

        .container {
            max-width: 800px;
            margin: 30px auto;
            padding: 30px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 18px rgba(0,0,0,0.08);
        }

        .back {
            display: inline-block;
            margin-bottom: 25px;
            color: #111;
            text-decoration: none;
            font-size: 16px;
        }

        .back:hover {
            color: #b8860b;
        }

        h1 {
            margin-bottom: 28px;
            font-size: 34px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            font-size: 17px;
        }

        input,
        textarea,
        select {
            width: 100%;
            padding: 13px;
            margin-bottom: 18px;
            border: 1px solid #ccc;
            border-radius: 8px;
            font-size: 15px;
        }

        input:focus,
        textarea:focus,
        select:focus {
            outline: none;
            border-color: #b8860b;
        }

        textarea {
            min-height: 110px;
            resize: vertical;
        }

        input[type="file"] {
            padding: 10px;
        }

        .section-title {
            margin-top: 15px;
            margin-bottom: 18px;
            font-size: 23px;
        }

        .variation {
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            background: #fafafa;
            position: relative;
        }

        .variation-title {
            font-weight: bold;
            margin-bottom: 15px;
            color: #555;
        }

        .remove-btn {
            position: absolute;
            top: 15px;
            right: 15px;
            width: auto;
            padding: 7px 12px;
            background: #d9534f;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
        }

        .remove-btn:hover {
            background: #b52b27;
        }

        .add-colour-btn {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            background: #111;
            color: white;
            border: none;
            border-radius: 7px;
            font-size: 15px;
            cursor: pointer;
        }

        .add-colour-btn:hover {
            background: #333;
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: #b8860b;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 17px;
            cursor: pointer;
            font-weight: bold;
        }

        .submit-btn:hover {
            background: #8f6507;
        }

        .success {
            background: #e7f7e7;
            color: #187a18;
            padding: 12px;
            border-radius: 7px;
            margin-bottom: 20px;
        }

        .error {
            background: #ffe5e5;
            color: #c00000;
            padding: 12px;
            border-radius: 7px;
            margin-bottom: 20px;
        }

        .info {
            background: #fff8df;
            border-left: 4px solid #b8860b;
            padding: 12px;
            margin-bottom: 22px;
            border-radius: 5px;
            color: #555;
        }

        @media (max-width: 600px) {

            .container {
                margin: 15px;
                padding: 20px;
            }

            h1 {
                font-size: 28px;
            }

            .variation {
                padding: 15px;
            }

        }

    </style>

</head>

<body>

<header>
    <h2>MUTHU JEWELLERS</h2>
</header>

<div class="container">

    <a href="dashboard.php" class="back">
        ← Back to Dashboard
    </a>

    <h1>Add New Product 💎</h1>

    <?php if ($message): ?>

        <div class="success">
            <?php echo htmlspecialchars($message); ?>
        </div>

    <?php endif; ?>

    <?php if ($error): ?>

        <div class="error">
            <?php echo htmlspecialchars($error); ?>
        </div>

    <?php endif; ?>

    <div class="info">
        Add the product details first, then add each available colour with its own stock and photo.
    </div>

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

        <label>Product Name *</label>

        <input
            type="text"
            name="name"
            placeholder="Example: Gold Earrings"
            required
        >

        <label>Category *</label>

      <select name="category" id="category" required onchange="toggleCustomCategory()">

    <option value="">
        Select Category
    </option>

    <option value="Rings">
        Rings
    </option>

    <option value="Necklaces">
        Necklaces
    </option>

    <option value="Earrings">
        Earrings
    </option>

    <option value="Bracelets">
        Bracelets
    </option>

    <option value="Pendants">
        Pendants
    </option>

    <option value="Hair Clips">
        Hair Clips
    </option>

    <option value="Anklets">
        Anklets
    </option>

    <option value="Brooches">
        Brooches
    </option>

    <option value="Other">
        Other / Custom
    </option>

</select>

<div id="customCategoryBox" style="display: none;">

    <label>Custom Category *</label>

    <input
        type="text"
        name="custom_category"
        id="custom_category"
        placeholder="Example: Hair Accessories"
    >

</div> 

        <label>Price (Rs.) *</label>

        <input
            type="number"
            name="price"
            step="0.01"
            min="0"
            placeholder="Example: 2500"
            required
        >

        <label>Description</label>

        <textarea
            name="description"
            placeholder="Enter product details..."
        ></textarea>

        <label>Product Code *</label>

        <input
            type="text"
            name="product_code"
            placeholder="Example: MJ001"
            required
        >

        <h2 class="section-title">
            🎨 Colours & Stock
        </h2>

        <div id="variations">

            <div class="variation">

                <div class="variation-title">
                    Colour 1
                </div>

                <label>Colour *</label>

                <input
                    type="text"
                    name="colours[]"
                    placeholder="Example: Gold"
                    required
                >

                <label>Stock *</label>

                <input
                    type="number"
                    name="variation_stock[]"
                    min="0"
                    placeholder="Example: 5"
                    required
                >

                <label>Colour Photo *</label>

                <input
                    type="file"
                    name="variation_image[]"
                    accept="image/jpeg,image/png,image/webp"
                    required
                >

            </div>

        </div>

        <button
            type="button"
            class="add-colour-btn"
            onclick="addVariation()"
        >
            + Add Another Colour
        </button>

        <button
            type="submit"
            class="submit-btn"
        >
            Add Product 💎
        </button>

    </form>

</div>
<script>

function addVariation() {

    const container = document.getElementById("variations");

    const count = container.querySelectorAll(".variation").length + 1;

    const div = document.createElement("div");

    div.className = "variation";

    div.innerHTML = `
        <div class="variation-title">
            Colour ${count}
        </div>

        <label>Colour *</label>

        <input
            type="text"
            name="colours[]"
            placeholder="Example: Red"
            required
        >

        <label>Stock *</label>

        <input
            type="number"
            name="variation_stock[]"
            min="0"
            placeholder="Example: 5"
            required
        >

        <label>Colour Photo *</label>

        <input
            type="file"
            name="variation_image[]"
            accept="image/jpeg,image/png,image/webp"
            required
        >
    `;

    container.appendChild(div);
}

function toggleCustomCategory() {

    const category = document.getElementById("category").value;

    const customBox = document.getElementById("customCategoryBox");

    const customInput = document.getElementById("custom_category");

    if (category === "Other") {

        customBox.style.display = "block";

        customInput.required = true;

    } else {

        customBox.style.display = "none";

        customInput.required = false;

        customInput.value = "";
    }
}

</script>
</body>

</html>