<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../security/auth_guard.php';
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../core/Response.php';

$db = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

if (empty($data['category_id'])) {
    Response::error('category_id is required', 422);
}

$categoryId = (int)$data['category_id'];

/**
 * Role check — Super Admin only
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetch();

if (!$role || $role['name'] !== 'Super Admin') {
    Response::error('Only Super Admin can delete FAQ categories', 403);
}

/**
 * Usage check
 */
$stmt = $db->prepare("
    SELECT COUNT(*) FROM faq_category_map WHERE category_id = :id
");
$stmt->execute(['id' => $categoryId]);

if ((int)$stmt->fetchColumn() > 0) {
    Response::error('FAQ category is in use and cannot be deleted', 422);
}

/**
 * Delete
 */
$stmt = $db->prepare("DELETE FROM faq_categories WHERE id = :id");
$stmt->execute(['id' => $categoryId]);

Response::success('FAQ category deleted permanently');
