<?php
declare(strict_types=1);

function start_session(array $config): void {
  if (session_status() === PHP_SESSION_NONE) {
    session_name($config['app']['session_name']);
    session_start();
  }
}

function require_login(array $config): void {
  start_session($config);
  if (empty($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
  }
}

function login_user(array $config, int $id, string $name, string $role): void {
  start_session($config);
  session_regenerate_id(true);
  $_SESSION['user_id'] = $id;
  $_SESSION['user_name'] = $name;
  $_SESSION['user_role'] = $role;
}

function logout_user(array $config): void {
  start_session($config);
  $_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();
}
