<?php

class LoginController extends Controller
{
    public function showForm(): void
    {
        if ($this->auth->isLoggedIn()) {
            $this->redirect('/');
        }

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

        $this->ensureCsrf();

        $this->view(WEBROOT_PATH . '/views/login.php', [
            'error'          => $error ?? null,
            'redirect'       => filter_input(INPUT_GET, 'redirect', FILTER_SANITIZE_URL) ?? '/',
            'enabledMethods' => $this->auth->getEnabledMethods(),
            'postedUsername'  => '',
        ]);
    }

    public function submit(): void
    {
        if ($this->auth->isLoggedIn()) {
            $this->redirect('/');
        }

        $redirect = filter_input(INPUT_GET, 'redirect', FILTER_SANITIZE_URL) ?? '/';
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $error    = null;

        $clientIp = LoginThrottle::clientIp();

        if (!$this->verifyCsrf()) {
            $error = t('msg.error');
        } elseif (empty($username) || empty($password)) {
            $error = t('msg.required_fields');
        } elseif (LoginThrottle::tooManyFailures($clientIp)) {
            // Anti-brute-force : trop d'échecs récents depuis cette IP.
            $this->logger->warning("Login rate-limited", ['ip' => $clientIp, 'username' => $username]);
            $error = t('auth.too_many_attempts');
        } else {
            $user           = null;
            $enabledMethods = $this->auth->getEnabledMethods();

            if (in_array(AUTH_LOCAL, $enabledMethods, true)) {
                $user = $this->auth->attempt($username, $password, AUTH_LOCAL);
            }
            if (!$user && in_array(AUTH_LDAP, $enabledMethods, true)) {
                $user = $this->auth->attempt($username, $password, AUTH_LDAP);
            }

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

                if (!str_starts_with($redirect, '/') || str_starts_with($redirect, '//')) {
                    $redirect = '/';
                }
                $this->redirect($redirect);
            }

            LoginThrottle::record($clientIp, $username, false);
            $error = t('auth.login_error');
            $this->logger->warning("Failed login attempt", ['username' => $username, 'ip' => $clientIp]);
        }

        $this->ensureCsrf();

        $this->view(WEBROOT_PATH . '/views/login.php', [
            'error'          => $error,
            'redirect'       => $redirect,
            'enabledMethods' => $this->auth->getEnabledMethods(),
            'postedUsername'  => $username,
        ]);
    }

    public function logout(): void
    {
        if ($this->auth->isLoggedIn()) {
            $this->logger->info("User logged out", ['username' => $this->currentUser['username'] ?? '']);
        }
        Session::destroy();
        $this->redirect('/login');
    }
}
