<?php

session_start();
require('app/app.php');

if (is_user_authenticated()) {
    redirect('./');
    exit;
}

$error_message = "";
$items = '';

if (is_post()) {

    $username = sanitize($_POST['username']);
    $password = sanitize($_POST['password']);

    // Check if fields are not empty
    if (!empty($username) && !empty($password)) {

        // Check if user is locked
        Data::get_record_is_locked($username);

        // Check if user is already logged in
        Data::get_record_is_online($username);

        // Validate login
        $items = Data::get_record_login($username, $password);

        // ✅ Check if credentials are valid
        if ($items && is_array($items)) {
            // Save to session, redirect to dashboard
            $_SESSION['username'] = $username;
            $_SESSION['logged_in'] = true; // ✅ Add this line
            redirect('./');
            exit;
        } else {
            // Invalid username or password
            echo "<script>alert('Incorrect username or password.');</script>";
        }

    } else {
        // Empty input fields
        echo "<script>alert('Username and password are required.');</script>";
    }
}

view('login', $items);


