<?php

/**
 * @file bootstrap.php
 * @brief Zentrale Initialisierung der Anwendung
 *
 * Startet die Session, lädt die Datenbankverbindung
 * und aktualisiert die Benutzerrollen.
 */

require_once __DIR__ . '/db.php';

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

if (session_status() !== PHP_SESSION_ACTIVE)
{
    // Session-Cookie Lifetime auf 30 Tage setzen
    session_set_cookie_params([
        'lifetime' => 60 * 60 * 24 * 30, // 30 days
        'path' => '/',
        'domain' => '',
        'secure' => false,
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
    session_start();
}


// Rollen bei jedem Request aus der DB aktualisieren
if (!empty($_SESSION['user_id']))
{
    $__bsConn = db_connect();
    $__bsStmt = $__bsConn->prepare('SELECT r.name FROM userRoles ur JOIN roles r ON r.roleID = ur.roleID WHERE ur.userID = ?');

    if ($__bsStmt)
    {
        $__bsUid = (int)$_SESSION['user_id'];
        $__bsStmt->bind_param('i', $__bsUid);
        $__bsStmt->execute();
        $__bsResult = $__bsStmt->get_result();
        $_SESSION['user_roles'] = [];

        while ($__bsRow = $__bsResult->fetch_assoc())
        {
            $_SESSION['user_roles'][] = $__bsRow['name'];
        }

        $__bsStmt->close();
    }

    $__bsConn->close();
}
else
{
    $_SESSION['user_roles'] = [];
}

?>
