<?php
/**
 * Fix Home Button v3.1 - aplicar.php
 * ====================================
 * Corrige el boton home (casita) en topbar.html de templates 20cones/21cones.
 * Enfoque DIRECTO: str_replace en archivo HTML puro.
 * Sin OPcache (los .html no se cachean en OPcache).
 *
 * MODOS:
 *   ?modo=escanear           -> Lista subdominios con estado real
 *   ?modo=probar&sub=nombre  -> Aplica fix en UN subdominio
 *   ?modo=todos              -> Aplica fix en TODOS
 *   ?modo=forzar             -> Fuerza reescritura en TODOS (incluso si ya OK)
 *   ?modo=revertir&sub=nombre -> Restaura backup
 *   ?modo=diagnostico&sub=nombre -> Muestra contenido RAW del topbar.html
 */

require_once __DIR__ . '/config.php';

set_time_limit(300);
ini_set('memory_limit', '256M');
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

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

function isDokuWiki($path) {
    return file_exists($path . '/doku.php')
        && (file_exists($path . '/conf/local.php') || file_exists($path . '/conf/dokuwiki.php'))
        && is_dir($path . '/data');
}

function getSiteTitle($path) {
    $localConf = $path . '/conf/local.php';
    if (!file_exists($localConf)) return '(sin titulo)';
    $content = @file_get_contents($localConf);
    if ($content === false) return '(no legible)';
    if (preg_match('/\$conf\s*\[\s*[\'"]title[\'"]\s*\]\s*=\s*[\'"](.+?)[\'"]\s*;/', $content, $m)) {
        return $m[1];
    }
    return '(sin titulo)';
}

function scanDirectory($basePath) {
    $sites = [];
    if (!is_dir($basePath)) return $sites;
    $items = @scandir($basePath);
    if ($items === false) return $sites;
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        if ($item[0] === '_' || $item[0] === '.') continue;
        $fullPath = $basePath . '/' . $item;
        if (is_link($fullPath)) continue;
        if (!is_dir($fullPath)) continue;
        if (isDokuWiki($fullPath)) {
            $sites[] = [
                'name'  => $item,
                'path'  => $fullPath,
                'title' => getSiteTitle($fullPath),
            ];
        }
    }
    usort($sites, function($a, $b) { return strcasecmp($a['name'], $b['name']); });
    return $sites;
}

function validateSubName($name) {
    return preg_match('/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/', $name) === 1;
}

/**
 * Analiza un topbar.html - enfoque SIMPLE y directo.
 * Retorna array con status, detail, y la linea del tab-home como prueba.
 */
function analyzeTopbar($filePath) {
    if (!file_exists($filePath)) {
        return ['status' => 'not_found', 'detail' => 'Archivo no existe', 'line' => ''];
    }

    $content = @file_get_contents($filePath);
    if ($content === false) {
        return ['status' => 'error', 'detail' => 'No se pudo leer', 'line' => ''];
    }

    // Buscar la linea que contiene tab-home
    $lines = explode("\n", $content);
    $tabHomeLine = '';
    foreach ($lines as $line) {
        if (stripos($line, 'tab-home') !== false) {
            $tabHomeLine = trim($line);
            break;
        }
    }

    if (empty($tabHomeLine)) {
        // Buscar icon-home como alternativa
        foreach ($lines as $line) {
            if (stripos($line, 'icon-home') !== false && stripos($line, '<a') !== false) {
                $tabHomeLine = trim($line);
                break;
            }
        }
    }

    if (empty($tabHomeLine)) {
        return ['status' => 'no_home', 'detail' => 'No tiene boton tab-home', 'line' => ''];
    }

    // Verificar si ya tiene ?id=inicio (el fix correcto)
    if (stripos($tabHomeLine, '?id=inicio') !== false) {
        return ['status' => 'ok', 'detail' => 'Correcto: ?id=inicio', 'line' => $tabHomeLine];
    }

    // Verificar si tiene href="/" (necesita fix)
    if (preg_match('/href\s*=\s*["\']\/["\']/', $tabHomeLine)) {
        return ['status' => 'broken', 'detail' => 'href="/" detectado', 'line' => $tabHomeLine];
    }

    // Verificar si tiene /doku.php?id=inicio (version anterior, cambiar a ?id=inicio)
    if (stripos($tabHomeLine, '/doku.php?id=inicio') !== false) {
        return ['status' => 'broken', 'detail' => 'Tiene /doku.php?id=inicio - cambiar a ?id=inicio', 'line' => $tabHomeLine];
    }

    // Verificar si tiene wl() (version anterior del fix)
    if (stripos($tabHomeLine, 'wl()') !== false) {
        return ['status' => 'broken', 'detail' => 'Tiene wl() - cambiar a ?id=inicio', 'line' => $tabHomeLine];
    }

    // Tiene tab-home pero href desconocido
    return ['status' => 'unknown', 'detail' => 'href no reconocido', 'line' => $tabHomeLine];
}

/**
 * Aplica el fix a un topbar.html - ENFOQUE DIRECTO con str_replace.
 * Es HTML puro, no necesita purga de OPcache.
 *
 * @param string $filePath  Ruta al topbar.html
 * @param bool   $force     Si true, reescribe incluso si ya esta correcto
 * @return array ['status' => ..., 'detail' => ..., 'line_before' => ..., 'line_after' => ...]
 */
function fixTopbar($filePath, $force = false) {
    if (!file_exists($filePath)) {
        return ['status' => 'not_found', 'detail' => 'Archivo no existe'];
    }

    $content = @file_get_contents($filePath);
    if ($content === false) {
        return ['status' => 'error', 'detail' => 'No se pudo leer'];
    }

    // Encontrar la linea tab-home ANTES del fix
    $lineBefore = '';
    $lines = explode("\n", $content);
    foreach ($lines as $line) {
        if (stripos($line, 'tab-home') !== false) {
            $lineBefore = trim($line);
            break;
        }
    }

    // Verificar si ya tiene ?id=inicio (sin /doku.php)
    $alreadyFixed = (stripos($lineBefore, 'href="?id=inicio"') !== false);

    if ($alreadyFixed && !$force) {
        return [
            'status' => 'already_ok',
            'detail' => 'Ya tiene ?id=inicio',
            'line_before' => $lineBefore,
            'line_after' => $lineBefore,
        ];
    }

    // Crear backup
    $backupPath = $filePath . '.bak_home';
    if (!file_exists($backupPath)) {
        @copy($filePath, $backupPath);
    }

    $newContent = $content;
    $changed = false;

    // FIX 1: href="/" -> href="?id=inicio"
    if (strpos($newContent, 'href="/"') !== false) {
        $newContent = str_replace('href="/"', 'href="?id=inicio"', $newContent);
        $changed = true;
    }
    // FIX 2: href='/' -> href="?id=inicio"
    if (strpos($newContent, "href='/'") !== false) {
        $newContent = str_replace("href='/'", 'href="?id=inicio"', $newContent);
        $changed = true;
    }
    // FIX 3: /doku.php?id=inicio -> ?id=inicio (corregir version anterior)
    if (strpos($newContent, 'href="/doku.php?id=inicio"') !== false) {
        $newContent = str_replace('href="/doku.php?id=inicio"', 'href="?id=inicio"', $newContent);
        $changed = true;
    }
    // FIX 4: wl() -> ?id=inicio (corregir version PHP anterior)
    if (strpos($newContent, 'href="<?php echo wl(); ?>"') !== false) {
        $newContent = str_replace('href="<?php echo wl(); ?>"', 'href="?id=inicio"', $newContent);
        $changed = true;
    }

    if ($force && !$changed) {
        $changed = true;
    }

    if ($changed) {
        if (@file_put_contents($filePath, $newContent) === false) {
            return [
                'status' => 'error',
                'detail' => 'No se pudo escribir (permisos?)',
                'line_before' => $lineBefore,
                'line_after' => '',
            ];
        }
    }

    // Verificar resultado
    clearstatcache(true, $filePath);
    $verifyContent = @file_get_contents($filePath);
    $lineAfter = '';
    if ($verifyContent !== false) {
        foreach (explode("\n", $verifyContent) as $line) {
            if (stripos($line, 'tab-home') !== false) { $lineAfter = trim($line); break; }
        }
    }

    return [
        'status' => $changed ? 'fixed' : 'already_ok',
        'detail' => $changed ? 'Corregido a ?id=inicio' : 'Ya correcto',
        'line_before' => $lineBefore,
        'line_after' => $lineAfter,
    ];
}

/**
 * Revierte un topbar.html desde backup
 */
function revertTopbar($filePath) {
    $backupPath = $filePath . '.bak_home';
    if (!file_exists($backupPath)) {
        return ['status' => 'no_backup', 'detail' => 'No hay backup'];
    }
    if (@copy($backupPath, $filePath) === false) {
        return ['status' => 'error', 'detail' => 'No se pudo restaurar'];
    }
    @unlink($backupPath);
    return ['status' => 'reverted', 'detail' => 'Restaurado desde backup'];
}

/**
 * Procesa un subdominio
 */
function processSite($sitePath, $action = 'analyze', $force = false) {
    global $FIX_TEMPLATES;
    $results = [];
    foreach ($FIX_TEMPLATES as $tplFile) {
        $fullPath = $sitePath . '/' . $tplFile;
        $tplName = basename(dirname($tplFile));

        switch ($action) {
            case 'fix':
                $r = fixTopbar($fullPath, $force);
                $results[] = array_merge(['template' => $tplName, 'file' => $tplFile], $r);
                break;
            case 'revert':
                $r = revertTopbar($fullPath);
                $results[] = array_merge(['template' => $tplName, 'file' => $tplFile], $r);
                break;
            default:
                $r = analyzeTopbar($fullPath);
                $results[] = array_merge(['template' => $tplName, 'file' => $tplFile], $r);
                break;
        }
    }
    return $results;
}

function statusBadge($status) {
    $map = [
        'ok'              => ['badge-ok',    'OK'],
        'fixed'           => ['badge-fixed', 'CORREGIDO'],
        'already_ok'      => ['badge-ok',    'YA OK'],
        'force_rewritten' => ['badge-fixed', 'FORZADO'],
        'broken'          => ['badge-err',   'ROTO'],
        'not_found'       => ['badge-skip',  'NO EXISTE'],
        'no_home'         => ['badge-skip',  'SIN HOME'],
        'unknown'         => ['badge-warn',  'DESCONOCIDO'],
        'reverted'        => ['badge-rev',   'REVERTIDO'],
        'no_backup'       => ['badge-skip',  'SIN BACKUP'],
    ];
    if (strpos($status, 'error') === 0) {
        return '<span class="badge badge-err">' . htmlspecialchars(strtoupper($status)) . '</span>';
    }
    if (isset($map[$status])) {
        return '<span class="badge ' . $map[$status][0] . '">' . $map[$status][1] . '</span>';
    }
    return '<span class="badge badge-skip">' . htmlspecialchars(strtoupper($status)) . '</span>';
}

// ============================================================
// DETERMINAR MODO
// ============================================================

$modo = isset($_GET['modo']) ? $_GET['modo'] : 'escanear';
$subParam = isset($_GET['sub']) ? trim($_GET['sub']) : '';
$errorMsg = '';

if ($subParam !== '' && !validateSubName($subParam)) {
    $modo = 'error';
    $errorMsg = 'Nombre de subdominio invalido: ' . htmlspecialchars($subParam);
}

if ($modo !== 'error' && !is_dir(SEARCH_PATH)) {
    $modo = 'error';
    $errorMsg = 'Ruta base no existe: ' . htmlspecialchars(SEARCH_PATH);
}

// ============================================================
// EJECUTAR
// ============================================================

$allSites = [];
$stats = ['total' => 0, 'ok' => 0, 'broken' => 0, 'fixed' => 0, 'not_found' => 0, 'error' => 0, 'reverted' => 0];
$modoLabel = '';
$currentSite = null;
$fixResults = [];
$beforeAnalysis = [];
$afterAnalysis = [];
$revertResults = [];
$diagnosticData = [];

switch ($modo) {
    case 'escanear':
        $modoLabel = 'Escanear Sistemas';
        $allSites = scanDirectory(SEARCH_PATH);
        $stats['total'] = count($allSites);
        foreach ($allSites as &$site) {
            $site['analysis'] = processSite($site['path'], 'analyze');
            $siteOk = true;
            $siteBroken = false;
            foreach ($site['analysis'] as $a) {
                if ($a['status'] === 'broken') { $siteBroken = true; $siteOk = false; }
                elseif ($a['status'] !== 'ok' && $a['status'] !== 'not_found' && $a['status'] !== 'no_home') { $siteOk = false; }
                if ($a['status'] === 'ok') $stats['ok']++;
                elseif ($a['status'] === 'broken') $stats['broken']++;
                elseif ($a['status'] === 'not_found' || $a['status'] === 'no_home') $stats['not_found']++;
                else $stats['error']++;
            }
            $site['overall'] = $siteBroken ? 'broken' : ($siteOk ? 'ok' : 'unknown');
        }
        unset($site);
        break;

    case 'probar':
        $modoLabel = 'Probar en: ' . htmlspecialchars($subParam);
        $sitePath = SEARCH_PATH . '/' . $subParam;
        if (!is_dir($sitePath)) { $modo = 'error'; $errorMsg = 'Subdominio no encontrado: ' . htmlspecialchars($subParam); break; }
        if (!isDokuWiki($sitePath)) { $modo = 'error'; $errorMsg = 'No es DokuWiki valido: ' . htmlspecialchars($subParam); break; }
        $currentSite = ['name' => $subParam, 'path' => $sitePath, 'title' => getSiteTitle($sitePath)];
        $beforeAnalysis = processSite($sitePath, 'analyze');
        $fixResults = processSite($sitePath, 'fix', false);
        $afterAnalysis = processSite($sitePath, 'analyze');
        foreach ($fixResults as $r) {
            if ($r['status'] === 'fixed') $stats['fixed']++;
            elseif ($r['status'] === 'not_found') $stats['not_found']++;
            elseif (strpos($r['status'], 'error') === 0) $stats['error']++;
        }
        break;

    case 'todos':
    case 'forzar':
        $force = ($modo === 'forzar');
        $modoLabel = $force ? 'FORZAR Reescritura en TODOS' : 'Aplicar a TODOS';
        $allSites = scanDirectory(SEARCH_PATH);
        $stats['total'] = count($allSites);
        foreach ($allSites as &$site) {
            $site['fix_results'] = processSite($site['path'], 'fix', $force);
            foreach ($site['fix_results'] as $r) {
                if ($r['status'] === 'fixed') $stats['fixed']++;
                elseif ($r['status'] === 'already_ok') $stats['ok']++;
                elseif ($r['status'] === 'not_found' || $r['status'] === 'no_home') $stats['not_found']++;
                elseif (strpos($r['status'], 'error') === 0) $stats['error']++;
            }
        }
        unset($site);
        break;

    case 'revertir':
        $modoLabel = 'Revertir: ' . htmlspecialchars($subParam);
        $sitePath = SEARCH_PATH . '/' . $subParam;
        if (!is_dir($sitePath)) { $modo = 'error'; $errorMsg = 'Subdominio no encontrado'; break; }
        $currentSite = ['name' => $subParam, 'path' => $sitePath, 'title' => getSiteTitle($sitePath)];
        $revertResults = processSite($sitePath, 'revert');
        foreach ($revertResults as $r) {
            if ($r['status'] === 'reverted') $stats['reverted']++;
            elseif ($r['status'] === 'no_backup') $stats['not_found']++;
            else $stats['error']++;
        }
        break;

    case 'diagnostico':
        $modoLabel = 'Diagnostico: ' . htmlspecialchars($subParam);
        $sitePath = SEARCH_PATH . '/' . $subParam;
        if (!is_dir($sitePath)) { $modo = 'error'; $errorMsg = 'Subdominio no encontrado'; break; }
        $currentSite = ['name' => $subParam, 'path' => $sitePath, 'title' => getSiteTitle($sitePath)];
        foreach ($FIX_TEMPLATES as $tplFile) {
            $fp = $sitePath . '/' . $tplFile;
            $d = ['file' => $tplFile, 'exists' => file_exists($fp), 'content' => '', 'size' => 0, 'mtime' => ''];
            if ($d['exists']) {
                $d['content'] = @file_get_contents($fp);
                $d['size'] = filesize($fp);
                $d['mtime'] = date('Y-m-d H:i:s', filemtime($fp));
            }
            $diagnosticData[] = $d;
        }
        break;

    case 'error':
        break;

    default:
        header('Location: ' . basename(__FILE__) . '?modo=escanear');
        exit;
}

$selfUrl = basename(__FILE__);
?><!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fix Home Button v3.1</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #1a1a2e; color: #e0e0e0; padding: 20px; }
        .container { max-width: 1100px; margin: 0 auto; }
        h1 { color: #fdcb6e; margin-bottom: 5px; font-size: 1.5em; }
        h2 { color: #ffd93d; margin: 15px 0 10px; font-size: 1.1em; }
        .subtitle { color: #888; font-size: 0.85em; margin-bottom: 15px; }
        a { color: #74b9ff; text-decoration: none; }
        a:hover { text-decoration: underline; }

        .nav { display: flex; gap: 8px; margin: 15px 0; flex-wrap: wrap; align-items: center; }
        .nav-btn { display: inline-block; padding: 8px 16px; border-radius: 6px; font-size: 0.85em; font-weight: 600; cursor: pointer; border: none; transition: all 0.2s; text-decoration: none; }
        .nav-btn:hover { text-decoration: none; opacity: 0.9; transform: translateY(-1px); }
        .btn-scan { background: #0984e3; color: #fff; }
        .btn-fix-all { background: #00b894; color: #000; }
        .btn-fix-one { background: #6c5ce7; color: #fff; }
        .btn-revert { background: #d63031; color: #fff; }
        .btn-force { background: #e17055; color: #fff; }
        .btn-diag { background: #fdcb6e; color: #000; }

        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: 10px; margin: 15px 0; }
        .stat-box { background: #2a2a4a; padding: 12px; border-radius: 8px; text-align: center; }
        .stat-value { font-size: 1.5em; font-weight: bold; }
        .stat-label { font-size: 0.75em; color: #888; }
        .val-green { color: #00b894; } .val-blue { color: #74b9ff; } .val-yellow { color: #ffd93d; }
        .val-gray { color: #888; }     .val-red { color: #ff6b6b; }  .val-purple { color: #a29bfe; }

        table { width: 100%; border-collapse: collapse; font-size: 0.82em; }
        th { background: #2a2a4a; padding: 8px; text-align: left; color: #fdcb6e; position: sticky; top: 0; z-index: 2; }
        td { padding: 6px 8px; border-bottom: 1px solid #333; }
        tr:hover { background: #2a2a4a; }
        .table-wrap { max-height: 600px; overflow-y: auto; border: 1px solid #333; border-radius: 8px; margin: 10px 0; }

        .badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 0.75em; font-weight: bold; white-space: nowrap; }
        .badge-fixed { background: #00b894; color: #000; }
        .badge-ok { background: #0984e3; color: #fff; }
        .badge-skip { background: #636e72; color: #fff; }
        .badge-warn { background: #f39c12; color: #000; }
        .badge-err { background: #d63031; color: #fff; }
        .badge-rev { background: #6c5ce7; color: #fff; }

        .info-box { background: #1a2a1a; border: 1px solid #00b894; padding: 12px; border-radius: 8px; margin: 10px 0; font-size: 0.9em; }
        .error-box { background: #2a1a1a; border: 1px solid #d63031; padding: 12px; border-radius: 8px; margin: 10px 0; }
        .complete { background: #0d3320; border: 2px solid #00b894; padding: 20px; border-radius: 10px; text-align: center; margin: 20px 0; }
        .complete h2 { color: #00b894; font-size: 1.3em; margin: 0; }

        .search-box { margin: 10px 0; }
        .search-box input { width: 100%; max-width: 400px; padding: 8px 12px; border: 1px solid #444; border-radius: 6px; background: #2a2a4a; color: #fff; font-size: 0.9em; }
        .search-box input:focus { outline: none; border-color: #0984e3; }

        .detail-text { color: #888; font-size: 0.78em; }
        .site-title { color: #a29bfe; font-size: 0.78em; display: block; }
        .raw-line { background: #0a0a1a; border: 1px solid #444; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 0.78em; color: #74b9ff; word-break: break-all; margin-top: 3px; }
        code { background: #2a2a4a; padding: 2px 6px; border-radius: 3px; font-size: 0.9em; color: #74b9ff; }
        .footer-info { margin-top: 15px; color: #555; font-size: 0.8em; }
        pre.raw-content { background: #0a0a1a; border: 1px solid #444; padding: 12px; border-radius: 6px; font-size: 0.8em; color: #a29bfe; overflow-x: auto; white-space: pre-wrap; word-break: break-all; max-height: 400px; overflow-y: auto; }
    </style>
</head>
<body>
<div class="container">
    <h1>&#127968; Fix Home Button <small style="color:#888;font-size:0.6em;">v3.1</small></h1>
    <p class="subtitle">
        Correccion del boton home en topbar.html &mdash;
        <code>href="/"</code> &rarr; <code>href="?id=inicio"</code>
        &mdash; <strong>HTML puro, sin OPcache</strong>
    </p>

    <!-- NAVEGACION -->
    <div class="nav">
        <a href="<?php echo $selfUrl; ?>?modo=escanear" class="nav-btn btn-scan">&#128269; Escanear</a>
        <a href="<?php echo $selfUrl; ?>?modo=todos" class="nav-btn btn-fix-all" onclick="return confirm('Aplicar fix a TODOS los subdominios?')">&#9989; Aplicar a TODOS</a>
        <a href="<?php echo $selfUrl; ?>?modo=forzar" class="nav-btn btn-force" onclick="return confirm('FORZAR reescritura en TODOS?')">&#128293; Forzar Reescritura</a>
        <span style="color:#555;">|</span>
        <span style="color:#888;font-size:0.82em;">Modo: <strong style="color:#fdcb6e;"><?php echo htmlspecialchars($modoLabel ?: $modo); ?></strong></span>
    </div>

<?php if ($modo === 'error'): ?>
    <div class="error-box"><strong>Error:</strong> <?php echo $errorMsg; ?></div>
    <p><a href="<?php echo $selfUrl; ?>?modo=escanear">&larr; Volver al escaner</a></p>

<?php elseif ($modo === 'escanear'): ?>
    <!-- SELECTOR DE SUBDOMINIO -->
    <div style="background:#2a2a4a;border:2px solid #6c5ce7;border-radius:10px;padding:16px;margin:10px 0;">
        <h2 style="margin:0 0 10px;color:#a29bfe;font-size:1em;">&#127919; Seleccionar Subdominio</h2>
        <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
            <select id="subSelector" style="flex:1;min-width:250px;padding:10px 14px;font-size:0.95em;background:#1a1a2e;color:#fff;border:1px solid #6c5ce7;border-radius:6px;">
                <option value="">-- Seleccione un subdominio --</option>
                <?php foreach ($allSites as $site): ?>
                <option value="<?php echo htmlspecialchars($site['name']); ?>"><?php echo htmlspecialchars($site['name']); ?> &mdash; <?php echo htmlspecialchars($site['title']); ?></option>
                <?php endforeach; ?>
            </select>
            <button onclick="goToSub('probar')" class="nav-btn btn-fix-one" style="padding:10px 20px;">&#128295; Probar Fix</button>
            <button onclick="goToSub('revertir')" class="nav-btn btn-revert" style="padding:10px 20px;">&#8634; Revertir</button>
            <button onclick="goToSub('diagnostico')" class="nav-btn btn-diag" style="padding:10px 20px;">&#128270; Diagnostico</button>
        </div>
    </div>
    <script>
    function goToSub(modo) {
        var sel = document.getElementById('subSelector');
        if (!sel.value) { alert('Seleccione un subdominio primero'); return; }
        if (modo === 'revertir' && !confirm('Revertir fix en ' + sel.value + '?')) return;
        window.location = '<?php echo $selfUrl; ?>?modo=' + modo + '&sub=' + encodeURIComponent(sel.value);
    }
    </script>

    <div class="stats">
        <div class="stat-box"><div class="stat-value val-blue"><?php echo $stats['total']; ?></div><div class="stat-label">Sistemas</div></div>
        <div class="stat-box"><div class="stat-value val-green"><?php echo $stats['ok']; ?></div><div class="stat-label">OK</div></div>
        <div class="stat-box"><div class="stat-value val-red"><?php echo $stats['broken']; ?></div><div class="stat-label">Rotos</div></div>
        <div class="stat-box"><div class="stat-value val-gray"><?php echo $stats['not_found']; ?></div><div class="stat-label">Sin topbar</div></div>
        <div class="stat-box"><div class="stat-value val-yellow"><?php echo $stats['error']; ?></div><div class="stat-label">Otros</div></div>
    </div>

    <div class="search-box">
        <input type="text" id="searchInput" placeholder="Buscar subdominio..." onkeyup="filterTable()">
    </div>

    <div class="table-wrap">
    <table id="sitesTable">
        <thead><tr><th>#</th><th>Subdominio</th><th>20cones</th><th>21cones</th><th>Acciones</th></tr></thead>
        <tbody>
        <?php foreach ($allSites as $idx => $site): ?>
            <tr class="site-row" data-name="<?php echo htmlspecialchars(strtolower($site['name'])); ?>">
                <td><?php echo $idx + 1; ?></td>
                <td>
                    <strong style="color:#fdcb6e;"><?php echo htmlspecialchars($site['name']); ?></strong>
                    <span class="site-title"><?php echo htmlspecialchars($site['title']); ?></span>
                </td>
                <?php foreach ($site['analysis'] as $a): ?>
                <td>
                    <?php echo statusBadge($a['status']); ?>
                    <?php if (!empty($a['line'])): ?>
                    <div class="raw-line"><?php echo htmlspecialchars(substr($a['line'], 0, 100)); ?></div>
                    <?php elseif (!empty($a['detail'])): ?>
                    <div class="detail-text"><?php echo htmlspecialchars($a['detail']); ?></div>
                    <?php endif; ?>
                </td>
                <?php endforeach; ?>
                <td style="white-space:nowrap;">
                    <a href="<?php echo $selfUrl; ?>?modo=probar&sub=<?php echo urlencode($site['name']); ?>" class="nav-btn btn-fix-one" style="padding:3px 8px;font-size:0.72em;">&#128295; Fix</a>
                    <a href="<?php echo $selfUrl; ?>?modo=diagnostico&sub=<?php echo urlencode($site['name']); ?>" class="nav-btn btn-diag" style="padding:3px 8px;font-size:0.72em;">&#128270;</a>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <script>
    function filterTable() {
        var q = document.getElementById('searchInput').value.toLowerCase();
        document.querySelectorAll('.site-row').forEach(function(r) {
            r.style.display = r.getAttribute('data-name').indexOf(q) !== -1 ? '' : 'none';
        });
    }
    </script>

<?php elseif ($modo === 'probar'): ?>
    <div class="info-box">
        <strong>Subdominio:</strong> <?php echo htmlspecialchars($currentSite['name']); ?>
        &mdash; <em><?php echo htmlspecialchars($currentSite['title']); ?></em>
    </div>

    <h2>Resultado del Fix</h2>
    <table>
        <thead><tr><th>Template</th><th>Antes</th><th>Accion</th><th>Despues</th></tr></thead>
        <tbody>
        <?php foreach ($fixResults as $idx => $r): ?>
            <tr>
                <td><strong><?php echo htmlspecialchars($r['template']); ?></strong><br><span class="detail-text"><?php echo htmlspecialchars($r['file']); ?></span></td>
                <td>
                    <?php echo statusBadge($beforeAnalysis[$idx]['status']); ?>
                    <?php if (!empty($beforeAnalysis[$idx]['line'])): ?>
                    <div class="raw-line"><?php echo htmlspecialchars(substr($beforeAnalysis[$idx]['line'], 0, 100)); ?></div>
                    <?php endif; ?>
                </td>
                <td>
                    <?php echo statusBadge($r['status']); ?>
                    <div class="detail-text"><?php echo htmlspecialchars($r['detail']); ?></div>
                </td>
                <td>
                    <?php echo statusBadge($afterAnalysis[$idx]['status']); ?>
                    <?php if (!empty($afterAnalysis[$idx]['line'])): ?>
                    <div class="raw-line"><?php echo htmlspecialchars(substr($afterAnalysis[$idx]['line'], 0, 100)); ?></div>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <?php if ($stats['fixed'] > 0): ?>
    <div class="complete">
        <h2>&#9989; FIX APLICADO</h2>
        <p><?php echo $stats['fixed']; ?> archivo(s) corregido(s)</p>
        <p style="color:#a29bfe;font-size:0.85em;margin-top:5px;">HTML puro - cambio inmediato, sin cache</p>
    </div>
    <?php endif; ?>

    <div class="nav" style="margin-top:15px;">
        <a href="<?php echo $selfUrl; ?>?modo=revertir&sub=<?php echo urlencode($currentSite['name']); ?>" class="nav-btn btn-revert" onclick="return confirm('Revertir el fix?')">&#8634; Revertir</a>
        <a href="<?php echo $selfUrl; ?>?modo=diagnostico&sub=<?php echo urlencode($currentSite['name']); ?>" class="nav-btn btn-diag">&#128270; Ver Diagnostico</a>
        <a href="<?php echo $selfUrl; ?>?modo=todos" class="nav-btn btn-fix-all" onclick="return confirm('Aplicar a TODOS?')">&#9989; Aplicar a TODOS</a>
        <a href="<?php echo $selfUrl; ?>?modo=escanear" class="nav-btn btn-scan">&#128269; Volver</a>
    </div>

<?php elseif ($modo === 'todos' || $modo === 'forzar'): ?>
    <div class="stats">
        <div class="stat-box"><div class="stat-value val-blue"><?php echo $stats['total']; ?></div><div class="stat-label">Sistemas</div></div>
        <div class="stat-box"><div class="stat-value val-green"><?php echo $stats['fixed']; ?></div><div class="stat-label">Corregidos</div></div>
        <div class="stat-box"><div class="stat-value val-blue"><?php echo $stats['ok']; ?></div><div class="stat-label">Ya OK</div></div>
        <div class="stat-box"><div class="stat-value val-gray"><?php echo $stats['not_found']; ?></div><div class="stat-label">Sin topbar</div></div>
        <div class="stat-box"><div class="stat-value val-red"><?php echo $stats['error']; ?></div><div class="stat-label">Errores</div></div>
    </div>

    <div class="complete">
        <h2>&#9989; PROCESO COMPLETADO</h2>
        <p><?php echo $stats['fixed']; ?> corregidos, <?php echo $stats['ok']; ?> ya estaban bien</p>
        <p style="color:#a29bfe;font-size:0.85em;margin-top:5px;">HTML puro - cambios inmediatos, sin cache</p>
    </div>

    <h2>Detalle por Sistema</h2>
    <div class="search-box">
        <input type="text" id="searchInput" placeholder="Buscar subdominio..." onkeyup="filterTable()">
    </div>
    <div class="table-wrap">
    <table id="sitesTable">
        <thead><tr><th>#</th><th>Subdominio</th><th>20cones</th><th>21cones</th></tr></thead>
        <tbody>
        <?php foreach ($allSites as $idx => $site): ?>
            <tr class="site-row" data-name="<?php echo htmlspecialchars(strtolower($site['name'])); ?>">
                <td><?php echo $idx + 1; ?></td>
                <td>
                    <strong style="color:#fdcb6e;"><?php echo htmlspecialchars($site['name']); ?></strong>
                    <span class="site-title"><?php echo htmlspecialchars($site['title']); ?></span>
                </td>
                <?php foreach ($site['fix_results'] as $r): ?>
                <td>
                    <?php echo statusBadge($r['status']); ?>
                    <div class="detail-text"><?php echo htmlspecialchars($r['detail']); ?></div>
                </td>
                <?php endforeach; ?>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <div class="nav" style="margin-top:15px;">
        <a href="<?php echo $selfUrl; ?>?modo=escanear" class="nav-btn btn-scan">&#128269; Verificar con Escaner</a>
    </div>
    <script>
    function filterTable() {
        var q = document.getElementById('searchInput').value.toLowerCase();
        document.querySelectorAll('.site-row').forEach(function(r) {
            r.style.display = r.getAttribute('data-name').indexOf(q) !== -1 ? '' : 'none';
        });
    }
    </script>

<?php elseif ($modo === 'revertir'): ?>
    <div class="info-box">
        <strong>Subdominio:</strong> <?php echo htmlspecialchars($currentSite['name']); ?>
        &mdash; <em><?php echo htmlspecialchars($currentSite['title']); ?></em>
    </div>
    <h2>Resultado de la Reversion</h2>
    <table>
        <thead><tr><th>Template</th><th>Resultado</th></tr></thead>
        <tbody>
        <?php foreach ($revertResults as $r): ?>
            <tr>
                <td><strong><?php echo htmlspecialchars($r['template']); ?></strong></td>
                <td><?php echo statusBadge($r['status']); ?> <span class="detail-text"><?php echo htmlspecialchars($r['detail']); ?></span></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php if ($stats['reverted'] > 0): ?>
    <div class="complete" style="background:#1a1a3a;border-color:#6c5ce7;">
        <h2 style="color:#a29bfe;">&#8634; REVERSION COMPLETADA</h2>
        <p><?php echo $stats['reverted']; ?> archivo(s) restaurados</p>
    </div>
    <?php endif; ?>
    <div class="nav" style="margin-top:15px;">
        <a href="<?php echo $selfUrl; ?>?modo=escanear" class="nav-btn btn-scan">&#128269; Volver</a>
    </div>

<?php elseif ($modo === 'diagnostico'): ?>
    <div class="info-box">
        <strong>Diagnostico:</strong> <?php echo htmlspecialchars($currentSite['name']); ?>
        &mdash; <em><?php echo htmlspecialchars($currentSite['title']); ?></em>
    </div>

    <?php foreach ($diagnosticData as $d): ?>
    <h2><?php echo htmlspecialchars($d['file']); ?></h2>
    <?php if (!$d['exists']): ?>
        <p style="color:#ff6b6b;">Archivo no existe</p>
    <?php else: ?>
        <p style="color:#888;font-size:0.85em;">
            Tamano: <?php echo $d['size']; ?> bytes &mdash;
            Modificado: <?php echo $d['mtime']; ?>
        </p>
        <h3 style="color:#a29bfe;font-size:0.9em;margin:10px 0 5px;">Contenido completo:</h3>
        <pre class="raw-content"><?php echo htmlspecialchars($d['content']); ?></pre>
    <?php endif; ?>
    <?php endforeach; ?>

    <div class="nav" style="margin-top:15px;">
        <a href="<?php echo $selfUrl; ?>?modo=probar&sub=<?php echo urlencode($currentSite['name']); ?>" class="nav-btn btn-fix-one">&#128295; Aplicar Fix</a>
        <a href="<?php echo $selfUrl; ?>?modo=escanear" class="nav-btn btn-scan">&#128269; Volver</a>
    </div>

<?php endif; ?>

    <div class="footer-info">
        <p>Ruta base: <?php echo htmlspecialchars(SEARCH_PATH); ?></p>
        <p>Ejecutado: <?php echo date('Y-m-d H:i:s'); ?></p>
    </div>
</div>
</body>
</html>
