<?php
/**
 * Keycloak SSO Login Controller
 * 
 * Handles: /admin/index.php?module=keycloak/login
 * 
 * This controller does NOT extend Base to avoid login requirement check
 */

namespace Vvveb\Controller\Keycloak;

use Vvveb\System\Core\Request;
use Vvveb\System\Core\Response;
use Vvveb\System\Core\View;
use Vvveb\System\Session;
use Jumbojett\OpenIDConnectClient;

#[\AllowDynamicProperties]
class Login {
    // Declare properties to avoid dynamic property warnings in PHP 8.2+
    public $request;
    public $response;
    public $view;
    public $session;
    
    function index() {
        // Properties are injected by FrontController::di() automatically
        // Suppress deprecation warnings from jumbojett library (PHP 8.5 compatibility)
        // E_STRICT removed in PHP 8.4+, so we don't include it
        // Suppress warnings temporarily to prevent output before headers
        $oldErrorReporting = error_reporting(E_ALL & ~E_DEPRECATED & ~E_WARNING);
        
        // Load Keycloak configuration from config file
        $keycloakConfig = \Vvveb\config('keycloak', []);
        
        // Fallback to hardcoded values if config file doesn't exist
        $keycloakUrl    = $keycloakConfig['server_url'] ?? 'https://connect.slm-lab.net/realms/cercle';
        $keycloakClient = $keycloakConfig['client_id'] ?? 'page.slm-lab.net';
        $keycloakSecret = $keycloakConfig['client_secret'] ?? 'IGFw1QWDs9xQ7OyRp6YM8VRgQxn09tFF';
        
        // Redirect URL - MUST match exactly the one configured in Keycloak
        $redirectUrl = $keycloakConfig['redirect_uri'] ?? 'https://www.slm-lab.net/admin/index.php?module=keycloak/callback';
        
        // Get redirect parameter if present (for redirecting back to original page after login)
        $originalRedirect = $this->request->get['redirect'] ?? null;
        if ($originalRedirect) {
            // Store original redirect URL in session for use after Keycloak callback
            $this->session->set('keycloak_redirect', $originalRedirect);
        }
        
        try {
            // Create OpenID Connect client
            $oidc = new OpenIDConnectClient(
                $keycloakUrl,
                $keycloakClient,
                $keycloakSecret
            );
            
            $oidc->setRedirectURL($redirectUrl);
            $oidc->addScope(['openid', 'profile', 'email']);
            
            // Restore error reporting before redirect
            error_reporting($oldErrorReporting);
            
            // Redirect user to Keycloak for authentication
            // This will send headers, so no output before this
            $oidc->authenticate();
            
        } catch (\Exception $e) {
            // Restore error reporting
            error_reporting($oldErrorReporting);
            
            // If redirect fails, redirect to login page with error
            header('Location: /admin/index.php?module=user/login&error=' . urlencode('Keycloak authentication failed: ' . $e->getMessage()));
            exit;
        }
    }
}
