<?php

declare(strict_types=1);

class FrontVideoListController
{
    

    private static array $slugMap = [
        'slug_new_videos'      => ['method' => 'newest',        'label' => 'new_videos'],
        'slug_top_rated'       => ['method' => 'topRated',      'label' => 'top_rated'],
        'slug_most_viewed'     => ['method' => 'mostViewed',    'label' => 'most_viewed'],
        'slug_most_favorited'  => ['method' => 'mostFavorited', 'label' => 'most_favorited'],
    ];

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

    

    public static function show(): void
    {
        $slug = Router::param('slug');

         
        foreach (self::$slugMap as $slugKey => $entry) {
            $translatedSlug = Translator::slug($slugKey, $entry['label']);
            if ($slug === $translatedSlug) {
                self::{$entry['method']}();
                return;
            }
        }

         
        $en = Translator::getFileStrings('en');
        foreach (self::$slugMap as $slugKey => $entry) {
            $enSlug = $en[$slugKey] ?? '';
            if ($slug === $enSlug) {
                $translatedSlug = Translator::slug($slugKey, $entry['label']);
                if ($translatedSlug !== $slug) {
                    $qs = $_SERVER['QUERY_STRING'] ?? '';
                    header('Location: ' . Router::url('/videos/' . $translatedSlug) . ($qs ? '?' . $qs : ''), true, 301);
                    exit;
                }
                self::{$entry['method']}();
                return;
            }
        }

         
        http_response_code(404);
        ThemeRenderer::render('404', [
            'pageTitle' => SEO::title('Page Not Found'),
        ]);
    }

    public static function newest(): void
    {
        self::renderListing(
            defaultSort: 'newest',
            titleKey: 'simply_section_latest',
            metaTitle: __('page_title_new_videos'),
        );
    }

    public static function topRated(): void
    {
        self::renderListing(
            defaultSort: 'top_rated',
            titleKey: 'simply_section_top_rated',
            metaTitle: __('page_title_top_rated'),
        );
    }

    public static function mostViewed(): void
    {
        self::renderListing(
            defaultSort: 'popular',
            titleKey: 'simply_section_most_viewed',
            metaTitle: __('page_title_most_viewed'),
        );
    }

    public static function mostFavorited(): void
    {
        self::renderListing(
            defaultSort: 'most_favorited',
            titleKey: 'simply_section_most_favorited',
            metaTitle: __('page_title_most_favorited'),
            customSortTabs: [
                'most_favorited' => __('most_favorited'),
                'newest'         => __('newest'),
                'popular'        => __('most_viewed'),
                'top_rated'      => __('top_rated'),
            ],
        );
    }

    private static function renderListing(
        string $defaultSort,
        string $titleKey,
        string $metaTitle,
        ?array $customSortTabs = null,
    ): void {
        $sort = $_GET['sort'] ?? HookSystem::applyFilter('front.default_sort', $defaultSort, 'video_list');
        $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);

         
        $rawPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
        $rawPath = rtrim($rawPath, '/') ?: '/';
        $cleanPath = $rawPath;
        if (Router::langPrefix() !== '' && str_starts_with($cleanPath, Router::langPrefix())) {
            $cleanPath = substr($cleanPath, strlen(Router::langPrefix())) ?: '/';
        }
        if (Router::typePrefix() !== '' && str_starts_with($cleanPath, Router::typePrefix())) {
            $cleanPath = substr($cleanPath, strlen(Router::typePrefix())) ?: '/';
        }
        $prefix = ltrim(Router::langPrefix() . Router::typePrefix(), '/');
        $canonicalPath = $prefix !== '' ? $prefix . $cleanPath : ltrim($cleanPath, '/');
        $canonicalUrl = SEO::canonical($canonicalPath);

        $siteUrl = SEO::siteUrl();
        $defaultLang = Translator::getDefaultCode();
        $typePrefix = Router::typePrefix();
        $alternates = [];
        $alternates[$defaultLang] = $siteUrl . $typePrefix . $cleanPath;
        foreach (Translator::available() as $lang) {
            if ($lang['code'] === $defaultLang) continue;
            $alternates[$lang['code']] = $siteUrl . '/' . $lang['code'] . $typePrefix . $cleanPath;
        }
        $alternates['x-default'] = $alternates[$defaultLang];
        Router::setAlternates($alternates);

        ThemeRenderer::render('video-list', [
            'pageTitle'      => SEO::title($metaTitle),
            'metaDescription' => $metaTitle,
            'canonicalUrl'   => $canonicalUrl,
            'alternates'     => $alternates,
            'listingTitle'   => __($titleKey),
            'videos'         => $videos,
            'pagination'     => $pagination,
            'sort'           => $sort,
            'customSortTabs' => $customSortTabs,
        ]);
    }
}
