<?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 = trim($_POST['name']);
$sort = intval($_POST['sort_order'] ?? 1);
$status = $_POST['status'] ?? 'active';

if(!$category_id || !$name){
    echo json_encode(['status'=>'error','message'=>'Missing data']);
    exit;
}

$stmt = mysqli_prepare($conn,
"INSERT INTO sorting_groups (category_id,subcategory_id,name,sort_order,status)
 VALUES (?,?,?,?,?)");

mysqli_stmt_bind_param($stmt,"iisis",
    $category_id,
    $subcategory_id,
    $name,
    $sort,
    $status
);

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