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

$id = intval($_POST['id']);
$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'] ?? 'inactive';

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

$stmt = mysqli_prepare($conn,
"UPDATE sorting_groups
 SET category_id=?, 
     subcategory_id=?, 
     name=?, 
     sort_order=?, 
     status=?
 WHERE id=?");

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

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