<?php
/**
 * Diagnostico DokuWiki - SIE/NICC
 * ================================
 * Escanea cualquier subdominio desde la ubicacion central diagnosticos/.
 * Accede via: DOKU_BASE/lib/plugins/siedeployer/diagnosticos/test_dokuwiki.php
 *
 * PARAMETROS:
 *   ?sub=nombre   - Escanear un subdominio especifico
 *   (sin parametro muestra selector de subdominios)
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('memory_limit', '64M');

// ============================================================
// CONFIGURACION - RUTA BASE DE SUBDOMINIOS
// ============================================================

$basePath = '/home/systeng3/public_html';

$excluir = ['.', '..', 'cgi-bin', '.well-known', '.trash', '.htaccess',
            'respaldo', 'diagnosticos', 'tmp', 'error_log'];

// ============================================================
// PARAMETROS DE ENTRADA
// ============================================================

$targetSub = isset($_GET['sub']) ? trim($_GET['sub']) : '';

// Limpiar: si pasan URL completa, extraer solo el subdominio
if (!empty($targetSub)) {
    if (preg_match('#^https?://#i', $targetSub)) {
        $parsed = parse_url($targetSub);
        if (isset($parsed['host'])) {
            $parts = explode('.', $parsed['host']);
            $targetSub = $parts[0];
        }
    }
    $targetSub = basename(preg_replace('/[^a-zA-Z0-9._-]/', '', $targetSub));
}

// ============================================================
// ESCANEAR SUBDOMINIOS DISPONIBLES
// ============================================================

$subdominios = [];
if (is_dir($basePath)) {
    $items = @scandir($basePath);
    if ($items) {
        foreach ($items as $item) {
            if (in_array($item, $excluir)) continue;
            $subPath = "$basePath/$item";
            if (!is_dir($subPath)) continue;
            // Solo incluir si tiene doku.php (es un DokuWiki)
            if (file_exists("$subPath/doku.php")) {
                $subdominios[] = $item;
            }
        }
        sort($subdominios);
    }
}

// ============================================================
// SI NO HAY SUB SELECCIONADO -> MOSTRAR SELECTOR
// ============================================================

if (empty($targetSub)) {
    ?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Test DokuWiki - Selector de Subdominio</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #1a1a2e; color: #e0e0e0; padding: 20px; }
        h1 { color: #00d4ff; text-align: center; margin-bottom: 5px; font-size: 24px; }
        .subtitle { text-align: center; color: #888; margin-bottom: 20px; font-size: 14px; }
        .selector-box { max-width: 700px; margin: 20px auto; background: #16213e; border: 1px solid #0f3460; border-radius: 8px; padding: 20px; }
        .selector-box h2 { color: #e94560; font-size: 16px; margin-bottom: 15px; }
        select { width: 100%; padding: 10px; font-size: 15px; background: #0d1117; color: #e0e0e0; border: 1px solid #0f3460; border-radius: 4px; margin-bottom: 15px; }
        .btn { display: inline-block; padding: 10px 25px; background: #e94560; color: #fff; border: none; border-radius: 4px; font-size: 14px; cursor: pointer; text-decoration: none; }
        .btn:hover { background: #ff6b6b; }
        .btn:disabled { background: #555; cursor: not-allowed; }
        .count { text-align: center; color: #aaa; margin-bottom: 10px; font-size: 13px; }
        .search-box { width: 100%; padding: 8px 12px; font-size: 14px; background: #0d1117; color: #e0e0e0; border: 1px solid #0f3460; border-radius: 4px; margin-bottom: 10px; }
    </style>
</head>
<body>
<h1>&#128269; Test DokuWiki - SIE/NICC</h1>
<p class="subtitle">Seleccione un subdominio para diagnosticar</p>
<p class="count"><?php echo count($subdominios); ?> subdominios DokuWiki detectados en <?php echo htmlspecialchars($basePath); ?></p>

<div class="selector-box">
    <h2>Seleccionar Subdominio</h2>
    <input type="text" class="search-box" id="buscar" placeholder="Buscar subdominio..." oninput="filtrar()">
    <form method="get" id="formSub">
        <select name="sub" id="selectSub" size="15">
            <?php foreach ($subdominios as $s): ?>
            <option value="<?php echo htmlspecialchars($s); ?>"><?php echo htmlspecialchars($s); ?></option>
            <?php endforeach; ?>
        </select>
        <br>
        <button type="submit" class="btn" id="btnDiag">&#128269; Diagnosticar Subdominio</button>
    </form>
</div>

<script>
function filtrar() {
    var txt = document.getElementById('buscar').value.toLowerCase();
    var opts = document.getElementById('selectSub').options;
    for (var i = 0; i < opts.length; i++) {
        opts[i].style.display = opts[i].value.toLowerCase().indexOf(txt) >= 0 ? '' : 'none';
    }
}
</script>
</body>
</html>
    <?php
    exit;
}

// ============================================================
// VALIDAR QUE EL SUBDOMINIO EXISTE
// ============================================================

$siteRoot = "$basePath/$targetSub";

if (!is_dir($siteRoot)) {
    echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Error</title></head><body style='background:#1a1a2e;color:#ff4444;font-family:sans-serif;padding:40px;text-align:center;'>";
    echo "<h1>&#10060; Subdominio no encontrado</h1>";
    echo "<p>No existe el directorio: <code>" . htmlspecialchars($siteRoot) . "</code></p>";
    echo "<p><a href='?' style='color:#00d4ff;'>Volver al selector</a></p>";
    echo "</body></html>";
    exit;
}

if (!file_exists("$siteRoot/doku.php")) {
    echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Error</title></head><body style='background:#1a1a2e;color:#ff8800;font-family:sans-serif;padding:40px;text-align:center;'>";
    echo "<h1>&#9888; No es un DokuWiki</h1>";
    echo "<p>El directorio <code>" . htmlspecialchars($targetSub) . "</code> no contiene doku.php</p>";
    echo "<p><a href='?' style='color:#00d4ff;'>Volver al selector</a></p>";
    echo "</body></html>";
    exit;
}

// ============================================================
// FUNCIONES AUXILIARES
// ============================================================

function checkFile($path, $label = '') {
    $exists = file_exists($path);
    $readable = $exists ? is_readable($path) : false;
    $size = $exists ? filesize($path) : 0;
    $label = $label ?: basename($path);
    return [
        'label'    => $label,
        'path'     => $path,
        'exists'   => $exists,
        'readable' => $readable,
        'size'     => $size,
        'status'   => !$exists ? 'FALTA' : (!$readable ? 'SIN PERMISO' : 'OK'),
    ];
}

function checkDir($path, $label = '') {
    $exists = is_dir($path);
    $readable = $exists ? is_readable($path) : false;
    $count = 0;
    if ($exists && $readable) {
        $items = @scandir($path);
        $count = $items ? count(array_diff($items, ['.', '..'])) : 0;
    }
    $label = $label ?: basename($path);
    return [
        'label'    => $label,
        'path'     => $path,
        'exists'   => $exists,
        'readable' => $readable,
        'count'    => $count,
        'status'   => !$exists ? 'FALTA' : (!$readable ? 'SIN PERMISO' : ($count === 0 ? 'VACIO' : "OK ($count items)")),
    ];
}

function statusColor($status) {
    if (strpos($status, 'FALTA') !== false) return '#ff4444';
    if (strpos($status, 'VACIO') !== false) return '#ff8800';
    if (strpos($status, 'SIN PERMISO') !== false) return '#ff4444';
    if (strpos($status, 'OK') !== false) return '#44cc44';
    return '#cccccc';
}

function statusIcon($status) {
    if (strpos($status, 'FALTA') !== false) return '&#10060;';
    if (strpos($status, 'VACIO') !== false) return '&#9888;';
    if (strpos($status, 'SIN PERMISO') !== false) return '&#128274;';
    if (strpos($status, 'OK') !== false) return '&#9989;';
    return '&#8265;';
}

// ============================================================
// 1. INFORMACION PHP
// ============================================================
$phpInfo = [
    'PHP Version'       => PHP_VERSION,
    'SAPI'              => php_sapi_name(),
    'OS'                => PHP_OS,
    'display_errors'    => ini_get('display_errors'),
    'error_reporting'   => error_reporting(),
    'open_basedir'      => ini_get('open_basedir') ?: '(sin restriccion)',
    'disable_functions' => ini_get('disable_functions') ?: '(ninguna)',
    'memory_limit'      => ini_get('memory_limit'),
    'max_execution_time'=> ini_get('max_execution_time'),
    'document_root'     => $_SERVER['DOCUMENT_ROOT'] ?? 'N/A',
    'script_filename'   => $_SERVER['SCRIPT_FILENAME'] ?? 'N/A',
    'site_root (target)' => $siteRoot,
];

// ============================================================
// 2. ARCHIVOS CRITICOS DE DOKUWIKI (sin estos NO arranca)
// ============================================================
$criticalFiles = [
    // Entry points
    checkFile("$siteRoot/doku.php", 'doku.php (entry point)'),
    checkFile("$siteRoot/index.php", 'index.php'),

    // Core initialization
    checkFile("$siteRoot/inc/init.php", 'inc/init.php (CORE - inicializacion)'),
    checkFile("$siteRoot/inc/load.php", 'inc/load.php (CORE - autoload)'),
    checkFile("$siteRoot/inc/defines.php", 'inc/defines.php (CORE - constantes)'),
    checkFile("$siteRoot/inc/confutils.php", 'inc/confutils.php (CORE - config utils)'),
    checkFile("$siteRoot/inc/common.php", 'inc/common.php (CORE - funciones comunes)'),
    checkFile("$siteRoot/inc/events.php", 'inc/events.php (CORE - eventos)'),
    checkFile("$siteRoot/inc/actions.php", 'inc/actions.php (CORE - acciones)'),
    checkFile("$siteRoot/inc/pageutils.php", 'inc/pageutils.php (CORE - paginas)'),
    checkFile("$siteRoot/inc/auth.php", 'inc/auth.php (CORE - autenticacion)'),
    checkFile("$siteRoot/inc/template.php", 'inc/template.php (CORE - template engine)'),
    checkFile("$siteRoot/inc/html.php", 'inc/html.php (CORE - HTML rendering)'),
    checkFile("$siteRoot/inc/infoutils.php", 'inc/infoutils.php (CORE - info)'),
    checkFile("$siteRoot/inc/parserutils.php", 'inc/parserutils.php (CORE - parser)'),
    checkFile("$siteRoot/inc/io.php", 'inc/io.php (CORE - I/O)'),
    checkFile("$siteRoot/inc/fulltext.php", 'inc/fulltext.php (CORE - busqueda)'),
    checkFile("$siteRoot/inc/utf8.php", 'inc/utf8.php (CORE - UTF8)'),
    checkFile("$siteRoot/inc/mail.php", 'inc/mail.php (CORE - correo)'),
    checkFile("$siteRoot/inc/ActionRouter.php", 'inc/ActionRouter.php (CORE - router)'),

    // Vendor autoload
    checkFile("$siteRoot/vendor/autoload.php", 'vendor/autoload.php (Composer)'),

    // Configuracion por defecto
    checkFile("$siteRoot/conf/dokuwiki.php", 'conf/dokuwiki.php (config por defecto)'),

    // Configuracion POR SITIO (estos NO vienen con NICC, son del sitio)
    checkFile("$siteRoot/conf/local.php", 'conf/local.php ** CRITICO: config del sitio **'),
    checkFile("$siteRoot/conf/acl.auth.php", 'conf/acl.auth.php ** CRITICO: permisos **'),
    checkFile("$siteRoot/conf/users.auth.php", 'conf/users.auth.php ** CRITICO: usuarios **'),
    checkFile("$siteRoot/conf/plugins.local.php", 'conf/plugins.local.php (plugins config)'),

    // .htaccess
    checkFile("$siteRoot/conf/.htaccess", 'conf/.htaccess (proteccion conf/)'),
    checkFile("$siteRoot/data/.htaccess", 'data/.htaccess (proteccion data/)'),
    checkFile("$siteRoot/.htaccess", '.htaccess (raiz - rewrite rules)'),
];

// ============================================================
// 3. DIRECTORIOS CRITICOS
// ============================================================
$criticalDirs = [
    checkDir("$siteRoot/inc", 'inc/ (core DokuWiki)'),
    checkDir("$siteRoot/inc/Action", 'inc/Action/'),
    checkDir("$siteRoot/inc/Extension", 'inc/Extension/'),
    checkDir("$siteRoot/inc/Parsing", 'inc/Parsing/'),
    checkDir("$siteRoot/vendor", 'vendor/ (dependencias)'),
    checkDir("$siteRoot/vendor/composer", 'vendor/composer/'),
    checkDir("$siteRoot/conf", 'conf/ (configuracion)'),
    checkDir("$siteRoot/conf/tpl", 'conf/tpl/ (config templates)'),
    checkDir("$siteRoot/lib", 'lib/'),
    checkDir("$siteRoot/lib/plugins", 'lib/plugins/'),
    checkDir("$siteRoot/lib/scripts", 'lib/scripts/'),
    checkDir("$siteRoot/lib/styles", 'lib/styles/'),
    checkDir("$siteRoot/lib/exe", 'lib/exe/'),
    checkDir("$siteRoot/lib/tpl", 'lib/tpl/'),
    checkDir("$siteRoot/lib/images", 'lib/images/'),
    checkDir("$siteRoot/data", 'data/'),
    checkDir("$siteRoot/data/pages", 'data/pages/'),
    checkDir("$siteRoot/data/media", 'data/media/'),
    checkDir("$siteRoot/data/meta", 'data/meta/'),
    checkDir("$siteRoot/data/cache", 'data/cache/'),
    checkDir("$siteRoot/data/tmp", 'data/tmp/'),
    checkDir("$siteRoot/bin", 'bin/'),
];

// ============================================================
// 4. TEMPLATE ACTIVO
// ============================================================
$templateInfo = [];
// Leer conf/local.php para saber que template usa
$localPhp = "$siteRoot/conf/local.php";
$activeTemplate = '(desconocido)';
if (file_exists($localPhp) && is_readable($localPhp)) {
    $localContent = file_get_contents($localPhp);
    if (preg_match("/\\\$conf\['template'\]\s*=\s*'([^']+)'/", $localContent, $m)) {
        $activeTemplate = $m[1];
    }
    $templateInfo['template_activo'] = $activeTemplate;
    $templateInfo['template_dir'] = checkDir("$siteRoot/lib/tpl/$activeTemplate", "lib/tpl/$activeTemplate/");
    $templateInfo['main_php'] = checkFile("$siteRoot/lib/tpl/$activeTemplate/main.php", "lib/tpl/$activeTemplate/main.php");
    $templateInfo['style_ini'] = checkFile("$siteRoot/lib/tpl/$activeTemplate/style.ini", "lib/tpl/$activeTemplate/style.ini");
} else {
    $templateInfo['error'] = 'No se puede leer conf/local.php para detectar template activo';
}

// ============================================================
// 5. PLUGINS INSTALADOS
// ============================================================
$pluginsList = [];
$pluginsDir = "$siteRoot/lib/plugins";
if (is_dir($pluginsDir)) {
    $items = scandir($pluginsDir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        if (is_dir("$pluginsDir/$item")) {
            $pluginsList[] = $item;
        }
    }
}

// ============================================================
// 6. CONTENIDO DE conf/
// ============================================================
$confFiles = [];
$confDir = "$siteRoot/conf";
if (is_dir($confDir)) {
    $items = scandir($confDir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $full = "$confDir/$item";
        $confFiles[] = [
            'name' => $item,
            'type' => is_dir($full) ? 'DIR' : 'FILE',
            'size' => is_file($full) ? filesize($full) : '-',
        ];
    }
}

// ============================================================
// 7. INTENTAR CARGAR DOKUWIKI Y CAPTURAR ERROR
// ============================================================
$loadError = null;
$loadSuccess = false;
$syntaxErrors = [];
ob_start();
try {
    // Verificar sintaxis de archivos clave
    if (file_exists("$siteRoot/inc/init.php")) {
        $filesToCheck = [
            "$siteRoot/inc/init.php",
            "$siteRoot/inc/load.php",
            "$siteRoot/conf/dokuwiki.php",
        ];
        if (file_exists($localPhp)) {
            $filesToCheck[] = $localPhp;
        }
        foreach ($filesToCheck as $f) {
            if (!file_exists($f)) continue;
            $output = [];
            $ret = 0;
            @exec("php -l " . escapeshellarg($f) . " 2>&1", $output, $ret);
            if ($ret !== 0) {
                $syntaxErrors[] = [
                    'file' => str_replace($siteRoot, '', $f),
                    'error' => implode("\n", $output),
                ];
            }
        }
    }
} catch (\Throwable $e) {
    $loadError = $e->getMessage() . "\n" . $e->getFile() . ':' . $e->getLine();
}
$outputBuffer = ob_get_clean();

// ============================================================
// 8. VERIFICAR ERROR LOG
// ============================================================
$errorLogContent = '';
$possibleLogs = [
    "$siteRoot/error_log",
    "$siteRoot/../error_log",
];
foreach ($possibleLogs as $logPath) {
    if ($logPath && file_exists($logPath) && is_readable($logPath)) {
        $fh = @fopen($logPath, 'r');
        if ($fh) {
            $fsize = filesize($logPath);
            $readBytes = min($fsize, 8192);
            if ($fsize > $readBytes) {
                fseek($fh, -$readBytes, SEEK_END);
            }
            $tail = fread($fh, $readBytes);
            fclose($fh);
            $lines = explode("\n", $tail);
            $lines = array_slice($lines, -30);
            $errorLogContent .= "=== $logPath (ultimo ~8KB, tamano total: " . number_format($fsize) . " bytes) ===\n";
            $errorLogContent .= implode("\n", $lines);
            $errorLogContent .= "\n\n";
        }
    }
}

// ============================================================
// 9. ARCHIVOS EN RAIZ
// ============================================================
$rootFiles = [];
$items = @scandir($siteRoot);
if ($items) {
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $full = "$siteRoot/$item";
        $rootFiles[] = [
            'name' => $item,
            'type' => is_dir($full) ? 'DIR' : 'FILE',
            'size' => is_file($full) ? filesize($full) : '-',
            'perms' => substr(sprintf('%o', fileperms($full)), -4),
        ];
    }
}

// ============================================================
// 10. PERMISOS ESCRITURA
// ============================================================
$writableDirs = [
    "$siteRoot/data"        => 'data/',
    "$siteRoot/data/cache"  => 'data/cache/',
    "$siteRoot/data/tmp"    => 'data/tmp/',
    "$siteRoot/data/meta"   => 'data/meta/',
    "$siteRoot/data/media"  => 'data/media/',
    "$siteRoot/data/pages"  => 'data/pages/',
    "$siteRoot/data/log"    => 'data/log/',
    "$siteRoot/data/index"  => 'data/index/',
    "$siteRoot/conf"        => 'conf/',
    "$siteRoot/lib/plugins" => 'lib/plugins/',
];
$writeResults = [];
foreach ($writableDirs as $dir => $label) {
    if (is_dir($dir)) {
        $testFile = "$dir/_test_write_" . time() . ".tmp";
        $canWrite = @file_put_contents($testFile, 'test') !== false;
        if ($canWrite) @unlink($testFile);
        $writeResults[] = ['label' => $label, 'writable' => $canWrite, 'exists' => true];
    } else {
        $writeResults[] = ['label' => $label, 'writable' => false, 'exists' => false];
    }
}

// ============================================================
// HTML OUTPUT
// ============================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Diagnostico DokuWiki - <?php echo htmlspecialchars($targetSub); ?></title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #1a1a2e; color: #e0e0e0; padding: 20px; }
        h1 { color: #00d4ff; text-align: center; margin-bottom: 5px; font-size: 24px; }
        .subtitle { text-align: center; color: #888; margin-bottom: 20px; font-size: 14px; }
        .nav-bar { text-align: center; margin-bottom: 15px; }
        .nav-bar a { color: #00d4ff; text-decoration: none; font-size: 13px; padding: 6px 14px; background: #0f3460; border-radius: 4px; }
        .nav-bar a:hover { background: #1a3a6e; }
        .nav-bar select { padding: 6px 10px; font-size: 13px; background: #0d1117; color: #e0e0e0; border: 1px solid #0f3460; border-radius: 4px; }
        .section { background: #16213e; border: 1px solid #0f3460; border-radius: 8px; padding: 15px; margin-bottom: 15px; }
        .section h2 { color: #e94560; font-size: 16px; margin-bottom: 10px; border-bottom: 1px solid #333; padding-bottom: 5px; }
        table { width: 100%; border-collapse: collapse; font-size: 13px; }
        th { background: #0f3460; color: #00d4ff; padding: 6px 8px; text-align: left; }
        td { padding: 5px 8px; border-bottom: 1px solid #1a1a3e; }
        tr:hover { background: #1a1a3e; }
        .status { font-weight: bold; padding: 2px 8px; border-radius: 3px; font-size: 12px; }
        .FALTA { color: #ff4444; }
        .VACIO { color: #ff8800; }
        .OK { color: #44cc44; }
        .SIN_PERMISO { color: #ff4444; }
        .critical-missing { background: #3d0000; }
        .warn { background: #3d2d00; }
        pre { background: #0d1117; border: 1px solid #333; border-radius: 4px; padding: 10px; font-size: 12px; overflow-x: auto; max-height: 400px; overflow-y: auto; color: #c9d1d9; }
        .summary-box { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 15px; }
        .summary-card { flex: 1; min-width: 180px; background: #0f3460; border-radius: 8px; padding: 15px; text-align: center; }
        .summary-card .num { font-size: 36px; font-weight: bold; }
        .summary-card .label { font-size: 12px; color: #aaa; margin-top: 5px; }
        .green { color: #44cc44; }
        .red { color: #ff4444; }
        .orange { color: #ff8800; }
        .pills { display: flex; flex-wrap: wrap; gap: 4px; }
        .pill { background: #0f3460; padding: 3px 8px; border-radius: 12px; font-size: 11px; }
        .diagnosis { background: #2d0a0a; border: 2px solid #e94560; border-radius: 8px; padding: 15px; margin-bottom: 15px; }
        .diagnosis h2 { color: #ff6b6b; border-bottom-color: #e94560; }
        .diagnosis ul { margin-left: 20px; margin-top: 8px; }
        .diagnosis li { margin-bottom: 5px; color: #ffaaaa; }
        .fix { color: #44cc44; font-weight: bold; }
    </style>
</head>
<body>
<h1>&#128269; Diagnostico DokuWiki - SIE/NICC</h1>
<p class="subtitle"><strong><?php echo htmlspecialchars($targetSub); ?></strong> &mdash; <?php echo htmlspecialchars($siteRoot); ?> | <?php echo date('Y-m-d H:i:s'); ?></p>

<!-- BARRA DE NAVEGACION: cambiar subdominio sin volver al selector -->
<div class="nav-bar">
    <a href="?">&#8592; Volver al Selector</a>
    &nbsp;|&nbsp;
    <label for="switchSub">Cambiar a:</label>
    <select id="switchSub" onchange="if(this.value) window.location='?sub='+this.value;">
        <option value="">-- otro subdominio --</option>
        <?php foreach ($subdominios as $s): ?>
        <option value="<?php echo htmlspecialchars($s); ?>"<?php echo ($s === $targetSub) ? ' selected' : ''; ?>><?php echo htmlspecialchars($s); ?></option>
        <?php endforeach; ?>
    </select>
</div>

<?php
// ============================================================
// DIAGNOSTICO AUTOMATICO
// ============================================================
$problems = [];
$critical = 0;

// Verificar archivos criticos faltantes
foreach ($criticalFiles as $f) {
    if ($f['status'] === 'FALTA') {
        $isCritical = (strpos($f['label'], 'CRITICO') !== false || strpos($f['label'], 'CORE') !== false || $f['label'] === 'doku.php (entry point)' || strpos($f['label'], 'vendor/autoload') !== false);
        if ($isCritical) {
            $problems[] = ['level' => 'CRITICO', 'msg' => "Archivo FALTA: {$f['label']}", 'fix' => ''];
            $critical++;
        }
    }
}

// Verificar directorios vacios o faltantes
foreach ($criticalDirs as $d) {
    if ($d['status'] === 'FALTA' || $d['status'] === 'VACIO') {
        $problems[] = ['level' => 'ERROR', 'msg' => "Directorio {$d['status']}: {$d['label']}", 'fix' => ''];
        if (in_array($d['label'], ['inc/ (core DokuWiki)', 'vendor/ (dependencias)', 'conf/ (configuracion)', 'lib/plugins/', 'lib/scripts/'])) {
            $critical++;
        }
    }
}

// Verificar conf/local.php especificamente
$localExists = file_exists("$siteRoot/conf/local.php");
if (!$localExists) {
    $problems[] = [
        'level' => 'CRITICO',
        'msg' => 'conf/local.php NO EXISTE - Este archivo contiene la configuracion del sitio (titulo, template, idioma, etc)',
        'fix' => 'Restaurar desde backup o crear uno minimo con: $conf[\'title\'] = \'Mi Wiki\'; $conf[\'template\'] = \'20cones\';',
    ];
    $critical++;
}

// Verificar conf/acl.auth.php
if (!file_exists("$siteRoot/conf/acl.auth.php")) {
    $problems[] = [
        'level' => 'CRITICO',
        'msg' => 'conf/acl.auth.php NO EXISTE - Sin este archivo no hay control de acceso',
        'fix' => 'Restaurar desde backup o crear uno minimo con: * @ALL 8',
    ];
    $critical++;
}

// Verificar conf/users.auth.php
if (!file_exists("$siteRoot/conf/users.auth.php")) {
    $problems[] = [
        'level' => 'CRITICO',
        'msg' => 'conf/users.auth.php NO EXISTE - Sin este archivo no hay usuarios registrados',
        'fix' => 'Restaurar desde backup',
    ];
    $critical++;
}

// Verificar template
if (isset($templateInfo['template_activo']) && $templateInfo['template_activo'] !== '(desconocido)') {
    $tplDir = $templateInfo['template_dir'];
    if ($tplDir['status'] === 'FALTA') {
        $problems[] = [
            'level' => 'CRITICO',
            'msg' => "Template activo '{$templateInfo['template_activo']}' NO EXISTE en lib/tpl/",
            'fix' => "Instalar el template {$templateInfo['template_activo']} o cambiar conf/local.php",
        ];
        $critical++;
    } elseif (isset($templateInfo['main_php']) && $templateInfo['main_php']['status'] === 'FALTA') {
        $problems[] = [
            'level' => 'CRITICO',
            'msg' => "Template '{$templateInfo['template_activo']}' existe pero FALTA main.php",
            'fix' => "Reinstalar el template o restaurar main.php",
        ];
        $critical++;
    }
}

// Verificar inc/ vacio
$incDir = checkDir("$siteRoot/inc");
if ($incDir['count'] < 10) {
    $problems[] = [
        'level' => 'CRITICO',
        'msg' => "inc/ tiene solo {$incDir['count']} items (deberia tener ~35+)",
        'fix' => 'El directorio inc/ fue vaciado por la limpieza y no fue restaurado por el parche',
    ];
    $critical++;
}

// Verificar vendor
$vendorDir = checkDir("$siteRoot/vendor");
if ($vendorDir['count'] < 5) {
    $problems[] = [
        'level' => 'CRITICO',
        'msg' => "vendor/ tiene solo {$vendorDir['count']} items (deberia tener ~10)",
        'fix' => 'El directorio vendor/ fue vaciado por la limpieza y no fue restaurado por el parche',
    ];
    $critical++;
}

// Verificar lib/plugins
$plugDir = checkDir("$siteRoot/lib/plugins");
if ($plugDir['count'] < 3) {
    $problems[] = [
        'level' => 'ERROR',
        'msg' => "lib/plugins/ tiene solo {$plugDir['count']} items - plugins fueron borrados",
        'fix' => 'Restaurar plugins desde PROYECTO NICC',
    ];
}

// Verificar sintaxis
if (!empty($syntaxErrors)) {
    foreach ($syntaxErrors as $se) {
        $problems[] = [
            'level' => 'CRITICO',
            'msg' => "Error de sintaxis en {$se['file']}: {$se['error']}",
            'fix' => 'Corregir el error de sintaxis',
        ];
        $critical++;
    }
}

$totalProblems = count($problems);
$missingFiles = 0;
foreach ($criticalFiles as $f) { if ($f['status'] === 'FALTA') $missingFiles++; }
$emptyDirs = 0;
foreach ($criticalDirs as $d) { if ($d['status'] === 'VACIO' || $d['status'] === 'FALTA') $emptyDirs++; }
?>

<!-- RESUMEN -->
<div class="summary-box">
    <div class="summary-card">
        <div class="num <?php echo $critical > 0 ? 'red' : 'green'; ?>"><?php echo $critical; ?></div>
        <div class="label">PROBLEMAS CRITICOS</div>
    </div>
    <div class="summary-card">
        <div class="num <?php echo $missingFiles > 0 ? 'orange' : 'green'; ?>"><?php echo $missingFiles; ?></div>
        <div class="label">ARCHIVOS FALTANTES</div>
    </div>
    <div class="summary-card">
        <div class="num <?php echo $emptyDirs > 0 ? 'orange' : 'green'; ?>"><?php echo $emptyDirs; ?></div>
        <div class="label">DIRS VACIOS/FALTANTES</div>
    </div>
    <div class="summary-card">
        <div class="num"><?php echo count($pluginsList); ?></div>
        <div class="label">PLUGINS INSTALADOS</div>
    </div>
</div>

<?php if (!empty($problems)): ?>
<!-- DIAGNOSTICO -->
<div class="diagnosis">
    <h2>&#9888; DIAGNOSTICO: <?php echo $totalProblems; ?> problema(s) encontrado(s)</h2>
    <table>
        <tr><th>Nivel</th><th>Problema</th><th>Solucion sugerida</th></tr>
        <?php foreach ($problems as $p): ?>
        <tr class="<?php echo $p['level'] === 'CRITICO' ? 'critical-missing' : 'warn'; ?>">
            <td><span class="status <?php echo $p['level'] === 'CRITICO' ? 'FALTA' : 'VACIO'; ?>"><?php echo $p['level']; ?></span></td>
            <td><?php echo htmlspecialchars($p['msg']); ?></td>
            <td class="fix"><?php echo htmlspecialchars($p['fix']); ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>
<?php endif; ?>

<!-- PHP INFO -->
<div class="section">
    <h2>&#9881; Informacion PHP</h2>
    <table>
        <?php foreach ($phpInfo as $key => $val): ?>
        <tr><td style="width:200px;color:#aaa;"><?php echo $key; ?></td><td><?php echo htmlspecialchars($val); ?></td></tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- ARCHIVOS CRITICOS -->
<div class="section">
    <h2>&#128196; Archivos Criticos (<?php echo $missingFiles; ?> faltantes)</h2>
    <table>
        <tr><th>Estado</th><th>Archivo</th><th>Tamano</th></tr>
        <?php foreach ($criticalFiles as $f): ?>
        <tr class="<?php echo $f['status'] === 'FALTA' ? 'critical-missing' : ''; ?>">
            <td><span class="status <?php echo str_replace(' ', '_', $f['status']); ?>"><?php echo statusIcon($f['status']); ?> <?php echo $f['status']; ?></span></td>
            <td><?php echo htmlspecialchars($f['label']); ?></td>
            <td><?php echo $f['exists'] ? number_format($f['size']) . ' bytes' : '-'; ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- DIRECTORIOS CRITICOS -->
<div class="section">
    <h2>&#128193; Directorios Criticos</h2>
    <table>
        <tr><th>Estado</th><th>Directorio</th></tr>
        <?php foreach ($criticalDirs as $d): ?>
        <tr class="<?php echo ($d['status'] === 'FALTA' || $d['status'] === 'VACIO') ? 'critical-missing' : ''; ?>">
            <td><span class="status <?php echo str_replace([' ', '(', ')'], ['_', '', ''], $d['status']); ?>"><?php echo statusIcon($d['status']); ?> <?php echo $d['status']; ?></span></td>
            <td><?php echo htmlspecialchars($d['label']); ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- TEMPLATE -->
<div class="section">
    <h2>&#127912; Template Activo</h2>
    <?php if (isset($templateInfo['error'])): ?>
        <p class="FALTA"><?php echo $templateInfo['error']; ?></p>
    <?php else: ?>
        <table>
            <tr><td style="width:200px;color:#aaa;">Template configurado</td><td><strong><?php echo htmlspecialchars($templateInfo['template_activo']); ?></strong></td></tr>
            <tr>
                <td style="color:#aaa;">Directorio</td>
                <td><span class="status <?php echo str_replace([' ', '(', ')'], ['_', '', ''], $templateInfo['template_dir']['status']); ?>"><?php echo statusIcon($templateInfo['template_dir']['status']); ?> <?php echo $templateInfo['template_dir']['status']; ?></span></td>
            </tr>
            <?php if (isset($templateInfo['main_php'])): ?>
            <tr>
                <td style="color:#aaa;">main.php</td>
                <td><span class="status <?php echo str_replace(' ', '_', $templateInfo['main_php']['status']); ?>"><?php echo statusIcon($templateInfo['main_php']['status']); ?> <?php echo $templateInfo['main_php']['status']; ?></span></td>
            </tr>
            <?php endif; ?>
            <?php if (isset($templateInfo['style_ini'])): ?>
            <tr>
                <td style="color:#aaa;">style.ini</td>
                <td><span class="status <?php echo str_replace(' ', '_', $templateInfo['style_ini']['status']); ?>"><?php echo statusIcon($templateInfo['style_ini']['status']); ?> <?php echo $templateInfo['style_ini']['status']; ?></span></td>
            </tr>
            <?php endif; ?>
        </table>
        <?php
        // Listar solo archivos de PRIMER NIVEL del template (no recursivo para evitar memoria)
        $tplPath = "$siteRoot/lib/tpl/{$templateInfo['template_activo']}";
        if (is_dir($tplPath)) {
            $tplItems = @scandir($tplPath);
            if ($tplItems) {
                $tplItems = array_diff($tplItems, ['.', '..']);
                echo '<h3 style="margin-top:10px;color:#00d4ff;font-size:13px;">Contenido raiz del template (' . count($tplItems) . ' items):</h3>';
                echo '<div class="pills" style="margin-top:5px;">';
                foreach ($tplItems as $tf) {
                    $isDir = is_dir("$tplPath/$tf");
                    echo '<span class="pill">' . htmlspecialchars($tf) . ($isDir ? '/' : '') . '</span>';
                }
                echo '</div>';
            }
        }
        ?>
    <?php endif; ?>
</div>

<!-- PLUGINS -->
<div class="section">
    <h2>&#128268; Plugins Instalados (<?php echo count($pluginsList); ?>)</h2>
    <?php if (empty($pluginsList)): ?>
        <p class="FALTA">&#10060; No se encontraron plugins en lib/plugins/</p>
    <?php else: ?>
        <div class="pills">
            <?php foreach ($pluginsList as $pl): ?>
            <span class="pill"><?php echo htmlspecialchars($pl); ?></span>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- CONTENIDO conf/ -->
<div class="section">
    <h2>&#128194; Contenido de conf/ (<?php echo count($confFiles); ?> items)</h2>
    <table>
        <tr><th>Nombre</th><th>Tipo</th><th>Tamano</th></tr>
        <?php foreach ($confFiles as $cf): ?>
        <tr>
            <td><?php echo htmlspecialchars($cf['name']); ?></td>
            <td><?php echo $cf['type']; ?></td>
            <td><?php echo $cf['size'] !== '-' ? number_format($cf['size']) . ' bytes' : '-'; ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- PERMISOS ESCRITURA -->
<div class="section">
    <h2>&#128274; Permisos de Escritura</h2>
    <table>
        <tr><th>Directorio</th><th>Existe</th><th>Escritura</th></tr>
        <?php foreach ($writeResults as $wr): ?>
        <tr>
            <td><?php echo htmlspecialchars($wr['label']); ?></td>
            <td><?php echo $wr['exists'] ? '<span class="OK">SI</span>' : '<span class="FALTA">NO</span>'; ?></td>
            <td><?php echo $wr['writable'] ? '<span class="OK">&#9989; Escribible</span>' : '<span class="FALTA">&#10060; No escribible</span>'; ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- ARCHIVOS EN RAIZ -->
<div class="section">
    <h2>&#128193; Archivos en Raiz del Subdominio (<?php echo count($rootFiles); ?> items)</h2>
    <table>
        <tr><th>Nombre</th><th>Tipo</th><th>Tamano</th><th>Permisos</th></tr>
        <?php foreach ($rootFiles as $rf): ?>
        <tr>
            <td><?php echo htmlspecialchars($rf['name']); ?></td>
            <td><?php echo $rf['type']; ?></td>
            <td><?php echo $rf['size'] !== '-' ? number_format($rf['size']) . ' bytes' : '-'; ?></td>
            <td><?php echo $rf['perms']; ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- ERROR LOG -->
<?php if (!empty($errorLogContent)): ?>
<div class="section">
    <h2>&#128203; Error Log (ultimas 30 lineas)</h2>
    <pre><?php echo htmlspecialchars($errorLogContent); ?></pre>
</div>
<?php endif; ?>

<?php if (!empty($syntaxErrors)): ?>
<div class="section">
    <h2>&#9888; Errores de Sintaxis PHP</h2>
    <table>
        <tr><th>Archivo</th><th>Error</th></tr>
        <?php foreach ($syntaxErrors as $se): ?>
        <tr class="critical-missing">
            <td><?php echo htmlspecialchars($se['file']); ?></td>
            <td><pre style="margin:0"><?php echo htmlspecialchars($se['error']); ?></pre></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>
<?php endif; ?>

<?php if ($outputBuffer): ?>
<div class="section">
    <h2>PHP Output Buffer</h2>
    <pre><?php echo htmlspecialchars($outputBuffer); ?></pre>
</div>
<?php endif; ?>

<p style="text-align:center;color:#666;margin-top:20px;font-size:11px;">
    Diagnostico remoto desde diagnosticos/ central &mdash; No requiere copia a cada subdominio
</p>
</body>
</html>
