<?php
include 'db.php';

header('Content-Type: application/json');

$id = intval($_POST['id'] ?? 0);
$sorting_group_id = intval($_POST['sorting_group_id'] ?? 0);
$name = trim($_POST['name'] ?? '');
$sort_order = intval($_POST['sort_order'] ?? 0);
$status = trim($_POST['status'] ?? '');

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

$stmt = mysqli_prepare($conn, "
    UPDATE sorting_options
    SET sorting_group_id=?,
        name=?,
        sort_order=?,
        status=?
    WHERE id=?
");

mysqli_stmt_bind_param(
    $stmt,
    "isisi",
    $sorting_group_id,
    $name,
    $sort_order,
    $status,
    $id
);

if (mysqli_stmt_execute($stmt)) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Sorting option updated successfully'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => mysqli_error($conn) // 🔥 shows real reason
    ]);
}
