<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/database.php';

function is_logged_in(): bool
{
    return isset($_SESSION['user']);
}

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

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

function require_admin(): void
{
    require_login();

    if ((current_user()['role'] ?? '') !== 'Admin') {
        http_response_code(403);
        exit('Access denied.');
    }
}

function log_activity(mysqli $conn, string $action, string $details = ''): void
{
    $user = current_user();
    $userId = $user['id'] ?? null;
    $username = $user['username'] ?? null;

    db_execute(
        $conn,
        'INSERT INTO activity_logs (user_id, username, action, details)
         VALUES (?, ?, ?, ?)',
        'isss',
        [$userId, $username, $action, $details]
    );
}
