<?php

declare(strict_types=1);

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

    public static function index(): void
    {
        $sort = $_GET['sort'] ?? Setting::get('performers_default_sort', 'alphabetical');
        $perPage = (int) Setting::get('performers_per_page', '30');
        $videoType = Video::activeType();
        $total = Performer::count('', $videoType, true);
        $pagination = Pagination::fromRequest($total, $perPage);

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

        ThemeRenderer::render('performers', [
            'pageTitle' => SEO::title(__('page_title_pornstars')),
            'metaDescription' => __('page_title_pornstars'),
            'canonicalUrl' => $canonicalUrl,
            'alternates' => $alternates,
            'performers' => Performer::all('', $perPage, $pagination->offset, $sort, $videoType, true),
            'pagination' => $pagination,
            'sort' => $sort,
        ]);
    }

    public static function show(): void
    {
        $performer = Performer::findBySlug(Router::param('slug'));
        if (!$performer) { http_response_code(404); ThemeRenderer::render('404'); return; }
        Router::enforceCanonicalType($performer['video_type'], 'pornstar', $performer['slug']);

        $sort = $_GET['sort'] ?? HookSystem::applyFilter('front.default_sort', Setting::get('default_sort', 'newest'), 'performer');
        $perPage = (int) Setting::get('videos_per_page', 24);
        $filters = ['performer_id' => $performer['id'], 'status' => 'published', 'sort' => $sort];
        $total = Video::count($filters);
        $pagination = Pagination::fromRequest($total, $perPage);
        $videos = Video::all($filters, $perPage, $pagination->offset);

         
        if (empty($performer['photo'])) {
            $fallback = HookSystem::applyFilter('performer.profile_thumbnail', null, $performer);
            if ($fallback === null) {
                $row = Database::fetchOne(
                    "SELECT v.video_folder, v.storage_id FROM videos v
                     JOIN video_performers vp ON v.id = vp.video_id
                     WHERE vp.performer_id = ? AND v.status = 'published'
                       AND v.video_folder IS NOT NULL
                     ORDER BY v.views DESC LIMIT 1",
                    [$performer['id']]
                );
                $folder = $row['video_folder'] ?? '';
                $sid = isset($row['storage_id']) ? (int) $row['storage_id'] : null;
                $fallback = $folder !== '' ? VideoAsset::thumbUrlFromFolder($folder, false, $sid) : null;
                if ($fallback === '') $fallback = null;
            }
            if ($fallback) {
                $performer['_fallback_photo'] = $fallback;
            }
        }

         
        $prefix = ltrim(Router::langPrefix() . Router::typePrefix(), '/');
        $canonicalPath = $prefix !== '' ? $prefix . '/pornstar/' . $performer['slug'] : 'pornstar/' . $performer['slug'];
        $canonicalUrl = SEO::canonical($canonicalPath);
        $alternates = self::buildAlternates((int) $performer['id']);
        Router::setAlternates($alternates);

        $description = !empty($performer['bio']) ? mb_substr(strip_tags($performer['bio']), 0, 160) : $performer['name'];
        $siteUrl = SEO::siteUrl();

         
        $perfListPath = $prefix !== '' ? $prefix . '/pornstars' : 'pornstars';
        $breadcrumbJsonLd = SEO::breadcrumbJsonLd([
            ['name' => Setting::get('site_name', 'TubePress'), 'url' => $siteUrl . '/'],
            ['name' => __('page_title_pornstars'), 'url' => $siteUrl . '/' . $perfListPath],
            ['name' => $performer['name'], 'url' => html_entity_decode($canonicalUrl)],
        ]);
        $ogImage = '';
        if (!empty($performer['photo'])) {
            $ogImage = str_starts_with($performer['photo'], 'http') ? $performer['photo'] : $siteUrl . '/uploads/performers/' . $performer['photo'];
        } elseif (!empty($performer['_fallback_photo'])) {
            $fp = $performer['_fallback_photo'];
            $ogImage = (str_starts_with($fp, 'http://') || str_starts_with($fp, 'https://')) ? $fp : $siteUrl . $fp;
        }

        ThemeRenderer::render('performer', [
            'pageTitle' => SEO::title($performer['name']),
            'metaDescription' => $description,
            'canonicalUrl' => $canonicalUrl,
            'alternates' => $alternates,
            'ogTags' => [
                'og:title' => $performer['name'],
                'og:description' => $description,
                'og:url' => $canonicalUrl,
                'og:image' => $ogImage,
            ],
            'twitterCard' => [
                'twitter:title' => $performer['name'],
                'twitter:description' => $description,
                'twitter:image' => $ogImage,
            ],
            'jsonLd' => $breadcrumbJsonLd,
            'performer' => $performer,
            'videos' => $videos,
            'pagination' => $pagination,
            'sort' => $sort,
        ]);
    }

    private static function buildAlternates(int $performerId): array
    {
        $base = Database::fetchOne('SELECT slug, video_type FROM performers WHERE id = ?', [$performerId]);
        if (!$base) return [];

        $siteUrl = SEO::siteUrl();
        $defaultLang = Translator::getDefaultCode();
        $typePrefix = Router::typePrefixFor($base['video_type']);
        $translations = Performer::translations($performerId);
        $alternates = [];

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

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

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