<?php
declare(strict_types=1);

/** @return list<array{id:string,label:string,url:string,sort:int}> */
function menu_defaults(): array
{
    return [
        [
            'id' => 'm_home',
            'label' => 'Ana Sayfa',
            'url' => 'index.php',
            'sort' => 10,
        ],
        [
            'id' => 'm_shop',
            'label' => 'Mağaza',
            'url' => 'magaza.php',
            'sort' => 20,
        ],
    ];
}

/** @return list<array<string,mixed>> */
function menu_items(): array
{
    $items = store_read('menu');
    if (!$items) {
        $items = menu_defaults();
        store_write('menu', $items);
    }

    usort($items, static function (array $a, array $b): int {
        return ((int) ($a['sort'] ?? 0)) <=> ((int) ($b['sort'] ?? 0));
    });

    return array_values($items);
}

function menu_find(string $id): ?array
{
    foreach (menu_items() as $item) {
        if ((string) ($item['id'] ?? '') === $id) {
            return $item;
        }
    }
    return null;
}

function menu_href(string $url): string
{
    $url = trim($url);
    if ($url === '') {
        return url('index.php');
    }
    if (preg_match('#^https?://#i', $url) || str_starts_with($url, 'mailto:') || str_starts_with($url, 'tel:')) {
        return $url;
    }
    return url(ltrim($url, '/'));
}

function menu_slugify(string $text): string
{
    $map = [
        'ş' => 's', 'Ş' => 's', 'ı' => 'i', 'İ' => 'i', 'ğ' => 'g', 'Ğ' => 'g',
        'ü' => 'u', 'Ü' => 'u', 'ö' => 'o', 'Ö' => 'o', 'ç' => 'c', 'Ç' => 'c',
    ];
    $text = strtr(trim($text), $map);
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text) ?? '';
    return trim($text, '-') ?: 'sayfa';
}

/** @return list<array<string,mixed>> */
function pages_all(): array
{
    return store_read('pages');
}

function page_find(string $id): ?array
{
    return store_find('pages', $id);
}

function page_find_by_slug(string $slug): ?array
{
    $slug = trim($slug);
    if ($slug === '') {
        return null;
    }
    foreach (pages_all() as $page) {
        if ((string) ($page['slug'] ?? '') === $slug) {
            return $page;
        }
    }
    return null;
}

function page_public_url(array $page): string
{
    $slug = (string) ($page['slug'] ?? '');
    return 'sayfa.php?s=' . rawurlencode($slug);
}

function save_page_image_upload(array $file): string|false
{
    $dir = BASE_PATH . '/uploads/pages';
    $name = save_uploaded_image($file, $dir, 'pg_');
    return $name !== false ? $name : false;
}

function page_image_url(string $filename): string
{
    $filename = ltrim($filename, '/');
    return url('uploads/pages/' . $filename);
}

/** Tehlikeli etiketleri temizleyerek HTML’e izin ver (sadece admin içeriği). */
function page_sanitize_html(string $html): string
{
    $allowed = '<p><br><br/><h1><h2><h3><h4><h5><h6><strong><b><em><i><u><s><a><img>'
        . '<ul><ol><li><blockquote><hr><div><span><table><thead><tbody><tr><th><td>'
        . '<figure><figcaption><pre><code><section><article>';
    $html = strip_tags($html, $allowed);
    $html = preg_replace('/\s+on\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html) ?? $html;
    $html = preg_replace('/\s(href|src)\s*=\s*([\'"])\s*javascript:[^\'"]*\2/i', ' $1="#"', $html) ?? $html;
    return $html;
}

/** Sayfa gövdesini bas — HTML veya düz metin. */
function page_render_body(array $page): string
{
    $body = (string) ($page['body'] ?? '');
    if ($body === '') {
        return '';
    }
    $format = (string) ($page['format'] ?? '');
    $looksHtml = $format === 'html' || (bool) preg_match('/<[a-z][\s\S]*>/i', $body);
    if ($looksHtml) {
        return page_sanitize_html($body);
    }
    return nl2br(e($body), false);
}
