<?php
require 'db.php';
error_reporting(-1);

$conn->begin_transaction();

try {

    $id = (int)$_POST['id'];

    function generateSlug($string) {
        return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)));
    }

    $name = $_POST['name'];
    $slug = generateSlug($name);
    $category_id = (int)$_POST['category_id'];
  $subcategory_id = !empty($_POST['subcategory_id']) 
                  ? intval($_POST['subcategory_id']) 
                  : 0;
    $description = $_POST['description'] ?? '';
    $requires = isset($_POST['requires_machinery']) ? 1 : 0;
    $no_sorting = isset($_POST['no_sorting']) ? 1 : 0;
    $base_price = floatval($_POST['base_price'] ?? 0);

    // =========================
    // UPDATE PRODUCT
    // =========================
    $stmt = $conn->prepare("
       UPDATE products SET
    name=?,
    slug=?,
    category_id=?,
    subcategory_id=?,
    description=?,
    base_price=?,
    requires_machinery=?,
    no_sorting=?
WHERE id=?
    ");

$stmt->bind_param(
    "ssiisdiii",
    $name,
    $slug,
    $category_id,
    $subcategory_id,
    $description,
    $base_price,
    $requires,
    $no_sorting,
    $id
);

    $stmt->execute();


    // =========================
    // FEATURED IMAGE
    // =========================
    if (!empty($_FILES['featured_image']['name'])) {

        $uploadDir = "../uploads/products/";
        $ext = pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION);
        $newName = uniqid().'_'.$id.'.'.$ext;

        move_uploaded_file(
            $_FILES['featured_image']['tmp_name'],
            $uploadDir.$newName
        );

        $imgStmt = $conn->prepare("
            UPDATE products SET featured_image=? WHERE id=?
        ");
        $imgStmt->bind_param("si", $newName, $id);
        $imgStmt->execute();
    }


    // =========================
    // SORTING
    // =========================
    $conn->query("DELETE FROM product_sorting_map WHERE product_id=$id");

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

        $map = $conn->prepare("
            INSERT INTO product_sorting_map (product_id, sorting_option_id)
            VALUES (?, ?)
        ");

        foreach ($_POST['sorting'] as $sid) {
            $sid = (int)$sid;
            $map->bind_param("ii", $id, $sid);
            $map->execute();
        }
    }


    // =========================
    // VARIANTS (SAFE FK)
    // =========================
    $conn->query("DELETE FROM product_variants WHERE product_id=$id");

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

        $v = $conn->prepare("
            INSERT INTO product_variants
            (product_id, variant_group_id, label, price, unit, status)
            VALUES (?, ?, ?, ?, ?, 'active')
        ");

        foreach ($_POST['variant_label'] as $i => $label) {

            if (!$label) continue;

            $group_id = intval($_POST['variant_group_id'][$i] ?? 0);
            $price = floatval($_POST['variant_price'][$i] ?? 0);
            $unit = $_POST['variant_unit'][$i] ?? '';

            if ($group_id <= 0) continue;

            $v->bind_param(
                "iisds",
                $id,
                $group_id,
                $label,
                $price,
                $unit
            );

            if (!$v->execute()) {
                throw new Exception("Variant insert failed: " . $v->error);
            }
        }
    }


    // =========================
    // ADDONS
    // =========================
    $conn->query("DELETE FROM product_addons WHERE product_id=$id");

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

        $a = $conn->prepare("
            INSERT INTO product_addons
            (product_id, name, price, unit)
            VALUES (?, ?, ?, ?)
        ");

        foreach ($_POST['addon_name'] as $i => $addonName) {

            $addonName = trim($addonName);
            if (!$addonName) continue;

            $price = floatval($_POST['addon_price'][$i] ?? 0);
            $unit = $_POST['addon_unit'][$i] ?? '';

            $a->bind_param("isds", $id, $addonName, $price, $unit);
            $a->execute();
        }
    }


    $conn->commit();

    echo json_encode([
        'status' => 'success',
        'message' => 'Product updated successfully'
    ]);

} catch (Exception $e) {

    $conn->rollback();

    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}