<?php

declare(strict_types=1);

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

    public static function index(): void
    {
        $sort = $_GET['sort'] ?? HookSystem::applyFilter('front.default_sort', Setting::get('default_sort', 'newest'), 'home');
        $perPage = (int) Setting::get('videos_per_page', 24);
        $filters = ['sort' => $sort, 'status' => 'published'];
        if ($vt = Video::activeType()) $filters['video_type'] = $vt;
        $total = Video::count($filters);
        $pagination = Pagination::fromRequest($total, $perPage);
        $videos = Video::all($filters, $perPage, $pagination->offset);
         
         
        $videos = HookSystem::applyFilter('front.home_videos', $videos, $sort, $pagination, $vt ?? '');

         
        $siteUrl = SEO::siteUrl();
        $prefix = ltrim(Router::langPrefix() . Router::typePrefix(), '/');
        $canonicalPath = $prefix !== '' ? $prefix : '';  
        $canonicalUrl = SEO::canonical($canonicalPath);
        $alternates = self::buildAlternates();
        Router::setAlternates($alternates);

        $siteName = Branding::siteName();
        $siteDesc = Branding::siteDescription();

        ThemeRenderer::render('home', [
            'pageTitle' => SEO::title(),
            'metaDescription' => $siteDesc,
            'canonicalUrl' => $canonicalUrl,
            'alternates' => $alternates,
            'ogTags' => [
                'og:title' => $siteName,
                'og:description' => $siteDesc,
                'og:url' => $canonicalUrl,
                'og:type' => 'website',
            ],
            'twitterCard' => [
                'twitter:title' => $siteName,
                'twitter:description' => $siteDesc,
            ],
            'jsonLd' => SEO::websiteJsonLd(),
            'videos' => $videos,
            'pagination' => $pagination,
            'sort' => $sort,
        ]);
    }

    private static function buildAlternates(): array
    {
        $siteUrl = SEO::siteUrl();
        $defaultLang = Translator::getDefaultCode();
        $typePrefix = Router::typePrefix();
        $alternates = [];

        $alternates[$defaultLang] = $siteUrl . ($typePrefix !== '' ? $typePrefix : '/');
        foreach (Translator::available() as $lang) {
            if ($lang['code'] === $defaultLang) continue;
            $alternates[$lang['code']] = $siteUrl . '/' . $lang['code'] . $typePrefix;
        }
        $alternates['x-default'] = $alternates[$defaultLang];
        return $alternates;
    }
}
