<?php

declare(strict_types=1);

class AdminThemeController
{
    public static function routes(): void
    {
        Router::get('/admin/themes', [self::class, 'index']);
        Router::get('/admin/themes/installed', [self::class, 'redirectToIndex']);
        Router::get('/admin/themes/editor', [self::class, 'editor']);
        Router::post('/admin/themes/editor/save', [self::class, 'saveFile']);
        Router::post('/admin/themes/{slug}/activate', [self::class, 'activate']);
        Router::post('/admin/themes/{slug}/install', [self::class, 'install']);
        Router::post('/admin/themes/{slug}/uninstall', [self::class, 'uninstall']);
        Router::post('/admin/themes/{slug}/reset', [self::class, 'resetData']);
    }

    private static function fetchMarketplaceData(): array
    {
        $installed = ThemeManager::getAll();
        $available = [];
        $marketplaceError = '';
        $creditRate = 0.01;

        $mpData = CatalogueClient::getMarketplaceThemes();
        if ($mpData && !empty($mpData['items'])) {
            $installedSlugs = array_column($installed, 'slug');
            if (isset($mpData['credit_rate'])) {
                $creditRate = (float) $mpData['credit_rate'];
                Setting::set('catalogue_credit_rate', (string) $creditRate);
            }

            foreach ($mpData['items'] as $mpItem) {
                $slug = $mpItem['slug'] ?? '';
                if (in_array($slug, $installedSlugs)) {
                    foreach ($installed as &$t) {
                        if ($t['slug'] === $slug) {
                             
                            foreach (['description', 'long_description', 'features', 'author',
                                      'icon_url', 'screenshot_url', 'download_count',
                                      'requires_cms', 'price_credits', 'is_free',
                                      'pricing_tiers', 'has_tiers'] as $field) {
                                if (isset($mpItem[$field])) {
                                    $t['mp_' . $field] = $mpItem[$field];
                                }
                            }
                            $t['mp_owned'] = $mpItem['owned'] ?? true;

                            if (!empty($mpItem['latest_version'])) {
                                $currentVersion = $t['version'] ?? '0.0.0';
                                if (version_compare($mpItem['latest_version'], $currentVersion, '>')) {
                                    $t['mp_has_update'] = true;
                                    $t['mp_latest_version'] = $mpItem['latest_version'];
                                }
                            }
                        }
                    }
                    unset($t);
                } else {
                    $available[] = $mpItem;
                }
            }
        } elseif ($mpData && isset($mpData['_error'])) {
            $marketplaceError = 'Could not load marketplace data.';
        }

        return compact('installed', 'available', 'marketplaceError', 'creditRate');
    }

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

        $data = self::fetchMarketplaceData();

        Router::render('admin/themes', [
            'pageTitle' => 'Themes',
            'activeMenu' => 'themes',
            'activeSubMenu' => '',
            'contentTemplate' => '_themes',
            'themes' => $data['installed'],
            'available' => $data['available'],
            'marketplaceError' => $data['marketplaceError'],
            'marketplaceConfigured' => CatalogueClient::isConfigured(),
            'creditRate' => $data['creditRate'],
        ]);
    }

    public static function redirectToIndex(): void
    {
        Router::redirect('/admin/themes');
    }

    public static function editor(): void
    {
        Auth::requireSuperAdmin();
        $slug = ThemeManager::active();
        $files = ThemeManager::listFiles($slug);
        $selectedFile = $_GET['file'] ?? '';
        $fileContent = '';

        if ($selectedFile !== '') {
            $fileContent = ThemeManager::readFile($selectedFile, $slug);
            if ($fileContent === null) {
                $fileContent = '';
                $selectedFile = '';
            }
        }

        Router::render('admin/themes', [
            'pageTitle' => 'Edit Code', 'activeMenu' => 'themes', 'activeSubMenu' => 'editor',
            'contentTemplate' => '_theme_editor',
            'themeSlug' => $slug,
            'themeFiles' => $files,
            'selectedFile' => $selectedFile,
            'fileContent' => $fileContent,
        ]);
    }

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

        if (!Router::verifyCsrf()) {
            echo json_encode(['success' => false, 'error' => 'Invalid CSRF token.']);
            exit;
        }

        $file = $_POST['file'] ?? '';
        $content = $_POST['content'] ?? '';
        $slug = ThemeManager::active();

        if ($file === '') {
            echo json_encode(['success' => false, 'error' => 'No file specified.']);
            exit;
        }

        $result = ThemeManager::writeFile($file, $content, $slug);
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'File saved successfully.']);
        } else {
            echo json_encode(['success' => false, 'error' => 'Failed to save file. Check permissions or path.']);
        }
        exit;
    }

    public static function activate(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/themes'); return; }

        $slug = Router::param('slug');

         
        if (CatalogueClient::isConfigured()) {
            $domain = CatalogueClient::getSiteDomain();
            $result = CatalogueClient::activateSite('theme', $slug, $domain);
            if ($result && isset($result['valid']) && $result['valid'] === false) {
                $reason = $result['reason'] ?? 'unknown';
                if ($reason === 'not_purchased') {
                    $price = $result['price_credits'] ?? 0;
                    $_SESSION['flash'] = ['type' => 'error', 'message' => 'License required: this theme costs ' . number_format($price) . ' Credits. Purchase it from the marketplace dashboard.'];
                } elseif ($reason === 'no_slots') {
                    $used = $result['sites_used'] ?? 0;
                    $max = $result['max_sites'] ?? 1;
                    $_SESSION['flash'] = ['type' => 'error', 'message' => "All {$max} site slot(s) are in use ({$used}/{$max}). Upgrade your license or unbind a site at tubepress.io/dashboard/catalogue."];
                } elseif ($reason === 'cooldown') {
                    $_SESSION['flash'] = ['type' => 'error', 'message' => $result['message'] ?? 'This domain is in cooldown. Please wait before rebinding.'];
                } else {
                    $_SESSION['flash'] = ['type' => 'error', 'message' => $result['message'] ?? 'License verification failed.'];
                }
                Router::redirect('/admin/themes');
                return;
            }
        }

        ThemeManager::activate($slug);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Theme activated successfully.'];
        Router::redirect('/admin/themes');
    }

    private static function isAjax(): bool
    {
        return ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'XMLHttpRequest'
            || str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json');
    }

    public static function install(): void
    {
        Auth::requireSuperAdmin();
        $ajax = self::isAjax();

        if (!Router::verifyCsrf()) {
            if ($ajax) { Router::json(['success' => false, 'message' => 'Session expired.'], 403); return; }
            Router::redirect('/admin/themes');
            return;
        }

        $slug = Router::param('slug');

        if (!CatalogueClient::isConfigured()) {
            if ($ajax) { Router::json(['success' => false, 'message' => 'Marketplace not configured.'], 400); return; }
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Marketplace not configured.'];
            Router::redirect('/admin/themes');
            return;
        }

        $mpData = CatalogueClient::getMarketplaceThemes();
        $mpItem = null;
        if ($mpData && !empty($mpData['items'])) {
            foreach ($mpData['items'] as $item) {
                if (($item['slug'] ?? '') === $slug) {
                    $mpItem = $item;
                    break;
                }
            }
        }

        if (!$mpItem) {
            if ($ajax) { Router::json(['success' => false, 'message' => 'Theme not found in marketplace.'], 404); return; }
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Theme not found in marketplace.'];
            Router::redirect('/admin/themes');
            return;
        }

         
        $version = $mpItem['latest_version'] ?? '1.0.0';
        $result = UpdateManager::updateTheme($slug, $version, '');

        if ($result['success']) {
            if ($ajax) { Router::json(['success' => true, 'message' => 'Theme "' . ($mpItem['name'] ?? $slug) . '" installed successfully.']); return; }
            $_SESSION['flash'] = ['type' => 'success', 'message' => 'Theme "' . htmlspecialchars($mpItem['name'] ?? $slug) . '" installed successfully.'];
        } else {
            $err = $result['error'] ?? 'Unknown error';
            if ($ajax) { Router::json(['success' => false, 'message' => 'Install failed: ' . $err], 500); return; }
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Install failed: ' . $err];
        }

        Router::redirect('/admin/themes');
    }

    public static function uninstall(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/themes'); return; }

        $slug = Router::param('slug');
        $activeTheme = ThemeManager::active();

        if ($slug === $activeTheme) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Cannot uninstall the active theme. Activate a different theme first.'];
            Router::redirect('/admin/themes');
            return;
        }

        $themeDir = APP_ROOT . '/themes/' . $slug;
        if (!is_dir($themeDir)) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Theme not found.'];
            Router::redirect('/admin/themes');
            return;
        }

         
        if (CatalogueClient::isConfigured()) {
            CatalogueClient::deactivateSite('theme', $slug, CatalogueClient::getSiteDomain());
        }

        UpdateManager::deleteDir($themeDir);

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Theme uninstalled.'];
        Router::redirect('/admin/themes');
    }

    public static function resetData(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) {
            Router::redirect('/admin/themes');
            return;
        }

        $slug = Router::param('slug');

         
        $installed = ThemeManager::getAll();
        $found = false;
        foreach ($installed as $t) {
            if ($t['slug'] === $slug) {
                $found = true;
                break;
            }
        }

        if (!$found) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Theme not found.'];
            Router::redirect('/admin/themes');
            return;
        }

         
        Setting::deleteByPrefix($slug . '_');

         
        try {
            $escaped = str_replace(['%', '_'], ['\\%', '\\_'], $slug);
            Database::query(
                "DELETE FROM translation_overrides WHERE translation_key LIKE ?",
                [$escaped . '\\_%']
            );
        } catch (\Throwable $e) {
             
        }

         
        try {
            Database::query("DELETE FROM settings WHERE setting_key = 'footer_config'");
        } catch (\Throwable $e) {
        }

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'All data for theme "' . htmlspecialchars($slug) . '" has been reset.'];
        Router::redirect('/admin/themes');
    }
}
