<?php
declare(strict_types=1);

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

$db = Database::getInstance();

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

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

$blogId = (int)$data['blog_id'];

/**
 * Role check: Super Admin, Admin, SEO Manager only
 */
$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']]);
$role = $stmt->fetch();

if (!$role || !in_array($role['name'], ['Super Admin', 'Admin', 'SEO Manager'], true)) {
    Response::error('You are not authorized to delete blogs', 403);
}

/**
 * Ensure blog exists
 */
$stmt = $db->prepare("SELECT id, title FROM blogs WHERE id = :id");
$stmt->execute(['id' => $blogId]);
$blog = $stmt->fetch();

if (!$blog) {
    Response::error('Blog not found', 404);
}

/**
 * Permanent delete
 * (Assumes FK constraints or manual cleanup elsewhere)
 */
$stmt = $db->prepare("DELETE FROM blogs WHERE id = :id");
$stmt->execute(['id' => $blogId]);

Logger::auth('Blog permanently deleted', [
    'blog_id' => $blogId,
    'title'   => $blog['title'],
    'by'      => $_SESSION['employee_id']
]);

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