<?php
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';
AdminAuth::requireLogin();

$pageTitle = "Système";

$_db         = new Database();
$_cache      = new SystemCache($_db->getPDO());
$_controller = new SystemController($_db, $_cache);

if (isset($_GET['refresh']) && $_GET['refresh'] === '1') {
    $_controller->invalidateAll();
}

// ── Status / PHP / Disk data ──────────────────────────────────────────────────
$statusData     = $_controller->getStatusData();
$checks         = $statusData['checks'];
$statusCached   = $statusData['cached'];
$statusCacheAge = $statusData['cacheAge'];

$phpInfo  = $_controller->getPhpInfo();
$diskInfo = $_controller->getDiskInfo();

$diskTotal = $diskInfo['total'];
$diskFree  = $diskInfo['free'];
$diskUsed  = $diskInfo['used'];
$diskPct   = $diskInfo['pct'];
$diskColor = SystemController::diskColor($diskPct);

// ── Active tab + line count ───────────────────────────────────────────────────
$activeTab = $_GET['tab'] ?? 'nginx_access';
if ($activeTab === 'status') {
    $activeTab = 'nginx_access';
} elseif ($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;
}

// ── Tab content data ──────────────────────────────────────────────────────────
$logLines    = null;
$logError    = null;
$logFileMeta = null;

$nginxConfigLines  = null;
$nginxConfigSource = null;
$nginxConfigError  = null;
$nginxConfigMeta   = null;

if ($activeTab === 'nginx_config') {
    $nginxData         = $_controller->getNginxConfigData();
    $nginxConfigLines  = $nginxData['lines'];
    $nginxConfigSource = $nginxData['source'];
    $nginxConfigMeta   = $nginxData['meta'];
    $nginxConfigError  = $nginxData['error'];
} else {
    $logData     = $_controller->getLogData($activeTab, $selectedN);
    $logLines    = $logData['lines'];
    $logError    = $logData['error'];
    $logFileMeta = $logData['meta'];
}

$isAdmin = true; $bodyClass = 'admin-body';
$extraCss = ['/assets/css/system.css'];
require_once APP_ROOT . '/templates/head.php';

$collapsed = $_COOKIE['sys_collapsed'] ?? null;
$statusInitiallyCollapsed = $collapsed === '1';

include APP_ROOT . '/templates/header.php';
include APP_ROOT . '/templates/admin/system.php';
require_once APP_ROOT . '/templates/admin/footer.php';
