<?php
/**
 * Shared authentication + authorization guard for entry points.
 *
 * Usage (JSON/AJAX endpoint):
 *     require_once __DIR__ . '/../includes/require_auth.php';
 *     require_login();                          // any signed-in user
 *     require_role(['admin', 'accountant']);    // restrict by role
 *
 * Usage (full page):
 *     require_once __DIR__ . '/includes/require_auth.php';
 *     require_login('redirect');
 *
 * Response mode ($as): 'json' (default) | 'html' | 'redirect'.
 */

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

if (!function_exists('auth_user_id')) {
    function auth_user_id(): int
    {
        return isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : 0;
    }

    function auth_role(): string
    {
        return isset($_SESSION['role']) ? (string) $_SESSION['role'] : '';
    }

    function auth_unauthorized_exit(string $as): void
    {
        http_response_code(401);
        if ($as === 'redirect') {
            header('Location: index.php');
            exit;
        }
        if ($as === 'html') {
            echo '<p class="text-danger">Unauthorized. Please sign in again.</p>';
            exit;
        }
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }
        echo json_encode(['success' => false, 'message' => 'Unauthorized. Please sign in again.']);
        exit;
    }

    function auth_forbidden_exit(string $as): void
    {
        http_response_code(403);
        if ($as === 'redirect') {
            header('Location: dashboard.php?error=access_denied');
            exit;
        }
        if ($as === 'html') {
            echo '<p class="text-danger">Access denied.</p>';
            exit;
        }
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }
        echo json_encode(['success' => false, 'message' => 'Access denied.']);
        exit;
    }

    /** Reject the request unless a user is signed in. */
    function require_login(string $as = 'json'): void
    {
        if (auth_user_id() <= 0) {
            auth_unauthorized_exit($as);
        }
    }

    /** Reject the request unless the signed-in user holds one of $roles. */
    function require_role(array $roles, string $as = 'json'): void
    {
        require_login($as);
        if (!in_array(auth_role(), $roles, true)) {
            auth_forbidden_exit($as);
        }
    }
}
