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

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

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

$id = intval($_GET['id'] ?? 0);

if (!$id) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid category ID"]);
    exit;
}

// Check if there are any menu items in this category
$check = $conn->prepare("SELECT COUNT(*) as count FROM menu_items WHERE category_id = ?");
$check->bind_param("i", $id);
$check->execute();
$result = $check->get_result();
$row = $result->fetch_assoc();
$check->close();

if ($row['count'] > 0) {
    http_response_code(400);
    echo json_encode([
        "error" => "Cannot delete category",
        "message" => "This category contains {$row['count']} menu item(s). Please remove or reassign them first before deleting the category."
    ]);
    exit;
}

// Safe to delete - no items in this category
$deleteResult = $conn->query("DELETE FROM menu_categories WHERE id = $id");

if ($deleteResult) {
    echo json_encode(["success" => true, "message" => "Category deleted"]);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to delete category"]);
}
