<?php

/**
 * Admin-menu dispatcher for the plugin's Customlink tabs. JTL renders each Customlink by
 * `require`-ing this file (see PluginController::renderMenu) with $oPlugin, $smarty and $menu in
 * scope. We map the tab's stored name ($menu->name) to a fixed controller via an ALLOWLIST — never
 * interpolating the name into a class string — so a tab name with spaces/`&` is safe and no
 * arbitrary class can be instantiated. Unknown names render nothing.
 */

declare(strict_types=1);

use JTL\Plugin\PluginInterface;
use Plugin\tnt_mcp\adminmenu\Controller\Activity;
use Plugin\tnt_mcp\adminmenu\Controller\Ai;
use Plugin\tnt_mcp\adminmenu\Controller\Start;
use Plugin\tnt_mcp\adminmenu\Controller\TokensAudit;

/** @var PluginInterface|null $oPlugin */
$tntMcpPlugin = $oPlugin ?? null;
if (!$tntMcpPlugin instanceof PluginInterface) {
    return;
}

// $menu is injected by the shop's admin menu dispatcher; it is untyped at this point, so the
// is_object()/isset() guards below are real runtime checks — do not narrow this to \stdClass.
/** @var mixed $menu */
$tntMcpTabName = (isset($menu) && \is_object($menu) && isset($menu->name)) ? (string)$menu->name : '';

// The old tab names stay mapped: JTL keeps a shop's stored Customlinks until the plugin is
// updated, and a bookmark or a `?cPluginTab=` link from an assistant's instruction outlives the
// rename. An unknown name still renders nothing.
$tntMcpControllers = [
    'Start'             => Start::class,
    'Server-Status'     => Start::class,
    'Integrationen'     => Start::class,
    'Aktivität'         => Activity::class,
    'Anfrage-Protokoll' => Activity::class,
    'Änderungen'        => Activity::class,
    'Zugriff'           => TokensAudit::class,
    'Tokens & Audit'    => TokensAudit::class,
    'KI'                => Ai::class,
];

$tntMcpController = $tntMcpControllers[$tntMcpTabName] ?? null;
if ($tntMcpController === null) {
    return;
}

// The tab name is handed on so a controller can link back to its OWN pane (`cPluginTab`); without
// it every self-link lands on the plugin page's first tab.
(new $tntMcpController($tntMcpPlugin, $tntMcpTabName))->render();
