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

/**
 * Required fields
 */
Validator::required($data, [
    'title',
    'content'
]);

$title   = trim($data['title']);
$content = trim($data['content']);

/**
 * Optional fields
 */
$pageType        = $data['page_type'] ?? 'static';
$template        = $data['template'] ?? 'default';
$shortDesc       = $data['short_description'] ?? null;
$sections        = $data['sections'] ?? null;
$showInMenu      = (int)($data['show_in_menu'] ?? 0);
$menuTitle       = $data['menu_title'] ?? null;
$menuOrder       = $data['menu_order'] ?? null;
$parentPageId    = $data['parent_page_id'] ?? null;
$isSystemPage    = (int)($data['is_system_page'] ?? 0);
$isIndexable     = (int)($data['is_indexable'] ?? 1);

/**
 * Generate slug (central + fixed)
 */
$slug = Slug::make($title);

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

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

/**
 * Validate parent page (if provided)
 */
if ($parentPageId) {
    Validator::int($parentPageId, 'parent_page_id');

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

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

/**
 * Insert page
 */
$stmt = $db->prepare("
    INSERT INTO pages (
        title,
        slug,
        page_type,
        template,
        short_description,
        content,
        sections,
        show_in_menu,
        menu_title,
        menu_order,
        parent_page_id,
        is_system_page,
        is_indexable,
        status,
        approval_status,
        created_by,
        created_at
    ) VALUES (
        :title,
        :slug,
        :page_type,
        :template,
        :short_description,
        :content,
        :sections,
        :show_in_menu,
        :menu_title,
        :menu_order,
        :parent_page_id,
        :is_system_page,
        :is_indexable,
        'Draft',
        'Pending',
        :created_by,
        NOW()
    )
");

$stmt->execute([
    'title'            => $title,
    'slug'             => $slug,
    'page_type'        => $pageType,
    'template'         => $template,
    'short_description'=> $shortDesc,
    'content'          => $content,
    'sections'         => $sections ? json_encode($sections) : null,
    'show_in_menu'     => $showInMenu,
    'menu_title'       => $menuTitle,
    'menu_order'       => $menuOrder,
    'parent_page_id'   => $parentPageId,
    'is_system_page'   => $isSystemPage,
    'is_indexable'     => $isIndexable,
    'created_by'       => $_SESSION['employee_id']
]);

$pageId = (int)$db->lastInsertId();

Response::success('Page created successfully', [
    'page_id' => $pageId,
    'slug'    => $slug
]);
