<?php

declare(strict_types=1);

class AdminPluginController
{
    public static function routes(): void
    {
        Router::get('/admin/plugins', [self::class, 'index']);
        Router::get('/admin/plugins/installed', [self::class, 'redirectToIndex']);
        Router::post('/admin/plugins/{slug}/activate', [self::class, 'activate']);
        Router::post('/admin/plugins/{slug}/deactivate', [self::class, 'deactivate']);
        Router::post('/admin/plugins/{slug}/install', [self::class, 'install']);
        Router::post('/admin/plugins/{slug}/uninstall', [self::class, 'uninstall']);
    }

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

        $mpData = CatalogueClient::getMarketplacePlugins();
        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 &$p) {
                        if ($p['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])) {
                                    $p['mp_' . $field] = $mpItem[$field];
                                }
                            }
                            $p['mp_owned'] = $mpItem['owned'] ?? true;

                            if (!empty($mpItem['latest_version'])) {
                                $currentVersion = $p['version'] ?? '0.0.0';
                                if (version_compare($mpItem['latest_version'], $currentVersion, '>')) {
                                    $p['mp_has_update'] = true;
                                    $p['mp_latest_version'] = $mpItem['latest_version'];
                                }
                            }
                        }
                    }
                    unset($p);
                } 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/plugins', [
            'pageTitle' => 'Plugins',
            'activeMenu' => 'plugins',
            'activeSubMenu' => '',
            'contentTemplate' => '_plugins',
            'plugins' => $data['installed'],
            'available' => $data['available'],
            'marketplaceError' => $data['marketplaceError'],
            'marketplaceConfigured' => CatalogueClient::isConfigured(),
            'creditRate' => $data['creditRate'],
        ]);
    }

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

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

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

         
        if (CatalogueClient::isConfigured()) {
            $domain = CatalogueClient::getSiteDomain();
            $result = CatalogueClient::activateSite('plugin', $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 plugin 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/plugins');
                return;
            }
        }

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

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

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

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

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Plugin deactivated.'];
        Router::redirect('/admin/plugins');
    }

    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();
        Gate::authorize('manage_plugins');  
        $ajax = self::isAjax();

        if (!Router::verifyCsrf()) {
            if ($ajax) { Router::json(['success' => false, 'message' => 'Session expired.'], 403); return; }
            Router::redirect('/admin/plugins');
            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/plugins');
            return;
        }

         
        $mpData = CatalogueClient::getMarketplacePlugins();
        $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' => 'Plugin not found in marketplace.'], 404); return; }
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Plugin not found in marketplace.'];
            Router::redirect('/admin/plugins');
            return;
        }

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

        if (!$result['success']) {
            $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/plugins');
            return;
        }

         
        $pluginName = htmlspecialchars($mpItem['name'] ?? $slug);
        $isFree = !empty($mpItem['is_free']);

         
        if (!$isFree && CatalogueClient::isConfigured()) {
            $domain = CatalogueClient::getSiteDomain();
            $licResult = CatalogueClient::activateSite('plugin', $slug, $domain);

            if ($licResult && isset($licResult['valid']) && $licResult['valid'] === false) {
                $reason = $licResult['reason'] ?? 'unknown';
                $licMsg = match ($reason) {
                    'not_purchased' => 'License required: this plugin costs ' . number_format($licResult['price_credits'] ?? 0) . ' Credits. Purchase it from the marketplace.',
                    'no_slots'      => 'All ' . ($licResult['max_sites'] ?? 1) . ' site slot(s) are in use (' . ($licResult['sites_used'] ?? 0) . '/' . ($licResult['max_sites'] ?? 1) . '). Upgrade your license or unbind a site at tubepress.io/dashboard.',
                    'cooldown'      => $licResult['message'] ?? 'This domain is in cooldown. Please wait before rebinding.',
                    default         => $licResult['message'] ?? 'License verification failed.',
                };
                 
                if ($ajax) { Router::json(['success' => true, 'message' => "Plugin \"{$pluginName}\" installed but not activated: {$licMsg}", 'activated' => false]); return; }
                $_SESSION['flash'] = ['type' => 'warning', 'message' => "Plugin \"{$pluginName}\" installed but not activated: {$licMsg}"];
                Router::redirect('/admin/plugins');
                return;
            }
        }

         
        PluginManager::activate($slug);

        if ($ajax) { Router::json(['success' => true, 'message' => "Plugin \"{$pluginName}\" installed and activated.", 'activated' => true]); return; }
        $_SESSION['flash'] = ['type' => 'success', 'message' => "Plugin \"{$pluginName}\" installed and activated."];
        Router::redirect('/admin/plugins');
    }

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

        $slug = Router::param('slug');
        $pluginDir = APP_ROOT . '/plugins/' . $slug;

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

         
        $pluginInstance = PluginManager::getPlugin($slug);
        if (!$pluginInstance) {
             
            $pluginPath = $pluginDir . '/plugin.php';
            if (file_exists($pluginPath)) {
                try {
                    $pluginInstance = require $pluginPath;
                } catch (\Throwable $e) {
                    $pluginInstance = null;
                }
            }
        }

         
        $row = Database::fetchOne('SELECT is_active FROM plugins WHERE slug = ?', [$slug]);
        if ($row && $row['is_active']) {
            PluginManager::deactivate($slug);
            if (CatalogueClient::isConfigured()) {
                CatalogueClient::deactivateSite('plugin', $slug, CatalogueClient::getSiteDomain());
            }
        }

         
        if ($pluginInstance instanceof PluginInterface) {
            try {
                $pluginInstance->uninstall();
            } catch (\Throwable $e) {
                 
            }
        }

         
        Database::query('DELETE FROM plugins WHERE slug = ?', [$slug]);

         
        UpdateManager::deleteDir($pluginDir);

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