<?php
session_start();

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

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

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

if (!isset($_GET["id"]) || !is_numeric($_GET["id"])) {
    header("Location: products.php");
    exit;
}

$product_id = (int)$_GET["id"];


/*
 * GET PRODUCT
 */

$stmt = $conn->prepare(
    "SELECT * FROM products WHERE id = ?"
);

$stmt->bind_param("i", $product_id);
$stmt->execute();

$result = $stmt->get_result();
$product = $result->fetch_assoc();

$stmt->close();

if (!$product) {
    header("Location: products.php");
    exit;
}


/*
 * GET COLOUR VARIATIONS
 */

$variation_stmt = $conn->prepare(
    "SELECT * FROM product_variations
     WHERE product_id = ?
     ORDER BY id ASC"
);

$variation_stmt->bind_param("i", $product_id);
$variation_stmt->execute();

$variation_result = $variation_stmt->get_result();

$variations = [];

while ($variation = $variation_result->fetch_assoc()) {
    $variations[] = $variation;
}

$variation_stmt->close();


/*
 * UPDATE PRODUCT
 */

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

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

    /*
     * EXISTING VARIATIONS
     */

    $variation_colours = $_POST["variation_colour"] ?? [];
    $variation_stocks = $_POST["variation_stock"] ?? [];

    /*
     * NEW VARIATIONS
     */

    $new_colours = $_POST["new_colour"] ?? [];
    $new_stocks = $_POST["new_stock"] ?? [];


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

    } else {

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

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

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

        $new_files = [];
        $old_files = [];

        try {

            /*
             * VALIDATE EXISTING VARIATIONS
             */

            $total_stock = 0;

            foreach ($variation_colours as $variation_id => $colour) {

                $colour = trim($colour);

                $stock = $variation_stocks[$variation_id] ?? "";

                if (
                    $colour === "" ||
                    $stock === "" ||
                    !is_numeric($stock) ||
                    $stock < 0
                ) {
                    throw new Exception(
                        "Please enter valid colour and stock information."
                    );
                }

                $total_stock += (int)$stock;
            }


            /*
             * VALIDATE NEW VARIATIONS
             */

            foreach ($new_colours as $index => $colour) {

                $colour = trim($colour);

                $stock = $new_stocks[$index] ?? "";

                if (
                    $colour === "" ||
                    $stock === "" ||
                    !is_numeric($stock) ||
                    $stock < 0
                ) {
                    throw new Exception(
                        "Please enter valid new colour and stock information."
                    );
                }

                $total_stock += (int)$stock;
            }


            /*
             * MAIN IMAGE
             */

            $main_image = $product["image"];

            if (
                isset($_FILES["main_image"]) &&
                $_FILES["main_image"]["error"] === UPLOAD_ERR_OK
            ) {

                if ($_FILES["main_image"]["size"] > 6 * 1024 * 1024) {
                    throw new Exception(
                        "Main image must be less than 6MB."
                    );
                }

                $finfo = finfo_open(FILEINFO_MIME_TYPE);

                $mime_type = finfo_file(
                    $finfo,
                    $_FILES["main_image"]["tmp_name"]
                );

                finfo_close($finfo);

                if (!in_array($mime_type, $allowed_types)) {
                    throw new Exception(
                        "Only JPG, PNG and WEBP images are allowed."
                    );
                }

                $extension = strtolower(
                    pathinfo(
                        $_FILES["main_image"]["name"],
                        PATHINFO_EXTENSION
                    )
                );

                $new_main_image =
                    uniqid("product_", true) . "." . $extension;

                $main_path =
                    $upload_dir . $new_main_image;

                if (!move_uploaded_file(
                    $_FILES["main_image"]["tmp_name"],
                    $main_path
                )) {
                    throw new Exception(
                        "Failed to upload main image."
                    );
                }

                $new_files[] = $main_path;

                if (!empty($product["image"])) {
                    $old_files[] =
                        $upload_dir . $product["image"];
                }

                $main_image = $new_main_image;
            }


            /*
             * START DATABASE TRANSACTION
             */

            $conn->begin_transaction();


            /*
             * UPDATE PRODUCT DETAILS
             */

            $stmt = $conn->prepare(
                "UPDATE products
                 SET name = ?,
                     category = ?,
                     price = ?,
                     description = ?,
                     image = ?,
                     stock = ?,
                     product_code = ?
                 WHERE id = ?"
            );

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

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

            $stmt->close();


            /*
             * UPDATE EXISTING COLOUR VARIATIONS
             */

            $variation_stmt = $conn->prepare(
                "UPDATE product_variations
                 SET colour = ?,
                     stock = ?
                 WHERE id = ?
                 AND product_id = ?"
            );

            foreach ($variation_colours as $variation_id => $colour) {

                $colour = trim($colour);

                $stock =
                    (int)$variation_stocks[$variation_id];

                $variation_id =
                    (int)$variation_id;

                $variation_stmt->bind_param(
                    "siii",
                    $colour,
                    $stock,
                    $variation_id,
                    $product_id
                );

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

            $variation_stmt->close();


            /*
             * ADD NEW COLOUR VARIATIONS
             */

            if (!empty($new_colours)) {

                foreach ($new_colours as $index => $colour) {

                    $colour = trim($colour);

                    $stock =
                        (int)($new_stocks[$index] ?? 0);

                    $image_name = "";


                    /*
                     * NEW COLOUR IMAGE
                     */

                    if (
                        isset($_FILES["new_variation_image"]["error"][$index]) &&
                        $_FILES["new_variation_image"]["error"][$index]
                            === UPLOAD_ERR_OK
                    ) {

                        if (
                            $_FILES["new_variation_image"]["size"][$index]
                            > 6 * 1024 * 1024
                        ) {
                            throw new Exception(
                                "Each colour image must be less than 6MB."
                            );
                        }

                        $tmp_name =
                            $_FILES["new_variation_image"]["tmp_name"][$index];

                        $finfo =
                            finfo_open(FILEINFO_MIME_TYPE);

                        $mime_type =
                            finfo_file(
                                $finfo,
                                $tmp_name
                            );

                        finfo_close($finfo);

                        if (!in_array(
                            $mime_type,
                            $allowed_types
                        )) {
                            throw new Exception(
                                "Only JPG, PNG and WEBP images are allowed."
                            );
                        }

                        $extension = strtolower(
                            pathinfo(
                                $_FILES["new_variation_image"]["name"][$index],
                                PATHINFO_EXTENSION
                            )
                        );

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

                        $image_path =
                            $upload_dir . $image_name;

                        if (!move_uploaded_file(
                            $tmp_name,
                            $image_path
                        )) {
                            throw new Exception(
                                "Failed to upload new colour image."
                            );
                        }

                        $new_files[] = $image_path;

                    } else {

                        throw new Exception(
                            "Please select a photo for the new colour."
                        );
                    }


                    /*
                     * INSERT NEW COLOUR
                     */

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

                    $insert_stmt->bind_param(
                        "isis",
                        $product_id,
                        $colour,
                        $stock,
                        $image_name
                    );

                    if (!$insert_stmt->execute()) {
                        throw new Exception(
                            "Failed to add new colour variation."
                        );
                    }

                    $insert_stmt->close();
                }
            }


            /*
             * UPDATE EXISTING COLOUR PHOTOS
             */

            if (isset($_FILES["variation_image"])) {

                foreach (
                    $_FILES["variation_image"]["error"]
                    as $variation_id => $file_error
                ) {

                    if ($file_error !== UPLOAD_ERR_OK) {
                        continue;
                    }

                    if (
                        $_FILES["variation_image"]["size"][$variation_id]
                        > 6 * 1024 * 1024
                    ) {
                        throw new Exception(
                            "Each image must be less than 6MB."
                        );
                    }

                    $tmp_name =
                        $_FILES["variation_image"]["tmp_name"][$variation_id];

                    $finfo =
                        finfo_open(FILEINFO_MIME_TYPE);

                    $mime_type =
                        finfo_file(
                            $finfo,
                            $tmp_name
                        );

                    finfo_close($finfo);

                    if (!in_array(
                        $mime_type,
                        $allowed_types
                    )) {
                        throw new Exception(
                            "Only JPG, PNG and WEBP images are allowed."
                        );
                    }


                    /*
                     * GET OLD IMAGE
                     */

                    $old_stmt = $conn->prepare(
                        "SELECT image
                         FROM product_variations
                         WHERE id = ?
                         AND product_id = ?"
                    );

                    $variation_id =
                        (int)$variation_id;

                    $old_stmt->bind_param(
                        "ii",
                        $variation_id,
                        $product_id
                    );

                    $old_stmt->execute();

                    $old_result =
                        $old_stmt->get_result();

                    $old_variation =
                        $old_result->fetch_assoc();

                    $old_stmt->close();


                    /*
                     * CREATE NEW IMAGE
                     */

                    $extension = strtolower(
                        pathinfo(
                            $_FILES["variation_image"]["name"][$variation_id],
                            PATHINFO_EXTENSION
                        )
                    );

                    $new_image =
                        uniqid("product_", true)
                        . "." . $extension;

                    $new_image_path =
                        $upload_dir . $new_image;

                    if (!move_uploaded_file(
                        $tmp_name,
                        $new_image_path
                    )) {
                        throw new Exception(
                            "Failed to upload colour image."
                        );
                    }

                    $new_files[] =
                        $new_image_path;


                    /*
                     * UPDATE IMAGE DATABASE
                     */

                    $image_stmt = $conn->prepare(
                        "UPDATE product_variations
                         SET image = ?
                         WHERE id = ?
                         AND product_id = ?"
                    );

                    $image_stmt->bind_param(
                        "sii",
                        $new_image,
                        $variation_id,
                        $product_id
                    );

                    if (!$image_stmt->execute()) {
                        throw new Exception(
                            "Failed to update colour image."
                        );
                    }

                    $image_stmt->close();


                    /*
                     * REMEMBER OLD IMAGE
                     */

                    if (
                        $old_variation &&
                        !empty($old_variation["image"])
                    ) {

                        $old_files[] =
                            $upload_dir .
                            $old_variation["image"];
                    }
                }
            }


            /*
             * SAVE EVERYTHING
             */

            $conn->commit();


            /*
             * DELETE OLD IMAGES
             */

            foreach ($old_files as $old_file) {

                if (
                    file_exists($old_file) &&
                    !in_array($old_file, $new_files)
                ) {
                    unlink($old_file);
                }
            }


            /*
             * REDIRECT
             */

            header(
                "Location: edit-product.php?id="
                . $product_id
                . "&updated=1"
            );

            exit;


        } catch (Exception $e) {

            $conn->rollback();


            /*
             * DELETE NEW FILES IF UPDATE FAILED
             */

            foreach ($new_files as $new_file) {

                if (file_exists($new_file)) {
                    unlink($new_file);
                }
            }

            $error = $e->getMessage();
        }
    }
}


/*
 * SUCCESS MESSAGE
 */

if (isset($_GET["updated"])) {
    $message = "Product updated successfully!";
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Edit 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: 22px 30px;
        }

        header h2 {
            font-size: 28px;
        }

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

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

        h1 {
            font-size: 38px;
            margin-bottom: 25px;
        }

        .message {
            background: #e7f7e7;
            color: #187a18;
            padding: 14px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

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

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

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

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

        .current-image {
            margin-bottom: 20px;
        }

        .current-image img {
            width: 180px;
            height: 180px;
            object-fit: cover;
            border-radius: 10px;
            border: 1px solid #ddd;
        }

        .section-title {
            font-size: 25px;
            margin: 25px 0 15px;
        }

        .variation {
            border: 1px solid #ddd;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 18px;
            background: #fafafa;
        }

        .variation-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
        }

        .variation-image {
            width: 130px;
            height: 130px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .add-colour-btn {
            width: 100%;
            padding: 14px;
            background: #111;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 17px;
            font-weight: bold;
            cursor: pointer;
            margin-bottom: 10px;
        }

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

        .remove-colour-btn {
            width: 100%;
            padding: 11px;
            background: #c00000;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 15px;
            cursor: pointer;
            margin-top: 5px;
        }

        .remove-colour-btn:hover {
            background: #8f0000;
        }

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

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

    </style>

</head>

<body>

<header>

    <h2>MUTHU JEWELLERS</h2>

</header>


<div class="container">

    <a href="products.php" class="back">
        ← Back to Products
    </a>

    <h1>
        Edit Product ✏️
    </h1>


    <?php if ($message): ?>

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

    <?php endif; ?>


    <?php if ($error): ?>

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

    <?php endif; ?>


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


        <label>Product Name *</label>

        <input
            type="text"
            name="name"
            value="<?php echo htmlspecialchars($product["name"]); ?>"
            required
        >


        <label>Category *</label>

        <select name="category" required>

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

            <option
                value="Rings"
                <?php
                if ($product["category"] === "Rings")
                    echo "selected";
                ?>
            >
                Rings
            </option>

            <option
                value="Necklaces"
                <?php
                if ($product["category"] === "Necklaces")
                    echo "selected";
                ?>
            >
                Necklaces
            </option>

            <option
                value="Earrings"
                <?php
                if ($product["category"] === "Earrings")
                    echo "selected";
                ?>
            >
                Earrings
            </option>

            <option
                value="Bracelets"
                <?php
                if ($product["category"] === "Bracelets")
                    echo "selected";
                ?>
            >
                Bracelets
            </option>

            <option
                value="Pendants"
                <?php
                if ($product["category"] === "Pendants")
                    echo "selected";
                ?>
            >
                Pendants
            </option>

            <option
                value="Other"
                <?php
                if ($product["category"] === "Other")
                    echo "selected";
                ?>
            >
                Other
            </option>

        </select>


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

        <input
            type="number"
            name="price"
            step="0.01"
            min="0"
            value="<?php echo htmlspecialchars($product["price"]); ?>"
            required
        >


        <label>Description</label>

        <textarea name="description"><?php
            echo htmlspecialchars($product["description"]);
        ?></textarea>


        <label>Product Code *</label>

        <input
            type="text"
            name="product_code"
            value="<?php echo htmlspecialchars($product["product_code"]); ?>"
            required
        >


        <label>Current Main Photo</label>

        <div class="current-image">

            <img
                src="../assets/images/<?php
                    echo htmlspecialchars($product["image"]);
                ?>"
                alt="Product Image"
            >

        </div>


        <label>Change Main Photo (Optional)</label>

        <input
            type="file"
            name="main_image"
            accept="image/jpeg,image/png,image/webp"
        >


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


        <div id="variations">

            <?php if (!empty($variations)): ?>

                <?php foreach ($variations as $index => $variation): ?>

                    <div class="variation">

                        <div class="variation-title">
                            Colour <?php echo $index + 1; ?>
                        </div>


                        <label>Colour *</label>

                        <input
                            type="text"
                            name="variation_colour[<?php
                                echo $variation["id"];
                            ?>]"
                            value="<?php
                                echo htmlspecialchars(
                                    $variation["colour"]
                                );
                            ?>"
                            required
                        >


                        <label>Stock *</label>

                        <input
                            type="number"
                            name="variation_stock[<?php
                                echo $variation["id"];
                            ?>]"
                            min="0"
                            value="<?php
                                echo (int)$variation["stock"];
                            ?>"
                            required
                        >


                        <label>Current Colour Photo</label>

                        <?php if (!empty($variation["image"])): ?>

                            <img
                                class="variation-image"
                                src="../assets/images/<?php
                                    echo htmlspecialchars(
                                        $variation["image"]
                                    );
                                ?>"
                                alt="<?php
                                    echo htmlspecialchars(
                                        $variation["colour"]
                                    );
                                ?>"
                            >

                        <?php endif; ?>


                        <label>
                            Change Colour Photo (Optional)
                        </label>

                        <input
                            type="file"
                            name="variation_image[<?php
                                echo $variation["id"];
                            ?>]"
                            accept="image/jpeg,image/png,image/webp"
                        >

                    </div>

                <?php endforeach; ?>

            <?php else: ?>

                <p>
                    No colour variations found.
                </p>

            <?php endif; ?>

        </div>


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


        <button
            type="submit"
            class="save-btn"
        >
            Save Changes 💾
        </button>

    </form>

</div>


<script>

let newVariationCount = 0;

function addVariation() {

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

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

    variation.className = "variation";

    const index =
        newVariationCount++;

    variation.innerHTML = `

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

        <label>Colour *</label>

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

        <label>Stock *</label>

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

        <label>Colour Photo *</label>

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

        <button
            type="button"
            class="remove-colour-btn"
            onclick="this.parentElement.remove()"
        >
            Remove Colour
        </button>

    `;

    container.appendChild(variation);
}

</script>

</body>

</html>