<?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();

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

if (empty($data['page_id']) || !filter_var($data['page_id'], FILTER_VALIDATE_INT)) {
    Response::error('Valid page_id is required', 422);
}

$pageId = (int)$data['page_id'];

/**
 * Role check — Admin & Super Admin only
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetchColumn();

if (!in_array($role, ['Super Admin', 'Admin'], true)) {
    Response::error('You are not authorized to approve pages', 403);
}

/**
 * Check page exists
 */
$stmt = $db->prepare("
    SELECT id, approval_status
    FROM pages
    WHERE id = :id
");
$stmt->execute(['id' => $pageId]);
$page = $stmt->fetch();

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

if ($page['approval_status'] === 'Approved') {
    Response::error('Page is already approved', 409);
}

/**
 * Approve page
 */
$stmt = $db->prepare("
    UPDATE pages
    SET
        approval_status = 'Approved',
        status = 'Active',
        published_at = NOW(),
        approved_by = :approved_by,
        rejected_by = NULL,
        rejection_reason = NULL
    WHERE id = :id
");
$stmt->execute([
    'approved_by' => $_SESSION['employee_id'],
    'id'          => $pageId
]);

Response::success('Page approved successfully');
