<?php
session_start();

$tenantId = 'a70b907f-9db5-417e-a1a4-77a71bd0c8b5';
$clientId = '94ee35c5-81fb-4ad6-8364-2a854a60851d';
$clientSecret = 'Qri8Q~8_VIBHxCkd4XvL2oEsOyn9RoQ3LKjZSbDx';
$redirectUri = 'https://test.sb.assecutor.de/admin/o-auth.php';

// ==============================
// Sicherheit prüfen: State
// ==============================
if (empty($_GET['state']) || $_GET['state'] !== $_SESSION['state']) {
    $_SESSION['sso_error'] = 'Fehler: ' . "Ungültiger State.";
    header("Location: login.php");
    exit;
}

// ==============================
// Fehler von Microsoft prüfen
// ==============================
if (isset($_GET['error'])) {
    $_SESSION['sso_error'] = 'Fehler: ' . htmlspecialchars($_GET['error']);
    header("Location: login.php");
    exit;
}

// ==============================
// Authorization Code prüfen
// ==============================
$code = $_GET['code'] ?? null;
if (!$code) {
    $_SESSION['sso_error'] = 'Fehler: Kein Autorisierungscode erhalten.';
    header("Location: login.php");
    exit;
}

// ==============================
// Token-Anfrage
// ==============================
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
$data = [
    'client_id'     => $clientId,
    'client_secret' => $clientSecret,
    'grant_type'    => 'authorization_code',
    'code'          => $code,
    'redirect_uri'  => $redirectUri,
    'scope'         => 'openid profile email offline_access'
];

$options = [
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    ]
];

$context = stream_context_create($options);
$response = @file_get_contents($tokenUrl, false, $context);

if ($response === false) {
    $error = error_get_last();
    $_SESSION['sso_error'] = 'Fehler bei der Token-Anforderung: ' . ($error['message'] ?? 'unbekannt');
    header("Location: login.php");
    exit;
}

$tokenData = json_decode($response, true);
if (isset($tokenData['error'])) {
    $_SESSION['sso_error'] = 'Fehler: ' . htmlspecialchars($tokenData['error_description'] ?? $tokenData['error']);
    header("Location: login.php");
    exit;
}

$accessToken = $tokenData['access_token'] ?? null;
$idToken = $tokenData['id_token'] ?? null;

if (!$accessToken || !$idToken) {
    $_SESSION['sso_error'] = 'Kein Access Token oder ID-Token erhalten.';
    header("Location: login.php");
    exit;
}

// ==============================
// ID-Token dekodieren
// ==============================
$parts = explode('.', $idToken);
if (count($parts) !== 3) {
    $_SESSION['sso_error'] = 'Ungültiges ID-Token-Format.';
    header("Location: login.php");
    exit;
}

// Payload dekodieren
$payload = $parts[1];
$payload .= str_repeat('=', (4 - strlen($payload) % 4) % 4);
$json = base64_decode(strtr($payload, '-_', '+/'));
$idPayload = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    $_SESSION['sso_error'] = 'Fehler beim Parsen des ID-Token-Payloads.';
    header("Location: login.php");
    exit;
}

// ==============================
// UPN oder alternative Identifier
// ==============================
$loginName = null;
if (isset($idPayload['upn']) && $idPayload['upn'] !== null) {
    $loginName = $idPayload['upn'];
} elseif (isset($idPayload['preferred_username']) && $idPayload['preferred_username'] !== null) {
    $loginName = $idPayload['preferred_username'];
} elseif (isset($idPayload['email']) && $idPayload['email'] !== null) {
    $loginName = $idPayload['email'];
}

if (!$loginName) {
    $_SESSION['sso_error'] = 'Kein gültiger Benutzername im Token enthalten.';
    header("Location: login.php");
    exit;
}

// ==============================
// Session setzen
// ==============================
$_SESSION['sso'] = $loginName;
$_SESSION['payload'] = json_encode($idPayload);
//
//// Gruppen / Rollen
//if (!empty($idPayload['roles'])) {
//    $_SESSION['sso_roles'] = $idPayload['roles'];
//    header("Location: login.php");
//    exit;
//} elseif (!empty($idPayload['groups'])) {
//    $_SESSION['sso_groups'] = $idPayload['groups'];
//    header("Location: login.php");
//    exit;
//} else {
//    $_SESSION['sso_groups_error'] = 'Keine Gruppen oder Rollen im Token enthalten.';
//    header("Location: login.php");
//    exit;
//}

header("Location: login.php");
exit;