<?php
// admin/sso/start.php
//
// Initiates Microsoft Entra ID (Azure AD) OpenID Connect login with PKCE.
// Uses global sso_settings + company_sso_settings via lib/sso.php.

session_start();

require __DIR__ . '/../../lib/config.php';
require __DIR__ . '/../../lib/db.php';
require __DIR__ . '/../../lib/sso.php';

function sso_fail(string $msg, ?string $debug = null): void
{
    http_response_code(500);
    ?>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Single sign-on error</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            body{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
                 background:#f3f4f6;color:#111827;margin:0;padding:40px;display:flex;justify-content:center}
            .box{max-width:520px;width:100%;background:#fff;border-radius:6px;padding:18px 20px;
                 box-shadow:0 10px 30px rgba(15,23,42,.12);}
            h1{margin:0 0 8px;font-size:19px;color:#b91c1c}
            p{margin:4px 0 0;font-size:14px}
            pre{margin-top:10px;padding:8px;background:#f9fafb;border-radius:4px;
                font-size:11px;overflow:auto;color:#6b7280}
        </style>
    </head>
    <body>
    <div class="box">
        <h1>Single sign-on error</h1>
        <p><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></p>
        <?php if ($debug): ?>
            <pre><?= htmlspecialchars($debug, ENT_QUOTES, 'UTF-8') ?></pre>
        <?php endif; ?>
    </div>
    </body>
    </html>
    <?php
    exit;
}

try {
    if (!$pdo instanceof PDO) {
        throw new RuntimeException('Database not available.');
    }
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // --- Determine which company this SSO attempt is for ---

    $companyId = 0;

    // 1) Explicit ?company_id= from the login page (preferred)
    if (isset($_GET['company_id'])) {
        $cid = (int)$_GET['company_id'];
        if ($cid > 0) {
            $stmt = $pdo->prepare("
                SELECT 1
                FROM company_sso_settings
                WHERE company_id = ? AND enabled = 1
                LIMIT 1
            ");
            $stmt->execute([$cid]);
            if ($stmt->fetchColumn()) {
                $companyId = $cid;
            } else {
                throw new RuntimeException('SSO not enabled for that company.');
            }
        }
    }

    // 2) If not provided, and there is exactly one enabled SSO config, use that.
    if ($companyId === 0) {
        $row = $pdo->query("
            SELECT company_id
            FROM company_sso_settings
            WHERE enabled = 1
            LIMIT 2
        ")->fetchAll(PDO::FETCH_COLUMN);

        if (count($row) === 1) {
            $companyId = (int)$row[0];
        }
    }

    // 3) If still 0: either use pure global config (multi-tenant), or require explicit company.
    // Here we allow global-only if sso_build_config can handle companyId=0.
    // If you prefer to force a company selection, uncomment the exception.
    // if ($companyId === 0) {
    //     throw new RuntimeException('No SSO configuration resolved. Please specify a company.');
    // }

    // Build full config (from lib/sso.php)
    $cfg = sso_build_config($pdo, $companyId);

    // --- Prepare PKCE + OIDC params ---

    $codeVerifier  = sso_random(64);
    $codeChallenge = sso_pkce_challenge($codeVerifier);
    $state         = sso_random(32);
    $nonce         = sso_random(32);

    $_SESSION['sso_code_verifier'] = $codeVerifier;
    $_SESSION['sso_state']         = $state;
    $_SESSION['sso_nonce']         = $nonce;
    $_SESSION['sso_company_id']    = $companyId;

    $params = [
        'client_id'             => $cfg['client_id'],
        'response_type'         => 'code',
        'redirect_uri'          => $cfg['redirect_uri'],
        'response_mode'         => 'query',
        'scope'                 => 'openid profile email offline_access',
        'state'                 => $state,
        'nonce'                 => $nonce,
        'code_challenge'        => $codeChallenge,
        'code_challenge_method' => 'S256',
    ];

    $authUrl = $cfg['authorize'] . '?' . http_build_query($params);

    header('Location: ' . $authUrl);
    exit;

} catch (Throwable $e) {
    sso_fail($e->getMessage());
}
