<?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();
$data = json_decode(file_get_contents('php://input'), true);

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

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

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

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

if (!in_array($role, ['Admin', 'Super Admin'], true)) {
    Response::error('Unauthorized', 403);
}

/**
 * Page exists
 */
$stmt = $db->prepare("SELECT id FROM pages WHERE id = :id");
$stmt->execute(['id' => $pageId]);
if (!$stmt->fetch()) {
    Response::error('Page not found', 404);
}

/**
 * Update status
 */
$stmt = $db->prepare("
    UPDATE pages
    SET status = :status,
        updated_by = :updated_by,
        updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'status'     => $status,
    'updated_by'=> $_SESSION['employee_id'],
    'id'         => $pageId
]);

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