<?php
session_start();

// Benutzerdatenbank
$valid_users = array(
    'admin' => array(
        'password' => 'Jennifer@1996+',
        'access_level' => 'all'
    ),
    'Lager' => array(
        'password' => 'MediaMarkt',
        'access_level' => 'limited'
    )
);

function authenticate($username, $password) {
    global $valid_users;
    
    if (array_key_exists($username, $valid_users) && $valid_users[$username]['password'] === $password) {
        $_SESSION['authenticated'] = true;
        $_SESSION['username'] = $username;
        $_SESSION['access_level'] = $valid_users[$username]['access_level'];
        $_SESSION['last_activity'] = time(); // Zeitstempel für die letzte Aktion setzen
        
        // Weiterleitung basierend auf der Benutzerrolle
        if ($_SESSION['access_level'] === 'all') {
            header('Location: public/admin.php');
            exit;
        } elseif ($_SESSION['access_level'] === 'limited') {
            header('Location: public/search.php');
            exit;
        }
        
        return true;
    } else {
        return false;
    }
}

function is_authenticated() {
    return isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true;
}

function require_login() {
    if (!is_authenticated()) {
        header('Location: public/search.php');
        exit;
    }
}

function require_admin_login() {
    require_login();
    if ($_SESSION['access_level'] !== 'all') {
        header('Location: unauthorized.php');
        exit;
    }
}

function require_limited_access_login() {
    require_login();
    if ($_SESSION['access_level'] !== 'limited') {
        header('Location: unauthorized.php');
        exit;
    }
}

function get_authenticated_username() {
    return $_SESSION['username'] ?? null;
}
?>
