<?php
/**
 * Keycloak SSO Login - Redirects to Keycloak for authentication
 * 
 * This file initiates the OAuth2/OIDC flow with Keycloak
 * 
 * Direct access: /admin/keycloak-login.php
 * Or via routing: /admin/index.php?module=keycloak/login
 */

// Suppress deprecation warnings from jumbojett library (PHP 8.5 compatibility)
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);

// Prevent output buffering issues
if (ob_get_level()) {
    ob_clean();
}

// Bootstrap minimal Vvveb (needed for session management)
define('APP', 'admin');
define('DS', DIRECTORY_SEPARATOR);
define('DIR_ROOT', dirname(__DIR__) . DS);
define('DIR_SYSTEM', DIR_ROOT . 'system' . DS);

// Load environment
require_once DIR_ROOT . 'env.php';

// Load Vvveb bootstrap (autoload, functions, etc.)
require_once DIR_SYSTEM . 'core/startup.php';

// Load Composer autoload for Keycloak library
require_once DIR_ROOT . 'vendor/autoload.php';

use Jumbojett\OpenIDConnectClient;

// Start session if not already started (needed for state parameter)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Configuration Keycloak - Adapt these values to your environment
$keycloakUrl    = 'https://connect.slm-lab.net/realms/cercle';
$keycloakClient = 'page.slm-lab.net';
$keycloakSecret = 'IGFw1QWDs9xQ7OyRp6YM8VRgQxn09tFF';

// Redirect URL - MUST match exactly the one configured in Keycloak
$redirectUrl = 'https://www.slm-lab.net/admin/index.php?page=keycloak-callback';

try {
    // Create OpenID Connect client
    $oidc = new OpenIDConnectClient(
        $keycloakUrl,
        $keycloakClient,
        $keycloakSecret
    );
    
    $oidc->setRedirectURL($redirectUrl);
    $oidc->addScope(['openid', 'profile', 'email']);
    
    // Redirect user to Keycloak for authentication
    // This will send headers, so no output before this
    $oidc->authenticate();
    
} catch (\Exception $e) {
    // If redirect fails, show error page
    http_response_code(500);
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Keycloak Authentication Error</title>
        <style>
            body { font-family: Arial, sans-serif; padding: 40px; text-align: center; }
            .error { color: #d32f2f; background: #ffebee; padding: 20px; border-radius: 4px; margin: 20px auto; max-width: 600px; }
        </style>
    </head>
    <body>
        <h1>Authentication Error</h1>
        <div class="error">
            <p><strong>Failed to start Keycloak authentication:</strong></p>
            <p><?php echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'); ?></p>
        </div>
        <p><a href="/admin/index.php?module=user/login">Return to login page</a></p>
    </body>
    </html>
    <?php
    exit;
}
