<?php
/**
 * system-fragment.php — returns only the tab-panel HTML for the admin system page.
 *
 * Called by fetch() from system.php JS when switching tabs or changing line count.
 * With JS disabled the user never hits this URL directly; the tab <a> hrefs still
 * point at system.php?tab=… so navigation degrades gracefully.
 *
 * Response: text/html fragment (no <html>/<head>/<body> wrapper).
 * On any auth failure or bad request: 403 / 400 with a plain-text body.
 */
require_once __DIR__ . "/../../bootstrap.php";
require_once __DIR__ . '/../../src/AdminAuth.php';
require_once APP_ROOT . '/src/Database.php';
require_once APP_ROOT . '/src/SystemCache.php';
require_once APP_ROOT . '/src/Controllers/SystemController.php';

if (!AdminAuth::isAuthenticated()) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Non autorisé';
    exit;
}

// ── Validate inputs ────────────────────────────────────────────────────────
$activeTab = $_GET['tab'] ?? 'nginx_access';
if ($activeTab !== 'nginx_config' && !array_key_exists($activeTab, SystemController::LOG_FILES)) {
    $activeTab = 'nginx_access';
}

$selectedN = isset($_GET['n']) ? (int) $_GET['n'] : 100;
if (!in_array($selectedN, SystemController::ALLOWED_LINES, true)) {
    $selectedN = 100;
}

header('Content-Type: text/html; charset=utf-8');
header('X-Robots-Tag: noindex');

// ── Build data via controller ──────────────────────────────────────────────
$_db         = new Database();
$_cache      = new SystemCache($_db->getPDO());
$_controller = new SystemController($_db, $_cache);

// ── Render ─────────────────────────────────────────────────────────────────
if ($activeTab === 'nginx_config') {
    $nginxData         = $_controller->getNginxConfigData();
    $nginxConfigLines  = $nginxData['lines'];
    $nginxConfigSource = $nginxData['source'];
    $nginxConfigMeta   = $nginxData['meta'];
    $nginxConfigError  = $nginxData['error'];

    include APP_ROOT . '/templates/admin/partials/system-nginx-config-panel.php';
} else {
    $logData     = $_controller->getLogData($activeTab, $selectedN);
    $logLines    = $logData['lines'];
    $logError    = $logData['error'];
    $logFileMeta = $logData['meta'];

    include APP_ROOT . '/templates/admin/partials/system-log-panel.php';
}
