<?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();

/**
 * 🔐 Fetch logged-in user's role
 * (role is NOT stored in session)
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :employee_id
");
$stmt->execute([
    'employee_id' => $_SESSION['employee_id']
]);

$userRole = $stmt->fetchColumn();

/**
 * 🚫 Permission check
 */
$allowedRoles = ['Super Admin', 'Admin', 'Manager'];

if (!in_array($userRole, $allowedRoles, true)) {
    Response::error('You are not authorized to delete categories', 403);
}

/**
 * 📥 Read JSON payload
 */
$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'];

/**
 * 🔍 Check category exists
 */
$stmt = $db->prepare("SELECT id FROM blog_categories WHERE id = :id");
$stmt->execute(['id' => $categoryId]);

if (!$stmt->fetch()) {
    Response::error('Category not found', 404);
}

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

Response::success('Blog category deleted successfully');
