<?php

declare(strict_types=1);

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

    public static function index(): void
    {
        $query = trim(is_string($_GET['q'] ?? null) ? $_GET['q'] : '');
        $perPage = (int) Setting::get('videos_per_page', 24);
        $videos = [];
        $total = 0;
        $albums = [];
        $albumTotal = 0;

        $safeQuery = preg_replace('/[+\-<>()~*"@]/', ' ', $query);
        $safeQuery = preg_replace('/\s+/', ' ', trim($safeQuery));

        if ($safeQuery !== '' && mb_strlen($safeQuery) >= 3) {
            $filters = ['search' => $safeQuery, 'status' => 'published'];
            $vt = Video::activeType();
            if ($vt) $filters['video_type'] = $vt;
            $total = Video::count($filters);
            $pagination = Pagination::fromRequest($total, $perPage);
            $videos = Video::all($filters, $perPage, $pagination->offset);

            if (Album::featureEnabled()) {
                $albumFilters = ['search' => $safeQuery, 'status' => 'published'];
                if ($vt) $albumFilters['video_type'] = $vt;
                $albumTotal = Album::count($albumFilters);
                $albums = Album::all($albumFilters, $perPage, 0);
            }
        } else {
            $pagination = new Pagination(0);
        }

        $prefix = ltrim(Router::langPrefix() . Router::typePrefix(), '/');
        $canonicalPath = $prefix !== '' ? $prefix . '/search' : 'search';
        $canonicalUrl = SEO::canonical($canonicalPath);

        ThemeRenderer::render('search', [
            'pageTitle' => SEO::title($query !== '' ? "Search: {$query}" : 'Search'),
            'metaDescription' => $query !== '' ? "Search results for: {$query}" : 'Search',
            'canonicalUrl' => $canonicalUrl,
            'alternates' => [],
            'query' => $query,
            'videos' => $videos,
            'pagination' => $pagination,
            'total' => $total,
            'albums' => $albums,
            'albumTotal' => $albumTotal,
        ]);
    }

    public static function suggest(): void
    {
        header('Content-Type: application/json');

        $query = trim(is_string($_GET['q'] ?? null) ? $_GET['q'] : '');
        $safeQuery = preg_replace('/[+\-<>()~*"@]/', ' ', $query);
        $safeQuery = preg_replace('/\s+/', ' ', trim($safeQuery));

        if (mb_strlen($safeQuery) < 3) {
            echo '[]';
            exit;
        }

        $rows = Database::fetchAll(
            "SELECT title FROM videos WHERE status = 'published' AND MATCH(title, description) AGAINST(? IN BOOLEAN MODE) ORDER BY views DESC LIMIT 8",
            [$safeQuery]
        );

        echo json_encode(array_column($rows, 'title'), JSON_UNESCAPED_UNICODE);
        exit;
    }
}
