<?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';
require_once __DIR__ . '/../../core/Slug.php';

$db   = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

/**
 * page_id is mandatory
 */
Validator::required($data, ['page_id']);

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

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

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

$fields = [];
$params = ['id' => $pageId];

/**
 * Title update (slug allowed ONLY before publish)
 */
if (!empty($data['title'])) {

    $title = trim($data['title']);
    Validator::minLength($title, 3, 'title');

    if ($page['approval_status'] === 'Approved' && $page['published_at']) {
        Response::error('Slug cannot be changed after page is published', 403);
    }

    $slug = Slug::make($title);

    // Ensure slug uniqueness
    $stmt = $db->prepare("
        SELECT id FROM pages
        WHERE slug = :slug AND id != :id
    ");
    $stmt->execute([
        'slug' => $slug,
        'id'   => $pageId
    ]);

    if ($stmt->fetch()) {
        Response::error('Another page with similar title exists', 409);
    }

    $fields[]        = 'title = :title';
    $fields[]        = 'slug = :slug';
    $params['title'] = $title;
    $params['slug']  = $slug;
}

/**
 * Content
 */
if (isset($data['content'])) {
    $fields[]           = 'content = :content';
    $params['content']  = trim($data['content']);
}

/**
 * Short description
 */
if (isset($data['short_description'])) {
    $fields[]                 = 'short_description = :short_description';
    $params['short_description'] = $data['short_description'];
}

/**
 * Sections (JSON)
 */
if (isset($data['sections'])) {
    $fields[]          = 'sections = :sections';
    $params['sections'] = json_encode($data['sections']);
}

/**
 * Template
 */
if (isset($data['template'])) {
    $fields[]           = 'template = :template';
    $params['template'] = $data['template'];
}

/**
 * Menu controls
 */
if (isset($data['show_in_menu'])) {
    $fields[]               = 'show_in_menu = :show_in_menu';
    $params['show_in_menu'] = (int)$data['show_in_menu'];
}

if (isset($data['menu_title'])) {
    $fields[]             = 'menu_title = :menu_title';
    $params['menu_title'] = $data['menu_title'];
}

if (isset($data['menu_order'])) {
    $fields[]             = 'menu_order = :menu_order';
    $params['menu_order'] = (int)$data['menu_order'];
}

/**
 * Parent page
 */
if (isset($data['parent_page_id'])) {
    if ($data['parent_page_id']) {
        Validator::int($data['parent_page_id'], 'parent_page_id');

        $stmt = $db->prepare("SELECT id FROM pages WHERE id = :id");
        $stmt->execute(['id' => $data['parent_page_id']]);

        if (!$stmt->fetch()) {
            Response::error('Invalid parent page', 422);
        }
    }

    $fields[]                  = 'parent_page_id = :parent_page_id';
    $params['parent_page_id']  = $data['parent_page_id'];
}

/**
 * Indexable
 */
if (isset($data['is_indexable'])) {
    $fields[]               = 'is_indexable = :is_indexable';
    $params['is_indexable'] = (int)$data['is_indexable'];
}

/**
 * Nothing to update
 */
if (empty($fields)) {
    Response::error('No valid fields provided for update', 422);
}

/**
 * Update page
 */
$sql = "
    UPDATE pages
    SET " . implode(', ', $fields) . ",
        updated_by = :updated_by,
        updated_at = NOW()
    WHERE id = :id
";

$params['updated_by'] = $_SESSION['employee_id'];

$stmt = $db->prepare($sql);
$stmt->execute($params);

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