<?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']) || empty($data['rejection_reason'])) {
    Response::error('blog_id and rejection_reason are required', 422);
}

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

/**
 * Role check: Super Admin / Admin 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'], true)) {
    Response::error('You are not authorized to reject blogs', 403);
}

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

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

if ($blog['approval_status'] !== 'Pending') {
    Response::error('Only pending blogs can be rejected', 422);
}

/**
 * Reject blog
 */
$stmt = $db->prepare("
    UPDATE blogs
    SET
        approval_status  = 'Rejected',
        status           = 'Draft',
        rejection_reason = :reason,
        rejected_by      = :rejected_by,
        rejected_at      = NOW(),
        updated_at       = NOW()
    WHERE id = :id
");

$stmt->execute([
    'reason'      => $reason,
    'rejected_by' => $_SESSION['employee_id'],
    'id'          => $blogId
]);

Logger::auth('Blog rejected', [
    'blog_id' => $blogId,
    'reason'  => $reason,
    'by'      => $_SESSION['employee_id']
]);

Response::success('Blog rejected successfully');
