<?php
require_once __DIR__ . '/app/bootstrap.php';

if (current_user()) {
    header('Location: ' . entra_same_origin_app_path('dashboard.php'));
    exit;
}

try {
    $expectedNonce = entra_validate_callback_state();
    if (isset($_GET['error'])) {
        $oauthError = is_scalar($_GET['error']) ? (string)$_GET['error'] : '';
        $oauthDescription = is_scalar($_GET['error_description'] ?? null) ? (string)$_GET['error_description'] : '';
        throw new EntraAuthException(entra_provider_error_reason($oauthError, $oauthDescription));
    }
    if (!isset($_GET['code']) || !is_scalar($_GET['code']) || (string)$_GET['code'] === '') {
        throw new EntraAuthException('invalid_response');
    }

    $client = entra_oidc_client();
    if (!$client->authenticate()) {
        throw new EntraAuthException('invalid_response');
    }
    $identity = entra_verified_identity($client, $expectedNonce);
    entra_clear_transient_session();
    $resolved = entra_resolve_ticketing_user($identity);
    $ticketingUser = $resolved['user'];

    if (!empty($resolved['linked'])) {
        auth_audit_event('AUTH_ENTRA_ACCOUNT_LINKED', (int)$ticketingUser['id'], 'entra');
    }
    $sessionUser = establish_authenticated_session((int)$ticketingUser['id'], 'entra');
    auth_audit_event('AUTH_ENTRA_SUCCESS', (int)$ticketingUser['id'], 'entra');

    if ((int)($sessionUser['must_change_password'] ?? 0) === 1) {
        flash('warning', 'Administrator je zahtevao da promenite privremenu lozinku pre pristupa sistemu.');
        header('Location: ' . entra_application_url('password_change_required.php'));
        exit;
    }
    flash('success', 'Uspešno ste se prijavili Microsoft 365 nalogom.');
    header('Location: ' . entra_application_url('dashboard.php'));
    exit;
} catch (EntraAuthException $e) {
    entra_redirect_with_error($e);
} catch (Jumbojett\OpenIDConnectClientException $e) {
    entra_redirect_with_error(new EntraAuthException(entra_library_error_reason($e), null, $e));
} catch (Throwable $e) {
    entra_redirect_with_error(new EntraAuthException('service_unavailable', null, $e));
}
