<?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['tag_id'])) {
    Response::error('tag_id is required', 422);
}

$tagId = (int)$data['tag_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->fetchColumn();

if ($role !== 'Super Admin') {
    Response::error('Only Super Admin can delete tags', 403);
}

/**
 * Exists check
 */
$stmt = $db->prepare("SELECT id FROM blog_tags WHERE id = :id");
$stmt->execute(['id' => $tagId]);
if (!$stmt->fetch()) {
    Response::error('Tag not found', 404);
}

/**
 * Usage check (many-to-many)
 */
$stmt = $db->prepare("
    SELECT COUNT(*) FROM blog_tag_map WHERE tag_id = :id
");
$stmt->execute(['id' => $tagId]);

if ((int)$stmt->fetchColumn() > 0) {
    Response::error('Tag is assigned to blogs and cannot be deleted', 422);
}

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

Response::success('Blog tag deleted permanently');
