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

/**
 * Params
 */
$context = $_GET['context'] ?? 'backend'; // backend | frontend
$id      = isset($_GET['id']) ? (int)$_GET['id'] : null;
$slug    = $_GET['slug'] ?? null;

if (!$id && !$slug) {
    Response::error('id or slug is required', 422);
}

/**
 * Conditions
 */
$where  = [];
$params = [];

if ($id) {
    $where[]      = 'p.id = :id';
    $params['id'] = $id;
}

if ($slug) {
    $where[]        = 'p.slug = :slug';
    $params['slug'] = $slug;
}

/**
 * Frontend visibility rules
 */
if ($context === 'frontend') {
    $where[] = "p.status = 'Active'";
    $where[] = "p.approval_status = 'Approved'";
    $where[] = "p.published_at <= NOW()";
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

/**
 * Fetch page (core + SEO)
 */
$sql = "
SELECT
    p.id,
    p.title,
    p.slug,
    p.page_type,
    p.template,
    p.short_description,
    p.content,
    p.sections,

    p.show_in_menu,
    p.menu_title,
    p.menu_order,
    p.parent_page_id,

    p.status,
    p.approval_status,
    p.published_at,
    p.created_at,

    seo.meta_title,
    seo.meta_description,
    seo.meta_keywords,
    seo.canonical_url,
    seo.seo_schema,
    seo.ai_seo_content,

    (
        SELECT image_path
        FROM page_images
        WHERE page_id = p.id AND status = 'Active'
        ORDER BY is_primary DESC
        LIMIT 1
    ) AS featured_image

FROM pages p
LEFT JOIN page_seo seo ON seo.page_id = p.id
$whereSql
LIMIT 1
";

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

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

/**
 * Decode sections JSON
 */
$page['sections'] = $page['sections'] ? json_decode($page['sections'], true) : null;

/**
 * Fetch inline images
 */
$stmt = $db->prepare("
    SELECT image_path, alt_text, caption, sort_order
    FROM page_images
    WHERE page_id = :page_id
      AND status = 'Active'
      AND is_primary = 0
    ORDER BY sort_order ASC, id ASC
");
$stmt->execute(['page_id' => $page['id']]);
$inlineImages = $stmt->fetchAll();

/**
 * Increment view count (frontend only)
 */
if ($context === 'frontend') {
    $db->prepare("
        UPDATE pages
        SET view_count = view_count + 1,
            last_viewed_at = NOW()
        WHERE id = :id
    ")->execute(['id' => $page['id']]);
}

/**
 * Response
 */
Response::success('Page fetched successfully', [
    'page' => $page,
    'images' => [
        'featured' => $page['featured_image'],
        'inline'   => $inlineImages
    ]
]);
