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

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

/**
 * Allowed status values
 */
$allowedStatuses = ['Active', 'Draft', 'InActive'];
if (!in_array($newStatus, $allowedStatuses, true)) {
    Response::error('Invalid status value', 422);
}

/**
 * Role check
 * Super Admin, Admin, SEO Manager, Manager
 */
$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();

$allowedRoles = ['Super Admin', 'Admin', 'SEO Manager', 'Manager'];

if (!$role || !in_array($role['name'], $allowedRoles, true)) {
    Response::error('You are not authorized to update blog status', 403);
}

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

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

/**
 * Business rules
 */

// Do not activate rejected blogs
if ($blog['approval_status'] === 'Rejected' && $newStatus === 'Active') {
    Response::error('Rejected blogs cannot be activated', 422);
}

// Do not change status of pending blogs to Active
if ($blog['approval_status'] === 'Pending' && $newStatus === 'Active') {
    Response::error('Pending blogs must be approved before activation', 422);
}

// No-op protection
if ($blog['status'] === $newStatus) {
    Response::success('Status already set');
}

/**
 * Update status
 */
$stmt = $db->prepare("
    UPDATE blogs
    SET
        status = :status,
        updated_by = :updated_by,
        updated_at = NOW()
    WHERE id = :id
");

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

Logger::auth('Blog status updated', [
    'blog_id' => $blogId,
    'from'    => $blog['status'],
    'to'      => $newStatus,
    'by'      => $_SESSION['employee_id']
]);

Response::success('Blog status updated successfully');
