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

// Already logged in
if ($auth->isLoggedIn()) {
    header('Location: /index.php');
    exit;
}

$error          = null;
$redirect       = filter_input(INPUT_GET, 'redirect', FILTER_SANITIZE_URL) ?? '/index.php';
$enabledMethods = $auth->getEnabledMethods();

// Handle POST login — un seul formulaire, test successif des méthodes
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    // Validate CSRF token
    $token = $_POST['csrf_token'] ?? '';
    if (!hash_equals(Session::get('csrf_token', ''), $token)) {
        $error = t('msg.error');
    } elseif (empty($username) || empty($password)) {
        $error = t('msg.required_fields');
    } else {
        $user = null;

        // 1. Essayer l'authentification locale
        if (!$user && in_array(AUTH_LOCAL, $enabledMethods, true)) {
            $user = $auth->attempt($username, $password, AUTH_LOCAL);
        }

        // 2. Si local échoue, essayer LDAP
        if (!$user && in_array(AUTH_LDAP, $enabledMethods, true)) {
            $user = $auth->attempt($username, $password, AUTH_LDAP);
        }

        if ($user) {
            $auth->loginUser($user);
            $i18n->init($user['language'] ?? null);
            $logger->info("User logged in", ['username' => $username, 'method' => $user['auth_method'] ?? '']);

            // Safe redirect
            if (!str_starts_with($redirect, '/') || str_starts_with($redirect, '//')) {
                $redirect = '/index.php';
            }
            header('Location: ' . $redirect);
            exit;
        } else {
            $error = t('auth.login_error');
            $logger->warning("Failed login attempt", ['username' => $username]);
        }
    }
}

// Handle OAuth callback
if (!empty($_GET['code']) && !empty($_GET['state'])) {
    $user = $auth->handleOAuthCallback($_GET['code'], $_GET['state']);
    if ($user) {
        $auth->loginUser($user);
        header('Location: /index.php');
        exit;
    }
    $error = t('auth.login_error');
}

// Generate CSRF token
if (!Session::has('csrf_token')) {
    Session::set('csrf_token', bin2hex(random_bytes(32)));
}

$pageTitle = t('auth.login_title');
include __DIR__ . '/includes/header.php';
?>

<div class="auth-wrapper">
    <div class="auth-box">
        <h1><?= t('auth.login_title') ?></h1>

        <?php if ($error): ?>
        <div class="alert alert-error" role="alert">
            <?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <form method="post" action="/login.php?redirect=<?= urlencode($redirect) ?>" class="auth-form" novalidate>
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(Session::get('csrf_token')) ?>">

            <div class="form-group">
                <label for="username"><?= t('auth.username') ?> *</label>
                <input type="text" id="username" name="username"
                       value="<?= htmlspecialchars($_POST['username'] ?? '') ?>"
                       required autofocus autocomplete="username">
            </div>

            <div class="form-group">
                <label for="password"><?= t('auth.password') ?> *</label>
                <input type="password" id="password" name="password"
                       required autocomplete="current-password">
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary btn-full">
                    <?= t('auth.login') ?>
                </button>
            </div>
        </form>

        <?php if (in_array(AUTH_OAUTH, $enabledMethods)): ?>
        <?php $oauthUrl = $auth->getOAuthRedirectUrl(); ?>
        <?php if ($oauthUrl): ?>
        <div class="auth-separator"><?= t('auth.or_use') ?></div>
        <a href="<?= htmlspecialchars($oauthUrl) ?>" class="btn btn-oauth btn-full">
            <?= t('auth.method_oauth') ?>
        </a>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
