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

$conn->begin_transaction();

try {

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

    // ---------- SLUG ----------
    $slug = generateSlug($_POST['name']);

    // ---------- IMAGE UPLOAD ----------
    $uploadDir = "../uploads/products/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    // Featured image
    $featuredImage = '';
    if (!empty($_FILES['featured_image']['name'])) {
        $ext = pathinfo($_FILES['featured_image']['name'], PATHINFO_EXTENSION);
        $featuredImage = uniqid() . '.' . $ext;
        move_uploaded_file(
            $_FILES['featured_image']['tmp_name'],
            $uploadDir . $featuredImage
        );
    }

    // ---------- PRODUCT INSERT ----------
   $stmt = $conn->prepare("
INSERT INTO products 
(category_id, subcategory_id, name, slug, description, base_price, featured_image, requires_machinery, no_sorting)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");

    

$category_id = (int) $_POST['category_id'];
$name = $_POST['name'];
$description = $_POST['description'] ?? '';
$requires_machinery = isset($_POST['requires_machinery']) ? 1 : 0;
$no_sorting = isset($_POST['no_sorting']) ? 1 : 0;
$base_price = floatval($_POST['base_price'] ?? 0);
$subcategory_id = !empty($_POST['subcategory_id']) 
                    ? intval($_POST['subcategory_id']) 
                    : 0; // use 0 instead of NULL



$stmt->bind_param(
    "iisssdsii",
    $category_id,
    $subcategory_id,
    $name,
    $slug,
    $description,
    $base_price,
    $featuredImage,
    $requires_machinery,
    $no_sorting
);


    $stmt->execute();
    $product_id = $stmt->insert_id;

    // ---------- GALLERY ----------
    // ---------- GALLERY (OPTIONAL) ----------
if (isset($_FILES['gallery_images']) && !empty($_FILES['gallery_images']['name'][0])) {

    $g = $conn->prepare("
        INSERT INTO product_images (product_id, image)
        VALUES (?, ?)
    ");

    foreach ($_FILES['gallery_images']['name'] as $key => $name) {

        if (empty($name)) continue;

        $tmpName = $_FILES['gallery_images']['tmp_name'][$key];
        $fileSize = $_FILES['gallery_images']['size'][$key];

        // Skip invalid uploads
        if (!is_uploaded_file($tmpName)) continue;

        // Validate extension
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        if (!in_array($ext, $allowed)) continue;

        // Optional: limit size (5MB)
        if ($fileSize > 5 * 1024 * 1024) continue;

        $newName = uniqid('gallery_') . '.' . $ext;

        move_uploaded_file(
            $tmpName,
            $uploadDir . $newName
        );

        $g->bind_param("is", $product_id, $newName);
        $g->execute();
    }
}


    // ---------- SORTING MAP ----------
    if (!empty($_POST['sorting'])) {
        $map = $conn->prepare("
            INSERT INTO product_sorting_map (product_id, sorting_option_id)
            VALUES (?, ?)
        ");

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

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

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

  

    if (!$v) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    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) {
            throw new Exception("Variant group ID missing");
        }

        $v->bind_param("iisds",
            $product_id,
            $group_id,
            $label,
            $price,
            $unit
        );
        //   throw new Exception("Trying to insert group ID: " . $group_id);

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

    // ---------- ADDONS ----------
    if (!empty($_POST['addon_name'])) {
        $a = $conn->prepare("
            INSERT INTO product_addons
            (product_id, name, price, unit)
            VALUES (?, ?, ?, ?)
        ");

        foreach ($_POST['addon_name'] as $i => $name) {
            if (!$name) continue;

            $price = $_POST['addon_price'][$i];
            $unit  = $_POST['addon_unit'][$i];

            $a->bind_param("isds", $product_id, $name, $price, $unit);
            $a->execute();
        }
    }

    $conn->commit();

    echo json_encode([
        "status" => "success",
        "message" => "Product saved successfully"
    ]);

} catch (Exception $e) {

    $conn->rollback();

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