<?php

declare(strict_types=1);

class AdminLanguageController
{
    private static array $sections = [
        'Navigation' => ['home', 'categories', 'tags', 'pornstars', 'channels', 'new_videos', 'most_favorited', 'search_placeholder', 'navigation', 'pages'],
        'Auth' => ['login', 'log_in', 'sign_up', 'logout', 'welcome', 'sign_in_subtitle', 'email_or_username', 'password', 'username', 'email', 'confirm_password', 'create_account', 'forgot_password', 'forgot_password_desc', 'send_reset_link', 'back_to_login', 'no_account', 'have_account'],
        'Profile' => ['my_profile', 'new_password', 'new_password_hint', 'confirm_new_password', 'update_profile', 'profile_updated'],
        'Video' => ['views', 'show_more', 'show_less', 'related_videos', 'recommended_videos', 'load_more', 'add_to_favorites', 'remove_from_favorites'],
        'Video Labels' => ['pornstars_label', 'pornstars_label_plural', 'artists_label', 'artists_label_plural', 'channels_label', 'channels_label_plural', 'categories_label', 'categories_label_plural', 'tags_label'],
        'Comments' => ['comments_count', 'comments_count_plural', 'add_a_comment', 'cancel', 'comment_btn', 'log_in_to_comment', 'view_more_comments', 'view_more_comments_plural', 'reply_to_comment'],
        'Time' => ['time_seconds_ago', 'time_minute_ago', 'time_minutes_ago', 'time_hour_ago', 'time_hours_ago', 'time_day_ago', 'time_days_ago', 'time_month_ago', 'time_months_ago', 'time_year_ago', 'time_years_ago'],
        'Sort & Counts' => ['newest', 'trending', 'most_viewed', 'top_rated', 'most_favorited', 'video_count', 'video_count_plural', 'views_count', 'likes_count'],
        'Listing Pages' => ['categories_to_explore', 'categories_to_explore_plural', 'tags_to_explore', 'tags_to_explore_plural', 'pornstars_count', 'pornstars_count_plural', 'channels_count', 'channels_count_plural'],
        'Page Titles' => ['page_title_new_videos', 'page_title_top_rated', 'page_title_most_viewed', 'page_title_most_favorited', 'page_title_categories', 'page_title_tags', 'page_title_pornstars', 'page_title_channels'],
        'Empty States' => ['no_videos', 'no_categories', 'no_tags', 'no_pornstars', 'no_channels', 'no_videos_category', 'no_videos_tag', 'no_videos_pornstar', 'no_videos_channel'],
        'Search' => ['search_videos', 'search_results_for', 'search_results_for_plural', 'no_results_for', 'no_results_try'],
        'Favorites & History' => ['my_favorites', 'videos_in_favorites', 'videos_in_favorites_plural', 'no_favorites', 'discover_videos', 'watch_history', 'videos_watched', 'videos_watched_plural', 'clear_history', 'clear_history_confirm', 'history_empty'],
        'Pages & Footer' => ['page_not_found', 'page_not_found_desc', 'back_to_home', 'all_rights_reserved', 'adults_only', 'about_site', 'footer_badge_18', 'footer_badge_free', 'footer_badge_hd', 'popular_videos'],
        'Messages' => ['please_wait', 'network_error', 'an_error_occurred', 'too_many_requests'],
        'Auth Errors' => ['error_username_length', 'error_username_chars', 'error_invalid_email', 'error_password_length', 'error_username_taken', 'error_fill_all_fields', 'error_invalid_credentials', 'error_account_deactivated', 'error_invalid_token', 'error_registration_disabled', 'error_passwords_mismatch', 'forgot_password_sent', 'error_invalid_email_address'],
        'URL Slugs' => ['slug_new_videos', 'slug_top_rated', 'slug_most_viewed', 'slug_most_favorited', 'slug_categories', 'slug_category', 'slug_tags', 'slug_tag', 'slug_videos', 'slug_video', 'slug_pornstars', 'slug_pornstar', 'slug_channels', 'slug_channel', 'slug_search', 'slug_favorites', 'slug_watch_history', 'slug_login', 'slug_register', 'slug_profile', 'slug_embed'],
    ];

    public static function routes(): void
    {
        Router::get('/admin/languages', [self::class, 'index']);
        Router::post('/admin/languages', [self::class, 'update']);
        Router::post('/admin/translations/save', [self::class, 'saveTranslations']);
        Router::post('/admin/translations/reset', [self::class, 'resetTranslation']);
         
        Router::get('/admin/translations', [self::class, 'redirectToLanguages']);
    }

    public static function redirectToLanguages(): void
    {
        Router::redirect('/admin/languages');
    }

    public static function index(): void
    {
        Auth::requireAdmin();

        $languages = Database::fetchAll(
            'SELECT code, name, native_name, direction, is_enabled, is_default FROM languages ORDER BY sort_order ASC'
        );

         
        $editLang = $_GET['edit'] ?? null;
        $editLang = $editLang ? preg_replace('/[^a-z]/', '', strtolower($editLang)) : null;

        $sections = [];
        $totalKeys = 0;
        $overrideCount = 0;
        $untranslatedCount = 0;
        $enabledLanguages = [];

        foreach ($languages as $lang) {
            if ((int) $lang['is_enabled']) {
                $enabledLanguages[] = $lang;
            }
        }

         
        $validCodes = array_column($enabledLanguages, 'code');
        if ($editLang === null && !empty($enabledLanguages)) {
            foreach ($enabledLanguages as $el) {
                if (!empty($el['is_default'])) {
                    $editLang = $el['code'];
                    break;
                }
            }
            if ($editLang === null) {
                $editLang = $enabledLanguages[0]['code'];
            }
        }

         
        if ($editLang && !in_array($editLang, $validCodes, true)) {
            $editLang = null;
        }

         
        $slugLabelMap = [
            'slug_new_videos'     => 'new_videos',
            'slug_top_rated'      => 'top_rated',
            'slug_most_viewed'    => 'most_viewed',
            'slug_most_favorited' => 'most_favorited',
        ];

        if ($editLang) {
            $enStrings = Translator::getFileStrings('en');
            $langStrings = ($editLang !== 'en') ? Translator::getFileStrings($editLang) : $enStrings;
            $overrides = Translator::getOverrides($editLang);

            $assignedKeys = [];
            foreach (self::$sections as $sectionName => $keys) {
                $rows = [];
                foreach ($keys as $key) {
                    if (!isset($enStrings[$key])) {
                        continue;
                    }
                    $assignedKeys[$key] = true;
                    $fileValue = $langStrings[$key] ?? '';
                    $overrideValue = $overrides[$key] ?? null;

                     
                    $hint = '';
                    if (isset($slugLabelMap[$key]) && $editLang !== 'en') {
                        $labelKey = $slugLabelMap[$key];
                        $label = $langStrings[$labelKey] ?? '';
                        if ($label !== '') {
                            $hint = Slug::generate($label);
                        }
                    }

                    $rows[] = [
                        'key' => $key,
                        'english' => $enStrings[$key],
                        'file_value' => $fileValue,
                        'current' => $overrideValue ?? $fileValue,
                        'is_overridden' => $overrideValue !== null,
                        'hint' => $hint,
                    ];
                }
                if (!empty($rows)) {
                    $sections[$sectionName] = $rows;
                }
            }

             
            $registeredSections = Translator::getRegisteredSections();
            $registeredKeys = Translator::getRegisteredKeys();
            $registeredSectionNames = [];
            foreach ($registeredSections as $regSectionName => $regKeys) {
                $rows = [];
                foreach ($regKeys as $key) {
                    if (isset($assignedKeys[$key])) {
                        continue;
                    }
                    $assignedKeys[$key] = true;
                    $regDefault = $registeredKeys[$key] ?? '';
                    $overrideValue = $overrides[$key] ?? null;
                    $rows[] = [
                        'key' => $key,
                        'english' => $regDefault,
                        'file_value' => $regDefault,
                        'current' => $overrideValue ?? $regDefault,
                        'is_overridden' => $overrideValue !== null,
                    ];
                }
                if (!empty($rows)) {
                    $sections[$regSectionName] = $rows;
                    $registeredSectionNames[$regSectionName] = true;
                }
            }

             
            $uncategorized = [];
            foreach ($enStrings as $key => $val) {
                if (!isset($assignedKeys[$key])) {
                    $fileValue = $langStrings[$key] ?? '';
                    $overrideValue = $overrides[$key] ?? null;
                    $uncategorized[] = [
                        'key' => $key,
                        'english' => $val,
                        'file_value' => $fileValue,
                        'current' => $overrideValue ?? $fileValue,
                        'is_overridden' => $overrideValue !== null,
                    ];
                }
            }
            if (!empty($uncategorized)) {
                $sections['Other'] = $uncategorized;
            }

            $totalKeys = count($enStrings) + count($registeredKeys);
            $overrideCount = count($overrides);

             
            $untranslatedCount = 0;
            foreach ($sections as $rows) {
                foreach ($rows as $row) {
                    if ($row['current'] === '') {
                        $untranslatedCount++;
                    }
                }
            }
        }

        Router::render('admin/languages', [
            'pageTitle' => 'Languages',
            'activeMenu' => 'languages',
            'contentTemplate' => '_languages',
            'languages' => $languages,
            'enabledLanguages' => $enabledLanguages,
            'editLang' => $editLang,
            'sections' => $sections,
            'totalKeys' => $totalKeys,
            'overrideCount' => $overrideCount,
            'untranslatedCount' => $untranslatedCount,
            'registeredSectionNames' => $registeredSectionNames ?? [],
            'autoDetectLanguage' => Setting::get('auto_detect_language', '1') === '1',
        ]);
    }

    public static function update(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            Router::redirect('/admin/languages');
        }

        $enabled = $_POST['enabled'] ?? [];
        $default = $_POST['default_lang'] ?? 'en';

        if (!is_array($enabled)) {
            $enabled = [];
        }

         
        if (!in_array('en', $enabled, true)) {
            $enabled[] = 'en';
        }

        if (!in_array($default, $enabled, true)) {
            $default = 'en';
        }

         
        $autoDetect = isset($_POST['auto_detect_language']) ? '1' : '0';
        Setting::set('auto_detect_language', $autoDetect);

         
        $allLanguages = Database::fetchAll('SELECT code FROM languages');
        foreach ($allLanguages as $lang) {
            $code = $lang['code'];
            $isEnabled = in_array($code, $enabled, true) ? 1 : 0;
            $isDefault = ($code === $default) ? 1 : 0;
            Database::query(
                'UPDATE languages SET is_enabled = ?, is_default = ? WHERE code = ?',
                [$isEnabled, $isDefault, $code]
            );
        }

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Languages updated successfully.'];
        Router::redirect('/admin/languages');
    }

    public static function saveTranslations(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            Router::redirect('/admin/languages');
        }

        $lang = $_POST['lang'] ?? 'en';
        $lang = preg_replace('/[^a-z]/', '', strtolower($lang));
        $translations = $_POST['translations'] ?? [];

        if (!is_array($translations)) {
            Router::redirect('/admin/languages?edit=' . $lang);
            return;
        }

        $fileStrings = Translator::getFileStrings($lang);
        $registeredKeys = Translator::getRegisteredKeys();
        $saved = 0;
        $deleted = 0;

        foreach ($translations as $key => $value) {
            $key = (string) $key;
            $value = trim((string) $value);

            if (strlen($key) > 100) {
                continue;
            }

            $fileDefault = $fileStrings[$key] ?? $registeredKeys[$key] ?? '';

            if ($value === $fileDefault || $value === '') {
                Database::query(
                    'DELETE FROM translation_overrides WHERE lang_code = ? AND translation_key = ?',
                    [$lang, $key]
                );
                $deleted++;
            } else {
                Database::query(
                    'INSERT INTO translation_overrides (lang_code, translation_key, value)
                     VALUES (?, ?, ?)
                     ON DUPLICATE KEY UPDATE value = VALUES(value), updated_at = CURRENT_TIMESTAMP',
                    [$lang, $key, $value]
                );
                $saved++;
            }
        }

        $_SESSION['flash'] = [
            'type' => 'success',
            'message' => "Translations saved. $saved override(s) set, $deleted reset to default.",
        ];
        Router::redirect('/admin/languages?edit=' . $lang);
    }

    public static function resetTranslation(): void
    {
        Auth::requireAdmin();

        if (!Router::verifyCsrf()) {
            Router::json(['error' => 'Your session has expired. Please refresh the page and try again.'], 403);
        }

        $input = json_decode(file_get_contents('php://input'), true);
        $lang = preg_replace('/[^a-z]/', '', strtolower((string) ($input['lang'] ?? '')));
        $key = (string) ($input['key'] ?? '');

        if ($lang === '' || $key === '') {
            Router::json(['error' => 'Missing language or key. Please try again.'], 400);
        }

        Database::query(
            'DELETE FROM translation_overrides WHERE lang_code = ? AND translation_key = ?',
            [$lang, $key]
        );

        $fileStrings = Translator::getFileStrings($lang);
        $registeredKeys = Translator::getRegisteredKeys();
        Router::json([
            'success' => true,
            'default_value' => $fileStrings[$key] ?? $registeredKeys[$key] ?? '',
        ]);
    }
}
