<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit();
}

require_once __DIR__ . '/../db.php';

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$name = isset($_POST['name']) ? trim($_POST['name']) : '';

if (!$id || !$name) {
    http_response_code(400);
    echo json_encode(["error" => "ID and name are required"]);
    exit;
}

// Create slug from name
$slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $name));

$stmt = $conn->prepare("UPDATE menu_categories SET name = ?, slug = ? WHERE id = ?");
$stmt->bind_param("ssi", $name, $slug, $id);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Category updated"]);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to update category"]);
}

$stmt->close();
