<?php
declare(strict_types=1);

class OidcPlugin
{
    public function register(): void
    {
        require_once __DIR__ . '/OidcDiscovery.php';
        require_once __DIR__ . '/OidcJwt.php';
        require_once __DIR__ . '/OidcConfig.php';
        require_once __DIR__ . '/OidcAuthAdapter.php';
        require_once __DIR__ . '/OidcProvisioner.php';
        require_once __DIR__ . '/OidcAdminController.php';
        require_once __DIR__ . '/OidcAuthController.php';

        // ── Routes ───────────────────────────────────────────────────────────
        // Admin settings.
        PluginManager::addRoute('/admin/plugins/oidc',  fn() => OidcAdminController::index());

        // Auth flow. Both routes must be reachable WITHOUT being logged in;
        // they implement the login process itself.
        PluginManager::addRoute('/auth/oidc/start',     fn() => OidcAuthController::start());
        PluginManager::addRoute('/auth/oidc/callback',  fn() => OidcAuthController::callback());

        // ── Login form: render SSO buttons ───────────────────────────────────
        PluginManager::on('login_form_extras', function (mixed $ctx): void {
            // Only render when the plugin is enabled AND at least one provider
            // is configured + active. Disabled providers are filtered.
            if (Helper::getSetting('oidc_enabled', '0') !== '1') return;
            $providers = OidcConfig::activeProviders();
            if (empty($providers)) return;

            echo '<div class="oidc-login-block" style="margin-top:14px;padding-top:14px;border-top:1px solid var(--border-color,#e5e7eb)">';
            echo '<div style="text-align:center;font-size:.78rem;color:var(--text-secondary,#666);margin-bottom:10px">' . htmlspecialchars(Lang::get('oidc_or_continue_with')) . '</div>';
            echo '<div style="display:flex;flex-direction:column;gap:8px">';
            foreach ($providers as $p) {
                $href  = htmlspecialchars((defined('APP_BASE') ? APP_BASE : '') . '/auth/oidc/start?provider=' . urlencode((string)$p['id']));
                $label = htmlspecialchars((string)($p['label'] ?? $p['id']));
                echo '<a href="' . $href . '" class="btn btn-secondary" style="display:flex;align-items:center;justify-content:center;gap:8px;text-decoration:none">';
                echo '<span style="font-size:.9rem">' . htmlspecialchars(Lang::get('oidc_sign_in_with')) . ' ' . $label . '</span>';
                echo '</a>';
            }
            echo '</div></div>';
        });
    }
}
