<?php
include __DIR__ . ('/user-ssinclude/user-init.php');

// logout
if (isset($_GET['logout'])) {
    if (isset($_COOKIE['user_session_id'])) {
        $sessionId = $_COOKIE['user_session_id'];
        destroySession($sessionId);
        setcookie('user_session_id', '', time() - 3600, '/', '', true, true);
    }
    js_redirect(user_login);
    exit();
}

// Try login
try {

    $pin = verif_posted('user_login'); // 8-digit PIN from form
    // basic validation
    if (!preg_match('/^[0-9]{8}$/', $pin)) {
        header("location:" . user_login . "?err=invalid_pin");
        exit();
    }

    // Step 1: get all users
    $stmt = $db->prepare("SELECT employee_id, first_name, last_name, email, id_number,schedule_group,password FROM employees");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $user = null;

    // Step 2: find the correct PIN match
    foreach ($users as $u) {
        if (!empty($u["password"]) && decrypt_pin($u["password"]) === $pin) {
            $user = $u;
            break;
        }
    }

    if ($user) {

        // SESSION
        $sessionId = generateSessionId();

        $sessionData = [
            'EMPLOYEE_AUTHORIZED' => true,
            'EMPLOYEE_ID'         => $user["employee_id"],
            'EMPLOYEE_FIRSTNAME'  => $user["first_name"],
            'EMPLOYEE_LASTNAME'   => $user["last_name"],
            'EMPLOYEE_EMAIL'      => $user["email"],
            'EMPLOYEE_ID_NUMBER'  => $user["id_number"],
            'EMPLOYEE_GROUP'  => $user["schedule_group"],
            'last_activity'       => time()
        ];

        storeSession($sessionId, $sessionData);

        // cookie
        $cookie_domain = parse_url(app_domain_hostname, PHP_URL_HOST);
        $cookie_path   = "/";

        setcookie(
            'user_session_id',
            $sessionId,
            time() + session_lifetime,
            $cookie_path,
            $cookie_domain,
            isset($_SERVER['HTTPS']),
            true
        );

        // update last login
        try {
            $sql = "UPDATE employees SET last_logged_in = NOW() 
                    WHERE employee_id = :id";
            $stmt = $db->prepare($sql);
            $stmt->execute(['id' => $user["employee_id"]]);

            header("location:" . user_home . "?status=logged");
            exit();
        } catch (PDOException $e) {
            header("location:" . user_login . "?err=failed");
            exit();
        }

    } else {
        header("location:" . user_login . "?err=failed");
        exit();
    }

} catch (PDOException $e) {
    header("location:" . user_login . "?err=failed");
    exit();
}
?>
