<?php

class AuthController extends Controller
{
    public function showLogin(): void
    {
        if (Auth::check()) {
            $this->redirect('dashboard');
        }
        $this->view('auth.login', ['csrf' => $this->csrfField()], null);
    }

    public function login(): void
    {
        $this->verifyCsrf();

        $username = trim($this->input('username', ''));
        $password = $this->input('password', '');

        if ($username === '' || $password === '') {
            $this->view('auth.login', ['error' => 'Please enter username and password.', 'csrf' => $this->csrfField()], null);
            return;
        }

        if (Auth::attempt($username, $password)) {
            $this->redirect('dashboard');
            return;
        }

        $this->view('auth.login', ['error' => 'Invalid username or password.', 'csrf' => $this->csrfField()], null);
    }

    public function logout(): void
    {
        Auth::logout();
        $this->redirect('login');
    }
}
