<?php

class AuthController extends Controller
{
    public function showLogin(): void
    {
        if (Auth::check()) {
            $this->redirect('/dashboard');
        }

        $this->view('auth/login', [], 'auth');
        clear_old();
    }

    public function login(): void
    {
        Csrf::verify();
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (!$email || !$password) {
            set_old($_POST);
            $this->flash('danger', 'Email and password are required.');
            $this->redirect('/login');
        }

        if (!Auth::attempt($email, $password)) {
            set_old($_POST);
            $this->flash('danger', 'Invalid login details.');
            $this->redirect('/login');
        }

        clear_old();
        $this->redirect('/dashboard');
    }

    public function logout(): void
    {
        Auth::logout();
        header('Location: ' . url('/login'));
        exit;
    }
}
