<?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/Validator.php';

$db = Database::getInstance();

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

Validator::required($data, ['page_id', 'reason']);

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

Validator::minLength($reason, 5, 'reason');

/**
 * 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 reject 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'] === 'Rejected') {
    Response::error('Page is already rejected', 409);
}

/**
 * Reject page
 */
$stmt = $db->prepare("
    UPDATE pages
    SET
        approval_status = 'Rejected',
        status = 'Draft',
        rejected_by = :rejected_by,
        rejection_reason = :reason
    WHERE id = :id
");
$stmt->execute([
    'rejected_by' => $_SESSION['employee_id'],
    'reason'      => $reason,
    'id'          => $pageId
]);

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