<?php

use Illuminate\Support\Collection;
use Mtc\Core\Admin\Menu;
use Mtc\Core\Admin\TotpService;
use Mtc\Core\Permissions;

$adminuser = new AdminUser();
$menuID = $adminuser->menuID($_SERVER['SCRIPT_NAME']);
if (!empty($_SESSION['adminId'])
    && !AdminUser::can($menuID, $_SESSION['adminId'])
    && $menuID > 0
) {
    header("Location: /admin/index.php?access=none");
    exit();
}

if (!empty($_SESSION['adminId'])) {
    Permissions::initPermissions();

    // Force 2FA setup for users who have logged in but never configured TOTP
    // Skip when impersonating — the original admin already passed 2FA via sudo
    $currentAdmin = \Mtc\Core\AdminUser::query()->find($_SESSION['adminId']);
    if ($currentAdmin
        && empty($currentAdmin->totp_secret)
        && !TotpService::isExempt($currentAdmin->username)
        && empty($_SESSION['admin_impersonating_from'])
    ) {
        $_SESSION['admin_2fa_pending_id'] = $_SESSION['adminId'];
        $_SESSION['admin_2fa_pending_at'] = time();
        unset($_SESSION['adminId']);
        unset($_SESSION['mtcadminarea']);
        header('Location: /admin/2fa_setup.php');
        exit();
    }

    $twig->addGlobal('admin_id', $_SESSION['adminId']);
    $twig->addGlobal('admin_user', $adminuser);

    $twigGlobals = $twig->getGlobals();
    if (empty($twigGlobals[Menu::GLOBAL_KEY])) {
        /** @var Collection $adminMenu */
        $adminMenu = Menu::getAdminMenu();
        $twig->addGlobal(Menu::GLOBAL_KEY, $adminMenu);
    }
} else {
    header("Location: /admin/login.php?redir=" . urlencode($_SERVER['REQUEST_URI']));
    exit();
}
