<?php
declare(strict_types=1);

function wikiSlugOk(string $slug): bool {
    return strlen($slug) <= 80 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) === 1;
}

/** @return list<string> */
function wikiReservedPageSlugs(): array {
    return ['nieuw', 'bewerken', 'categorie'];
}

/** @return list<string> */
function wikiReservedCategorySlugs(): array {
    return ['nieuw'];
}

function wikiSlugify(string $text): string {
    $text = mb_strtolower(trim($text), 'UTF-8');
    $text = strtr($text, [
        'à' => 'a', 'á' => 'a', 'â' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae',
        'ç' => 'c',
        'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
        'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
        'ñ' => 'n',
        'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'ö' => 'o', 'ø' => 'o', 'œ' => 'oe',
        'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u',
        'ý' => 'y', 'ÿ' => 'y', 'ß' => 'ss',
        'ĳ' => 'ij',
    ]);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text) ?? '';
    $text = trim($text, '-');
    if (strlen($text) > 80) $text = rtrim(substr($text, 0, 80), '-');
    return $text;
}

function wikiChooseSlug(mixed $given, string $title, array $reserved): string {
    if ($given === null || $given === '') {
        $slug = wikiSlugify($title);
        if ($slug === '' || in_array($slug, $reserved, true)) {
            throw new AppException('Kies een slug: de titel levert geen bruikbare slug op.');
        }
        return $slug;
    }
    if (!is_string($given) || !wikiSlugOk($given)) {
        throw new AppException('De slug mag alleen kleine letters, cijfers en streepjes bevatten.');
    }
    if (in_array($given, $reserved, true)) throw new AppException('Die slug is gereserveerd.');
    return $given;
}

function wikiOptionalPosition(array $input): ?int {
    if (!array_key_exists('position', $input) || $input['position'] === null) return null;
    $value = $input['position'];
    if (is_string($value) && preg_match('/^[1-9][0-9]{0,4}$/', $value)) $value = (int)$value;
    if (!is_int($value) || $value < 1 || $value > 10000) {
        throw new AppException('De positie moet een geheel getal vanaf 1 zijn.');
    }
    return $value;
}

function wikiNormalizeContent(mixed $value): string {
    if (!is_string($value)) throw new AppException('De tekst moet tekst zijn.');
    $value = str_replace(["\r\n", "\r"], "\n", $value);
    if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value)) throw new AppException('De tekst bevat ongeldige tekens.');
    if (mb_strlen($value) > 100000) throw new AppException('De tekst is te lang (maximaal 100000 tekens).');
    return $value;
}

function wikiCategoryRow(string $slug): array {
    if (!wikiSlugOk($slug)) throw new AppException('Deze categorie bestaat niet.', 404);
    $row = query('SELECT * FROM wiki_categories WHERE slug=?', [$slug])->fetch();
    if (!$row) throw new AppException('Deze categorie bestaat niet.', 404);
    return $row;
}

function wikiPageRow(string $slug): array {
    if (!wikiSlugOk($slug)) throw new AppException('Deze pagina bestaat niet.', 404);
    $row = query('SELECT * FROM wiki_pages WHERE slug=?', [$slug])->fetch();
    if (!$row) throw new AppException('Deze pagina bestaat niet.', 404);
    return $row;
}

function wikiNextCategoryPosition(): int {
    return (int)query('SELECT COALESCE(MAX(position), 0) FROM wiki_categories')->fetchColumn() + 1;
}

function wikiNextPagePosition(int $categoryId): int {
    return (int)query('SELECT COALESCE(MAX(position), 0) FROM wiki_pages WHERE category_id=?', [$categoryId])->fetchColumn() + 1;
}

/** @return list<array{slug:string,title:string,position:int}> */
function wikiPagesInCategory(int $categoryId): array {
    $rows = query('SELECT slug, title, position FROM wiki_pages WHERE category_id=? ORDER BY position, title, slug', [$categoryId])->fetchAll();
    return array_map(fn(array $row): array => [
        'slug' => $row['slug'],
        'title' => $row['title'],
        'position' => (int)$row['position'],
    ], $rows);
}

function wikiCategoryPayload(array $row): array {
    return [
        'slug' => $row['slug'],
        'title' => $row['title'],
        'position' => (int)$row['position'],
        'pages' => wikiPagesInCategory((int)$row['id']),
    ];
}

function wikiHasPages(): bool {
    return (int)query('SELECT COUNT(*) FROM wiki_pages')->fetchColumn() > 0;
}

function wikiVisible(bool $admin): bool {
    return $admin || wikiHasPages();
}

function listWikiCategories(): array {
    $rows = query('SELECT * FROM wiki_categories ORDER BY position, title, slug')->fetchAll();
    return ['categories' => array_map('wikiCategoryPayload', $rows)];
}

function loadWikiCategory(string $slug): array {
    return wikiCategoryPayload(wikiCategoryRow($slug));
}

function createWikiCategory(array $input): array {
    $title = cleanText($input['title'] ?? null, 80, 'De categorietitel');
    $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedCategorySlugs());
    $position = wikiOptionalPosition($input);
    transaction(function () use ($title, $slug, $position): void {
        if (query('SELECT 1 FROM wiki_categories WHERE slug=?', [$slug])->fetchColumn()) {
            throw new AppException('Die slug is al in gebruik.', 409);
        }
        $now = time();
        query('INSERT INTO wiki_categories (slug, title, position, created, updated) VALUES (?,?,?,?,?)', [
            $slug, $title, $position ?? wikiNextCategoryPosition(), $now, $now,
        ]);
    });
    return loadWikiCategory($slug);
}

function updateWikiCategory(string $slug, array $input): array {
    foreach (['title', 'slug', 'position'] as $key) {
        if (array_key_exists($key, $input)) {
            $present = true;
            break;
        }
    }
    if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
    $stored = $slug;
    transaction(function () use ($slug, $input, &$stored): void {
        $row = wikiCategoryRow($slug);
        $title = array_key_exists('title', $input) ? cleanText($input['title'], 80, 'De categorietitel') : $row['title'];
        $newSlug = array_key_exists('slug', $input)
            ? wikiChooseSlug($input['slug'], $title, wikiReservedCategorySlugs())
            : $row['slug'];
        $position = array_key_exists('position', $input) ? wikiOptionalPosition($input) : (int)$row['position'];
        if ($position === null) $position = (int)$row['position'];
        $clash = query('SELECT 1 FROM wiki_categories WHERE slug=? AND id<>?', [$newSlug, $row['id']])->fetchColumn();
        if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
        query('UPDATE wiki_categories SET slug=?, title=?, position=?, updated=? WHERE id=?', [
            $newSlug, $title, $position, time(), $row['id'],
        ]);
        $stored = $newSlug;
    });
    return loadWikiCategory($stored);
}

function deleteWikiCategory(string $slug): string {
    transaction(function () use ($slug): void {
        $row = wikiCategoryRow($slug);
        $count = (int)query('SELECT COUNT(*) FROM wiki_pages WHERE category_id=?', [$row['id']])->fetchColumn();
        if ($count > 0) throw new AppException('Deze categorie heeft nog pagina\'s. Verplaats of verwijder die eerst.', 409);
        query('DELETE FROM wiki_categories WHERE id=?', [$row['id']]);
    });
    return $slug;
}

function wikiPageSummary(array $row): array {
    return [
        'slug' => $row['slug'],
        'title' => $row['title'],
        'position' => (int)$row['position'],
        'updated' => (int)$row['updated'],
        'category' => ['slug' => $row['category_slug'], 'title' => $row['category_title']],
    ];
}

function listWikiPages(?string $categorySlug, ?string $query): array {
    if ($categorySlug !== null && $categorySlug !== '') {
        if (!wikiSlugOk($categorySlug)) throw new AppException('De categorie moet een slug zijn.');
        $category = wikiCategoryRow($categorySlug);
        $rows = query(
            'SELECT p.*, c.slug AS category_slug, c.title AS category_title
             FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
             WHERE p.category_id=? ORDER BY p.position, p.title, p.slug',
            [$category['id']]
        )->fetchAll();
    } else {
        $rows = query(
            'SELECT p.*, c.slug AS category_slug, c.title AS category_title
             FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
             ORDER BY c.position, p.position, p.title, p.slug'
        )->fetchAll();
    }
    $needle = $query === null ? '' : trim($query);
    if ($needle !== '') {
        if (mb_strlen($needle) > 200) throw new AppException('De zoekterm is te lang (maximaal 200 tekens).');
        $folded = mb_strtolower($needle, 'UTF-8');
        $rows = array_values(array_filter($rows, function (array $row) use ($folded): bool {
            return str_contains(mb_strtolower($row['title'], 'UTF-8'), $folded)
                || str_contains(mb_strtolower($row['content'], 'UTF-8'), $folded);
        }));
    }
    return array_map('wikiPageSummary', $rows);
}

/**
 * @return list<array{anchor:string,title:?string,blocks:list<array{inlines:list<array<string,mixed>>}>}>
 */
function parseWikiChapters(string $content): array {
    $content = str_replace(["\r\n", "\r"], "\n", $content);
    $lines = $content === '' ? [] : explode("\n", $content);
    $sections = [];
    $title = null;
    $buffer = [];
    $open = false;
    foreach ($lines as $line) {
        if (preg_match('/^##[ \t]*$/u', $line)) throw new AppException('Een hoofdstuk heeft een titel nodig.');
        if (preg_match('/^##[ \t]+(.*)$/u', $line, $match)) {
            $heading = trim($match[1]);
            if ($heading === '') throw new AppException('Een hoofdstuk heeft een titel nodig.');
            if (mb_strlen($heading) > 200) throw new AppException('Een hoofdstuktitel is te lang (maximaal 200 tekens).');
            if ($open || trim(implode("\n", $buffer)) !== '') {
                $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
            }
            $buffer = [];
            $open = true;
            $title = $heading;
            continue;
        }
        $buffer[] = $line;
    }
    if ($open || trim(implode("\n", $buffer)) !== '') {
        $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
    }
    return wikiAssignAnchors($sections);
}

/** @param list<array{title:?string,body:string}> $sections */
function wikiAssignAnchors(array $sections): array {
    $used = [];
    $chapters = [];
    foreach ($sections as $section) {
        if ($section['title'] === null) {
            $base = 'inleiding';
        } else {
            $base = wikiSlugify($section['title']);
            if ($base === '') $base = 'hoofdstuk';
        }
        $anchor = $base;
        $n = 2;
        while (isset($used[$anchor])) {
            $anchor = $base.'-'.$n;
            $n++;
        }
        $used[$anchor] = true;
        $chapters[] = [
            'anchor' => $anchor,
            'title' => $section['title'],
            'blocks' => wikiParagraphs($section['body']),
        ];
    }
    return $chapters;
}

/** @return list<array{inlines:list<array<string,mixed>>}> */
function wikiParagraphs(string $body): array {
    $parts = preg_split("/\n[ \t]*\n/u", $body) ?: [];
    $blocks = [];
    foreach ($parts as $part) {
        $lines = array_values(array_filter(array_map('trim', explode("\n", $part)), fn(string $line): bool => $line !== ''));
        if (!$lines) continue;
        $inlines = wikiParseInlines(implode(' ', $lines));
        if ($inlines) $blocks[] = ['inlines' => $inlines];
    }
    return $blocks;
}

/** @return list<array<string,mixed>> */
function wikiParseInlines(string $text): array {
    $inlines = [];
    $offset = 0;
    if (preg_match_all('/\[\[([^\[\]\n]+)\]\]/u', $text, $matches, PREG_OFFSET_CAPTURE)) {
        foreach ($matches[0] as $index => $full) {
            $start = $full[1];
            if ($start > $offset) {
                $inlines[] = ['type' => 'text', 'text' => substr($text, $offset, $start - $offset)];
            }
            $inlines[] = wikiRawLink($matches[1][$index][0]);
            $offset = $start + strlen($full[0]);
        }
    }
    if ($offset < strlen($text)) $inlines[] = ['type' => 'text', 'text' => substr($text, $offset)];
    return $inlines;
}

/** @return array<string,mixed> */
function wikiRawLink(string $inner): array {
    $label = null;
    $target = $inner;
    $bar = strpos($inner, '|');
    if ($bar !== false) {
        $target = substr($inner, 0, $bar);
        $label = trim(substr($inner, $bar + 1));
        if ($label === '') $label = null;
    }
    $target = trim($target);
    $page = null;
    $anchor = null;
    if (str_starts_with($target, '#')) {
        $anchor = substr($target, 1);
    } elseif (str_contains($target, '#')) {
        [$page, $anchor] = explode('#', $target, 2);
        if ($page === '') $page = null;
    } else {
        $page = $target;
    }
    $pageOk = $page === null || wikiSlugOk($page);
    $anchorOk = $anchor === null || ($anchor !== '' && wikiSlugOk($anchor));
    $valid = $pageOk && $anchorOk && ($page !== null || ($anchor !== null && $anchor !== ''));
    return [
        'type' => 'link',
        'page' => $page,
        'anchor' => $anchor === '' ? null : $anchor,
        'label' => $label,
        'raw' => trim($inner),
        'valid' => $valid,
    ];
}

/** @return array<string,array{title:string,anchors:array<string,string>,chapters:list<array<string,mixed>>}> */
function wikiCatalog(): array {
    $rows = query('SELECT slug, title, content FROM wiki_pages')->fetchAll();
    $catalog = [];
    foreach ($rows as $row) {
        $chapters = parseWikiChapters($row['content']);
        $anchors = [];
        foreach ($chapters as $chapter) $anchors[$chapter['anchor']] = $chapter['title'] ?? 'Inleiding';
        $catalog[$row['slug']] = [
            'title' => $row['title'],
            'anchors' => $anchors,
            'chapters' => $chapters,
        ];
    }
    return $catalog;
}

/** @param array<string,mixed> $link */
function wikiResolveLink(array $link, string $pageSlug, array $catalog): array {
    $targetPage = $link['page'] ?? $pageSlug;
    $anchor = $link['anchor'];
    $known = ($link['valid'] && is_string($targetPage) && isset($catalog[$targetPage])) ? $catalog[$targetPage] : null;
    $broken = $known === null;
    $chapterTitle = null;
    if (!$broken && $anchor !== null) {
        if (!isset($known['anchors'][$anchor])) $broken = true;
        else $chapterTitle = $known['anchors'][$anchor];
    }
    $text = $link['label'];
    if ($text === null || $text === '') {
        if ($broken) $text = $link['raw'];
        elseif ($anchor !== null) $text = $chapterTitle ?? $anchor;
        else $text = $known['title'];
    }
    return [
        'type' => 'link',
        'page' => $broken ? null : $targetPage,
        'anchor' => $broken ? null : $anchor,
        'text' => $text,
        'broken' => $broken,
    ];
}

/** @param list<array<string,mixed>> $chapters */
function wikiResolveChapters(array $chapters, string $pageSlug, array $catalog): array {
    $resolved = [];
    foreach ($chapters as $chapter) {
        $blocks = [];
        foreach ($chapter['blocks'] as $block) {
            $inlines = [];
            foreach ($block['inlines'] as $inline) {
                if (($inline['type'] ?? '') === 'text') {
                    if (($inline['text'] ?? '') !== '') $inlines[] = ['type' => 'text', 'text' => $inline['text']];
                    continue;
                }
                $inlines[] = wikiResolveLink($inline, $pageSlug, $catalog);
            }
            if ($inlines) $blocks[] = ['inlines' => $inlines];
        }
        $resolved[] = [
            'anchor' => $chapter['anchor'],
            'title' => $chapter['title'],
            'blocks' => $blocks,
        ];
    }
    return $resolved;
}

function loadWikiPage(string $slug): array {
    $page = wikiPageRow($slug);
    $category = query('SELECT slug, title FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
    if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
    $catalog = wikiCatalog();
    $chapters = wikiResolveChapters($catalog[$page['slug']]['chapters'], $page['slug'], $catalog);
    return [
        'slug' => $page['slug'],
        'title' => $page['title'],
        'position' => (int)$page['position'],
        'category' => ['slug' => $category['slug'], 'title' => $category['title']],
        'content' => $page['content'],
        'created' => (int)$page['created'],
        'updated' => (int)$page['updated'],
        'chapters' => $chapters,
    ];
}

function createWikiPage(array $input): array {
    $title = cleanText($input['title'] ?? null, 200, 'De paginatitel');
    if (!is_string($input['category'] ?? null) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
    $content = wikiNormalizeContent($input['content'] ?? '');
    parseWikiChapters($content);
    $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedPageSlugs());
    $position = wikiOptionalPosition($input);
    transaction(function () use ($title, $input, $content, $slug, $position): void {
        $category = wikiCategoryRow($input['category']);
        if (query('SELECT 1 FROM wiki_pages WHERE slug=?', [$slug])->fetchColumn()) {
            throw new AppException('Die slug is al in gebruik.', 409);
        }
        $now = time();
        query('INSERT INTO wiki_pages (category_id, slug, title, content, position, created, updated) VALUES (?,?,?,?,?,?,?)', [
            $category['id'], $slug, $title, $content, $position ?? wikiNextPagePosition((int)$category['id']), $now, $now,
        ]);
    });
    return loadWikiPage($slug);
}

function updateWikiPage(string $slug, array $input): array {
    foreach (['title', 'slug', 'position', 'content', 'category'] as $key) {
        if (array_key_exists($key, $input)) {
            $present = true;
            break;
        }
    }
    if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
    $stored = $slug;
    transaction(function () use ($slug, $input, &$stored): void {
        $page = wikiPageRow($slug);
        $title = array_key_exists('title', $input) ? cleanText($input['title'], 200, 'De paginatitel') : $page['title'];
        $newSlug = array_key_exists('slug', $input)
            ? wikiChooseSlug($input['slug'], $title, wikiReservedPageSlugs())
            : $page['slug'];
        $content = array_key_exists('content', $input) ? wikiNormalizeContent($input['content']) : $page['content'];
        parseWikiChapters($content);
        if (array_key_exists('category', $input)) {
            if (!is_string($input['category']) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
            $category = wikiCategoryRow($input['category']);
        } else {
            $category = query('SELECT * FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
            if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
        }
        $moved = (int)$category['id'] !== (int)$page['category_id'];
        if (array_key_exists('position', $input)) $position = wikiOptionalPosition($input);
        else $position = $moved ? null : (int)$page['position'];
        if ($position === null) $position = wikiNextPagePosition((int)$category['id']);
        $clash = query('SELECT 1 FROM wiki_pages WHERE slug=? AND id<>?', [$newSlug, $page['id']])->fetchColumn();
        if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
        query('UPDATE wiki_pages SET category_id=?, slug=?, title=?, content=?, position=?, updated=? WHERE id=?', [
            $category['id'], $newSlug, $title, $content, $position, time(), $page['id'],
        ]);
        $stored = $newSlug;
    });
    return loadWikiPage($stored);
}

function deleteWikiPage(string $slug): string {
    transaction(function () use ($slug): void {
        $page = wikiPageRow($slug);
        query('DELETE FROM wiki_pages WHERE id=?', [$page['id']]);
    });
    return $slug;
}
