<?php
require_once __DIR__ . '/db.php';

function auth_start(): void {
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
}

function auth_user(): ?array {
  auth_start();
  return $_SESSION['user'] ?? null;
}

function require_login(): array {
  $u = auth_user();
  if (!$u) {
    header("Location: login.php");
    exit;
  }
  return $u;
}

function require_role(array $roles): array {
  $u = require_login();
  if (!in_array($u['role'], $roles, true)) {
    http_response_code(403);
    exit("Forbidden");
  }
  return $u;
}
