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

$name       = trim($_POST['name'] ?? '');
$group_id   = intval($_POST['group_id'] ?? 0);
$sort_order = intval($_POST['sort_order'] ?? 1);
$status     = $_POST['status'] ?? 'active';

/* VALIDATION */
if (!$group_id || $name == '') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Required fields missing'
    ]);
    exit;
}

/* ESCAPE */
$name   = mysqli_real_escape_string($conn, $name);
$status = mysqli_real_escape_string($conn, $status);

/* DUPLICATE CHECK (optional but recommended) */
$check = mysqli_query($conn, "
    SELECT id FROM sorting_options 
    WHERE sorting_group_id = $group_id 
    AND name = '$name'
");

if (mysqli_num_rows($check) > 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Option already exists in this group'
    ]);
    exit;
}

/* INSERT */
$ins = mysqli_query($conn, "
    INSERT INTO sorting_options
    (sorting_group_id, name, sort_order, status)
    VALUES
    ($group_id, '$name', $sort_order, '$status')
");

if ($ins) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Sorting option added successfully'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database insert failed'
    ]);
}
