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

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

try {
    $client = entra_oidc_client();
    $_SESSION['entra_auth_started_at'] = time();
    $client->authenticate();
} catch (EntraAuthException $e) {
    entra_redirect_with_error($e);
} catch (Throwable $e) {
    auth_audit_event('AUTH_ENTRA_FAILED', null, 'entra', ['reason' => 'service_unavailable']);
    entra_clear_transient_session();
    flash('danger', entra_user_message('service_unavailable'));
    header('Location: ' . entra_same_origin_app_path('login.php'));
    exit;
}
