<?php
// logviewer/inc/auth.php

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

function app_config(): array {
    static $cfg = null;
    if ($cfg === null) {
        $cfg = require __DIR__ . '/../config/config.php';
        date_default_timezone_set($cfg['timezone'] ?? 'UTC');
    }
    return $cfg;
}

function is_logged_in(): bool {
    return !empty($_SESSION['lv_user']);
}

function require_login(): void {
    if (!is_logged_in()) {
        header('Location: index.php');
        exit;
    }
}

function login_attempt(string $username, string $password): bool {
    $cfg = app_config();
    $validUser = (string)($cfg['auth']['username'] ?? '');
    $validPass = (string)($cfg['auth']['password'] ?? '');

    if ($username === $validUser && $password === $validPass) {
        $_SESSION['lv_user'] = $username;
        $_SESSION['lv_login_time'] = time();
        session_regenerate_id(true);
        return true;
    }

    return false;
}

function logout_user(): void {
    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params['path'],
            $params['domain'],
            $params['secure'],
            $params['httponly']
        );
    }

    session_destroy();
}