<?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 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 approve blogs', 403);
}

/**
 * Fetch blog
 */
$stmt = $db->prepare("
    SELECT id, content, 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('Blog is not in pending state', 422);
}

if (trim($blog['content']) === '') {
    Response::error('Blog content cannot be empty', 422);
}

/**
 * Validate featured image
 */
$stmt = $db->prepare("
    SELECT COUNT(*) FROM blog_images
    WHERE blog_id = :id AND is_primary = 1 AND status = 'Active'
");
$stmt->execute(['id' => $blogId]);

if ((int)$stmt->fetchColumn() === 0) {
    Response::error('Featured image is required for approval', 422);
}

/**
 * Validate SEO
 */
$stmt = $db->prepare("
    SELECT meta_title, meta_description
    FROM blog_seo
    WHERE blog_id = :id
");
$stmt->execute(['id' => $blogId]);
$seo = $stmt->fetch();

if (!$seo || (empty($seo['meta_title']) && empty($seo['meta_description']))) {
    Response::error('SEO meta title or description is required', 422);
}

/**
 * Approve & publish blog
 */
$stmt = $db->prepare("
    UPDATE blogs
    SET
        approval_status = 'Approved',
        status = 'Active',
        published_at = NOW(),
        approved_by = :approved_by,
        approved_at = NOW(),
        updated_at = NOW()
    WHERE id = :id
");

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

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

Response::success('Blog approved and published successfully');
