<?php

declare(strict_types=1);

require_once __DIR__ . '/app/core/auth.php';
require_once __DIR__ . '/app/core/csrf.php';

$loginRedirect = 'app/public/index.php?login=1';

if (is_logged_in()) {
    redirect('dashboard.php');
}

if (is_post()) {
    require_valid_csrf();
    remember_old_input($_POST);

    $email = trim((string) ($_POST['email'] ?? ''));
    $password = (string) ($_POST['password'] ?? '');

    if ($email === '' || $password === '') {
        flash('error', ['type' => 'danger', 'message' => 'Email and password are required.']);
    } elseif (attempt_login($email, $password)) {
        clear_old_input();
        flash('success', ['type' => 'success', 'message' => 'Welcome back to JLFC.']);
        redirect_after_login();
    } else {
        flash('error', ['type' => 'danger', 'message' => 'Invalid credentials or inactive account.']);
    }

    redirect($loginRedirect);
}

redirect($loginRedirect);
