<?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'];

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

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

if ($page['status'] === 'InActive') {
    Response::error('Page is already inactive', 409);
}

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

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