<?php
session_start();

require_once "{$_SERVER['DOCUMENT_ROOT']}/login/php/authFunctions.php";

if (checkLoginAttempts() > 3) {
    header('Location: /login/');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        setcookie('login_error', 'Invalid username or password', time() + 3600, '/');
        header('Location: /login/');
        exit;
    }

    if ($username !== 'superuser' && !filter_var($username, FILTER_VALIDATE_EMAIL)) {
        setcookie('login_error', 'Invalid email address', time() + 3600, '/');
        header('Location: /login/');
        exit;
    }

    $stmt = $GLOBALS['conn']->prepare("SELECT * FROM system_users WHERE user_email = ? LIMIT 1");
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if (!$user) {
        setcookie('login_error', 'Invalid username or password', time() + 3600, '/');
        addLoginAttempts();
        header('Location: /login/');
        exit;
    }

    if (!password_verify($password, $user['user_password'])) {
        setcookie('login_error', 'Invalid username or password', time() + 3600, '/');
        addLoginAttempts();
        header('Location: /login/');
        exit;
    }

    switch ($user['user_status']) {
        case 'banned':
            setcookie('login_error', 'Account is banned.', time() + 3600, '/');
            header('Location: /login/');
            exit;
        case 'inactive':
            setcookie('login_error', 'Account is inactive.', time() + 3600, '/');
            header('Location: /login/');
            exit;
        case 'pending':
            setcookie('login_error', 'Account is pending approval.', time() + 3600, '/');
            header('Location: /login/');
            exit;
        case 'active':
            // continue
            break;
        default:
            setcookie('login_error', 'something went wrong, contact support', time() + 3600, '/');
            header('Location: /login/');
            exit;
    }

    setTimeZoneCookie();

    # check if mfa2 is enabled
    if ($user['user_two_factor_enabled'] == 1) {
        # go to the mfa login
        session_regenerate_id(true); # create session to store some data
        $_SESSION['mfa'] = ['user_uuid' => $user['user_uuid'], 'user_secret' => $user['user_two_factor_secret']];
        header('Location: /login/');
    } else {
        # No mfa2 is set up

        loginUser($user['user_uuid']);
        header('Location: /');
    }
    exit;

}

