<?php

declare(strict_types=1);

class FrontPageController
{
    public static function routes(): void
    {
        Router::get('/{slug}', [self::class, 'show']);
    }

    public static function show(): void
    {
        $slug = Router::param('slug');
        $locale = Translator::locale();
        $page = Page::findBySlugLocalized($slug, $locale);

        if (!$page) {
            http_response_code(404);
            ThemeRenderer::render('404');
            return;
        }

        $metaTitle = !empty($page['meta_title']) ? $page['meta_title'] : $page['title'];
        $metaDesc = $page['meta_description'] ?? '';
        $canonicalUrl = SEO::canonical($page['slug']);
        $alternates = self::buildAlternates((int) $page['id']);
        Router::setAlternates($alternates);

        ThemeRenderer::render('page', [
            'pageTitle' => SEO::title($metaTitle),
            'metaDescription' => $metaDesc,
            'canonicalUrl' => $canonicalUrl,
            'alternates' => $alternates,
            'page' => $page,
        ]);
    }

    private static function buildAlternates(int $pageId): array
    {
        $defaultLang = Translator::getDefaultCode();
        $basePage = Page::find($pageId);
        if (!$basePage || ($basePage['status'] ?? '') !== 'published') {
            return [];
        }

        $siteUrl = rtrim((string) Setting::get('site_url', ''), '/');
        if ($siteUrl === '') {
            $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $siteUrl = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
        }

        $alternates = [];

         
        $alternates[$defaultLang] = $siteUrl . '/' . $basePage['slug'];

         
        $translations = Page::translations($pageId);
        foreach ($translations as $langCode => $trans) {
            if (Translator::isEnabled($langCode)) {
                $alternates[$langCode] = $siteUrl . '/' . $langCode . '/' . $trans['slug'];
            }
        }

         
        $alternates['x-default'] = $alternates[$defaultLang];

        return $alternates;
    }
}
