<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

include('../../includes/config.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $id = (int) $_POST['id'];

    // Check if category exists
    $check = $conn->prepare("SELECT id FROM categories WHERE id = ?");
    $check->bind_param("i", $id);
    $check->execute();
    $check->store_result();

    if ($check->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Category not found.']);
        exit;
    }
    $check->close();

    // Proceed to delete
    $delete = $conn->prepare("DELETE FROM categories WHERE id = ?");
    $delete->bind_param("i", $id);

    if ($delete->execute()) {
        echo json_encode(['success' => true, 'message' => 'Category deleted successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting category.']);
    }
    $delete->close();
    $conn->close();
}
?>
