<?php
/**
 * Antara — auth guard. Include this at the very top of any page that should
 * respect the global "login_required" toggle.
 *
 * Behaviour:
 *   - If login_required = false → returns silently (no enforcement).
 *   - If login_required = true and no session → redirect to /login/.
 *   - If user is blocked / inactive / soft-deleted → logout + redirect.
 *   - If session expired (idle > timeout) → logout + redirect.
 *   - Optional role check via antara_guard_require_role(['super_admin', ...]).
 *
 * The redirect target preserves the originally requested URI in `?next=`.
 */

require_once __DIR__ . '/bootstrap_auth.php';

if (!function_exists('antara_login_url_root')) {
    function antara_login_url_root(): string
    {
        require_once dirname(__DIR__, 2) . '/includes/install_public.php';
        return antara_public_auth_entry_url();
    }
}

if (!function_exists('antara_redirect_to_login')) {
    function antara_redirect_to_login(string $reason = ''): void
    {
        $url = antara_login_url_root();
        $next = $_SERVER['REQUEST_URI'] ?? '';
        $qs = [];
        if ($next !== '' && stripos($next, '/login/') === false) $qs['next'] = $next;
        if ($reason) $qs['reason'] = $reason;
        if ($qs) $url .= '?' . http_build_query($qs);
        if (!headers_sent()) {
            header('Location: ' . $url, true, 302);
        } else {
            echo '<script>location.replace(' . json_encode($url) . ');</script>';
        }
        exit;
    }
}

if (!function_exists('antara_guard_run')) {
    function antara_guard_run(): void
    {
        try {
            $cfg = AntaraStore::configRead();
        } catch (\RuntimeException $e) {
            require_once __DIR__ . '/vault_config_recovery.php';
            antara_vault_config_recovery_respond_and_exit($e);
        }
        if (empty($cfg['login_required'])) return; // free access

        $u = AntaraSession::user();
        if (!$u) antara_redirect_to_login('login_required');

        $fresh = AntaraStore::findUserById($u['id']);
        if (!$fresh || !empty($fresh['deletedAt'])) {
            AntaraSession::destroy();
            antara_redirect_to_login('account_removed');
        }
        if (!empty($fresh['blocked']) || empty($fresh['active'])) {
            AntaraSession::destroy();
            antara_redirect_to_login('blocked');
        }
        if (AntaraSession::isExpired((int)$cfg['session_timeout_minutes'])) {
            AntaraSession::destroy();
            antara_redirect_to_login('expired');
        }
        AntaraSession::touch();
    }
}

if (!function_exists('antara_guard_require_role')) {
    function antara_guard_require_role(array $allowed): void
    {
        $u = AntaraSession::user();
        if (!$u) antara_redirect_to_login('login_required');
        if (!in_array($u['role'] ?? '', $allowed, true)) {
            require_once dirname(__DIR__, 2) . '/includes/install_public.php';
            antara_install_render_help_page([
                'title' => '403 — Permisos insuficientes',
                'message' => 'No tienes permisos para acceder a esta sección. Si necesitas acceso de administración, inicia sesión con una cuenta autorizada o contacta al responsable del sistema.',
                'show_install_link' => true,
                'http_status' => 403,
            ]);
        }
    }
}

// Always run on include.
antara_guard_run();
