<?php
include 'db.php';
header('Content-Type: application/json');

$category_id = intval($_POST['category_id']);
$subcategory_id = !empty($_POST['subcategory_id']) 
                    ? intval($_POST['subcategory_id']) 
                    : NULL;
$name = mysqli_real_escape_string($conn,$_POST['name']);
$unit = mysqli_real_escape_string($conn,$_POST['unit']);
$required = intval($_POST['required']);
$sort = intval($_POST['sort_order']);

$subcategory_sql = $subcategory_id !== NULL ? $subcategory_id : "NULL";

$q = mysqli_query($conn,"
INSERT INTO variant_groups
(category_id, subcategory_id, name, unit, required, sort_order)
VALUES
($category_id, $subcategory_sql, '$name', '$unit', $required, $sort)
");

echo json_encode([
'status'=>$q?'success':'error',
'message'=>$q?'Variant added':'Insert failed'
]);
