<?php
/**
 * ANALIZADOR DE PESO/TAMAÑO DE SISTEMAS SIE
 * ==========================================
 * Escanea cada subdominio DokuWiki y calcula el tamaño total,
 * desglosado por carpetas principales (data/media, data/pages, data/attic, etc.)
 *
 * MODOS:
 *   ?modo=escanear   (default) - Analizar todos los subdominios
 *   ?sub=nombre                - Analizar uno solo (detalle)
 *   ?orden=peso|nombre         - Ordenar resultados
 *
 * NO MODIFICA NADA - Solo lectura
 */

// =====================================================================
//  CONFIGURACION
// =====================================================================

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

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

// Carpetas clave de DokuWiki a analizar
$carpetasClave = [
    'data/media'  => 'Media (archivos)',
    'data/pages'  => 'Paginas wiki',
    'data/attic'  => 'Historial (attic)',
    'data/meta'   => 'Metadata',
    'data/cache'  => 'Cache',
    'data/tmp'    => 'Temporales',
    'data/log'    => 'Logs',
    'lib/plugins' => 'Plugins',
    'lib/tpl'     => 'Templates',
    'conf'        => 'Configuracion',
];

// =====================================================================
//  PARAMETROS
// =====================================================================

$esCLI = (php_sapi_name() === 'cli');

if (!$esCLI) {
    header('Content-Type: text/html; charset=UTF-8');
}

$modo      = $esCLI ? ($argv[1] ?? 'escanear') : ($_GET['modo'] ?? 'escanear');
$targetSub = $esCLI ? ($argv[2] ?? '')          : ($_GET['sub'] ?? '');
$orden     = $esCLI ? ($argv[3] ?? 'peso')      : ($_GET['orden'] ?? 'peso');

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));
}

// =====================================================================
//  FUNCIONES DE ANALISIS
// =====================================================================

/**
 * Calcula el tamaño total de una carpeta recursivamente
 */
function calcularPeso($dir)
{
    if (!is_dir($dir)) return ['size' => 0, 'files' => 0];

    $size  = 0;
    $files = 0;

    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($it as $file) {
        if ($file->isFile()) {
            $size += $file->getSize();
            $files++;
        }
    }

    return ['size' => $size, 'files' => $files];
}

/**
 * Cuenta archivos stub (0 bytes) en data/media
 */
function contarStubs($mediaDir)
{
    if (!is_dir($mediaDir)) return ['stubs' => 0, 'con_contenido' => 0];

    $stubs = 0;
    $conContenido = 0;

    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($mediaDir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($it as $file) {
        if ($file->isFile()) {
            if ($file->getSize() === 0) {
                $stubs++;
            } else {
                $conContenido++;
            }
        }
    }

    return ['stubs' => $stubs, 'con_contenido' => $conContenido];
}

/**
 * Formatea bytes a unidad legible
 */
function formatBytes($bytes, $decimals = 2)
{
    if ($bytes <= 0) return '0 B';
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = floor(log($bytes, 1024));
    return round($bytes / pow(1024, $i), $decimals) . ' ' . $units[$i];
}

/**
 * Analiza un subdominio completo
 */
function analizarSubdominio($subPath, $carpeta, $carpetasClave)
{
    $r = [
        'carpeta'     => $carpeta,
        'tiene_doku'  => false,
        'total_size'  => 0,
        'total_files' => 0,
        'desglose'    => [],
        'stubs'       => 0,
        'con_contenido' => 0,
        'otros_size'  => 0,
        'otros_files' => 0,
    ];

    if (!file_exists($subPath . '/doku.php')) return $r;
    $r['tiene_doku'] = true;

    // Calcular peso total del subdominio
    $total = calcularPeso($subPath);
    $r['total_size']  = $total['size'];
    $r['total_files'] = $total['files'];

    // Desglose por carpetas clave
    $sizeContabilizado = 0;
    $filesContabilizado = 0;
    foreach ($carpetasClave as $relPath => $label) {
        $fullPath = $subPath . '/' . $relPath;
        $info = calcularPeso($fullPath);
        $r['desglose'][$relPath] = [
            'label' => $label,
            'size'  => $info['size'],
            'files' => $info['files'],
        ];
        $sizeContabilizado  += $info['size'];
        $filesContabilizado += $info['files'];
    }

    // Otros (lo que no está en las carpetas clave)
    $r['otros_size']  = max(0, $r['total_size'] - $sizeContabilizado);
    $r['otros_files'] = max(0, $r['total_files'] - $filesContabilizado);

    // Contar stubs en media
    $stubInfo = contarStubs($subPath . '/data/media');
    $r['stubs'] = $stubInfo['stubs'];
    $r['con_contenido'] = $stubInfo['con_contenido'];

    return $r;
}

// =====================================================================
//  EJECUCION
// =====================================================================

$tiempoInicio = microtime(true);
$resultados   = [];

// Obtener lista de carpetas
if (!empty($targetSub)) {
    $carpetas = [$targetSub];
} else {
    $carpetas = [];
    $scan = @scandir($basePath);
    if (!$scan) {
        echo $esCLI ? "ERROR: No se puede leer {$basePath}\n" : "<p style='color:red'>ERROR: No se puede leer {$basePath}</p>";
        exit(1);
    }
    foreach ($scan as $c) {
        if (in_array($c, $excluir)) continue;
        if (!is_dir($basePath . '/' . $c)) continue;
        $carpetas[] = $c;
    }
    sort($carpetas);
}

// Escanear
foreach ($carpetas as $carpeta) {
    $subPath = $basePath . '/' . $carpeta;
    $r = analizarSubdominio($subPath, $carpeta, $carpetasClave);
    if (!$r['tiene_doku']) continue;
    $resultados[] = $r;
}

// Ordenar
if ($orden === 'peso') {
    usort($resultados, fn($a, $b) => $b['total_size'] - $a['total_size']);
} elseif ($orden === 'nombre') {
    usort($resultados, fn($a, $b) => strcasecmp($a['carpeta'], $b['carpeta']));
} elseif ($orden === 'media') {
    usort($resultados, fn($a, $b) => ($b['desglose']['data/media']['size'] ?? 0) - ($a['desglose']['data/media']['size'] ?? 0));
} elseif ($orden === 'cache') {
    usort($resultados, fn($a, $b) => ($b['desglose']['data/cache']['size'] ?? 0) - ($a['desglose']['data/cache']['size'] ?? 0));
}

$tiempoFin = round(microtime(true) - $tiempoInicio, 2);

// Estadisticas globales
$totalSizeAll     = array_sum(array_column($resultados, 'total_size'));
$totalFilesAll    = array_sum(array_column($resultados, 'total_files'));
$totalMediaSize   = array_sum(array_map(fn($r) => $r['desglose']['data/media']['size'] ?? 0, $resultados));
$totalCacheSize   = array_sum(array_map(fn($r) => $r['desglose']['data/cache']['size'] ?? 0, $resultados));
$totalAtticSize   = array_sum(array_map(fn($r) => $r['desglose']['data/attic']['size'] ?? 0, $resultados));
$totalPagesSize   = array_sum(array_map(fn($r) => $r['desglose']['data/pages']['size'] ?? 0, $resultados));
$totalStubs       = array_sum(array_column($resultados, 'stubs'));
$totalConContenido = array_sum(array_column($resultados, 'con_contenido'));

// Top 5 mas pesados
$top5 = array_slice($resultados, 0, 5);
if ($orden !== 'peso') {
    $sorted = $resultados;
    usort($sorted, fn($a, $b) => $b['total_size'] - $a['total_size']);
    $top5 = array_slice($sorted, 0, 5);
}

// =====================================================================
//  SALIDA CLI
// =====================================================================

if ($esCLI) {
    echo "================================================================\n";
    echo " ANALIZADOR DE PESO - SUBDOMINIOS SIE\n";
    echo " " . date('Y-m-d H:i:s') . " | Tiempo: {$tiempoFin}s\n";
    echo "================================================================\n\n";

    echo "Total: " . count($resultados) . " sistemas | Peso total: " . formatBytes($totalSizeAll) . " | Archivos: " . number_format($totalFilesAll) . "\n\n";

    echo sprintf("  %-30s %12s %10s %12s %12s\n", "Subdominio", "Total", "Archivos", "Media", "Cache");
    echo str_repeat('-', 80) . "\n";
    foreach ($resultados as $r) {
        echo sprintf("  %-30s %12s %10s %12s %12s\n",
            $r['carpeta'],
            formatBytes($r['total_size']),
            number_format($r['total_files']),
            formatBytes($r['desglose']['data/media']['size'] ?? 0),
            formatBytes($r['desglose']['data/cache']['size'] ?? 0)
        );
    }
    exit(0);
}

// =====================================================================
//  SALIDA HTML
// =====================================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Analizador de Peso - SIE</title>
<style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f1f5f9; color: #1e293b; padding: 20px; }
    .container { max-width: 1500px; margin: 0 auto; }
    h1 { font-size: 1.5em; color: #0f172a; margin-bottom: 4px; }
    .subtitle { color: #64748b; font-size: 0.88em; margin-bottom: 20px; }

    .summary { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px; margin-bottom: 20px; }
    .card { background: #fff; border-radius: 10px; padding: 14px; text-align: center; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
    .card .num { font-size: 1.6em; font-weight: 700; }
    .card .label { font-size: 0.78em; color: #64748b; margin-top: 2px; }
    .green { color: #16a34a; } .red { color: #dc2626; } .yellow { color: #d97706; } .blue { color: #2563eb; } .purple { color: #7c3aed; } .orange { color: #ea580c; }

    .section { background: #fff; border-radius: 10px; padding: 20px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
    .section h2 { font-size: 1.1em; margin-bottom: 12px; }

    .explain { background: #eff6ff; border: 1px solid #93c5fd; border-radius: 10px; padding: 16px; margin-bottom: 20px; }
    .explain h2 { color: #1e40af; margin-bottom: 8px; font-size: 1em; }
    .explain p { font-size: 0.86em; color: #334155; margin-bottom: 4px; }

    .actions { display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; align-items: center; }
    .btn { padding: 10px 20px; border: none; border-radius: 8px; font-size: 0.9em; cursor: pointer; text-decoration: none; display: inline-block; font-weight: 600; }
    .btn-blue { background: #2563eb; color: #fff; } .btn-blue:hover { background: #1d4ed8; }
    .btn-gray { background: #64748b; color: #fff; }
    .btn-active { background: #0f172a; color: #fff; }

    .top5 { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 12px; margin-bottom: 20px; }
    .top-card { background: #fff; border-radius: 10px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); border-left: 4px solid #dc2626; }
    .top-card .rank { font-size: 0.75em; color: #94a3b8; font-weight: 700; }
    .top-card .name { font-size: 1em; font-weight: 700; color: #0f172a; }
    .top-card .size { font-size: 1.4em; font-weight: 700; color: #dc2626; }
    .top-card .detail { font-size: 0.8em; color: #64748b; margin-top: 4px; }

    table { width: 100%; border-collapse: collapse; font-size: 0.82em; }
    th { text-align: left; padding: 8px 6px; border-bottom: 2px solid #e2e8f0; color: #475569; font-size: 0.82em; cursor: pointer; }
    th:hover { color: #0f172a; }
    td { padding: 7px 6px; border-bottom: 1px solid #f1f5f9; }
    tr:hover { background: #f8fafc; }

    .bar-container { width: 100%; height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; }
    .bar { height: 100%; border-radius: 4px; }
    .bar-media { background: #3b82f6; }
    .bar-attic { background: #f59e0b; }
    .bar-cache { background: #ef4444; }
    .bar-pages { background: #22c55e; }

    .badge { display: inline-block; padding: 2px 7px; border-radius: 4px; font-size: 0.76em; font-weight: 600; }
    .badge-heavy { background: #fee2e2; color: #991b1b; }
    .badge-medium { background: #fef3c7; color: #92400e; }
    .badge-light { background: #dcfce7; color: #166534; }

    .filter-bar { margin-bottom: 12px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
    .filter-bar input, .filter-bar select { padding: 6px 10px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.86em; }
    .filter-bar input { width: 200px; }

    /* Detalle de un subdominio */
    .detail-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
    .detail-bar { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
    .detail-bar .label { width: 140px; font-size: 0.85em; font-weight: 600; }
    .detail-bar .bar-wrap { flex: 1; height: 20px; background: #e2e8f0; border-radius: 6px; overflow: hidden; position: relative; }
    .detail-bar .bar-fill { height: 100%; border-radius: 6px; transition: width 0.3s; }
    .detail-bar .val { width: 100px; text-align: right; font-size: 0.85em; font-weight: 600; }
</style>
</head>
<body>
<div class="container">

<h1>&#128202; Analizador de Peso - Subdominios SIE</h1>
<p class="subtitle">
    <?= date('Y-m-d H:i:s') ?> |
    Tiempo: <?= $tiempoFin ?>s |
    Sistemas: <?= count($resultados) ?>
    <?php if (!empty($targetSub)): ?> | Sub: <strong><?= htmlspecialchars($targetSub) ?></strong><?php endif; ?>
</p>

<div class="explain">
    <h2>&#128161; Que analiza este script</h2>
    <p>Escanea cada subdominio DokuWiki y calcula el peso total desglosado por carpetas principales.</p>
    <p>Identifica los sistemas mas pesados y donde se concentra el espacio (media, cache, historial, etc.).</p>
    <p><strong>Solo lectura</strong> — no modifica ningun archivo.</p>
</div>

<!-- Resumen global -->
<div class="summary">
    <div class="card"><div class="num blue"><?= count($resultados) ?></div><div class="label">Sistemas DokuWiki</div></div>
    <div class="card"><div class="num red"><?= formatBytes($totalSizeAll) ?></div><div class="label">Peso Total</div></div>
    <div class="card"><div class="num purple"><?= number_format($totalFilesAll) ?></div><div class="label">Total Archivos</div></div>
    <div class="card"><div class="num blue"><?= formatBytes($totalMediaSize) ?></div><div class="label">Media (archivos)</div></div>
    <div class="card"><div class="num orange"><?= formatBytes($totalAtticSize) ?></div><div class="label">Historial (attic)</div></div>
    <div class="card"><div class="num red"><?= formatBytes($totalCacheSize) ?></div><div class="label">Cache</div></div>
    <div class="card"><div class="num green"><?= formatBytes($totalPagesSize) ?></div><div class="label">Paginas wiki</div></div>
    <?php if ($totalStubs > 0): ?>
    <div class="card"><div class="num yellow"><?= number_format($totalStubs) ?></div><div class="label">Stubs (0 bytes)</div></div>
    <?php endif; ?>
</div>

<!-- Botones -->
<div class="actions">
    <a href="?orden=peso" class="btn <?= $orden === 'peso' ? 'btn-active' : 'btn-blue' ?>">&#128201; Ordenar por peso</a>
    <a href="?orden=nombre" class="btn <?= $orden === 'nombre' ? 'btn-active' : 'btn-blue' ?>">&#128196; Ordenar por nombre</a>
    <a href="?orden=media" class="btn <?= $orden === 'media' ? 'btn-active' : 'btn-blue' ?>">&#128247; Ordenar por media</a>
    <a href="?orden=cache" class="btn <?= $orden === 'cache' ? 'btn-active' : 'btn-blue' ?>">&#128165; Ordenar por cache</a>
    <?php if (!empty($targetSub)): ?>
        <a href="?" class="btn btn-gray">Ver todos</a>
    <?php endif; ?>
</div>

<?php if (!empty($targetSub) && count($resultados) === 1): ?>
<!-- ============ DETALLE DE UN SUBDOMINIO ============ -->
<?php $r = $resultados[0]; ?>
<div class="section">
    <h2>&#128194; Detalle: <?= htmlspecialchars($r['carpeta']) ?> (<?= formatBytes($r['total_size']) ?>)</h2>

    <div style="margin-top:16px;">
    <?php
    $colors = [
        'data/media'  => '#3b82f6',
        'data/pages'  => '#22c55e',
        'data/attic'  => '#f59e0b',
        'data/meta'   => '#8b5cf6',
        'data/cache'  => '#ef4444',
        'data/tmp'    => '#64748b',
        'data/log'    => '#06b6d4',
        'lib/plugins' => '#ec4899',
        'lib/tpl'     => '#14b8a6',
        'conf'        => '#a855f7',
    ];
    foreach ($r['desglose'] as $relPath => $info):
        $pct = $r['total_size'] > 0 ? round(($info['size'] / $r['total_size']) * 100, 1) : 0;
        $color = $colors[$relPath] ?? '#94a3b8';
    ?>
    <div class="detail-bar">
        <div class="label"><?= htmlspecialchars($info['label']) ?></div>
        <div class="bar-wrap">
            <div class="bar-fill" style="width:<?= $pct ?>%;background:<?= $color ?>"></div>
        </div>
        <div class="val"><?= formatBytes($info['size']) ?></div>
        <div style="width:60px;text-align:right;font-size:0.8em;color:#94a3b8;"><?= number_format($info['files']) ?> arch</div>
        <div style="width:50px;text-align:right;font-size:0.8em;color:#64748b;"><?= $pct ?>%</div>
    </div>
    <?php endforeach; ?>

    <?php if ($r['otros_size'] > 0):
        $pctOtros = round(($r['otros_size'] / $r['total_size']) * 100, 1);
    ?>
    <div class="detail-bar">
        <div class="label">Otros</div>
        <div class="bar-wrap">
            <div class="bar-fill" style="width:<?= $pctOtros ?>%;background:#94a3b8"></div>
        </div>
        <div class="val"><?= formatBytes($r['otros_size']) ?></div>
        <div style="width:60px;text-align:right;font-size:0.8em;color:#94a3b8;"><?= number_format($r['otros_files']) ?> arch</div>
        <div style="width:50px;text-align:right;font-size:0.8em;color:#64748b;"><?= $pctOtros ?>%</div>
    </div>
    <?php endif; ?>
    </div>

    <?php if ($r['stubs'] > 0 || $r['con_contenido'] > 0): ?>
    <div style="margin-top:16px;padding:12px;background:#eff6ff;border-radius:8px;">
        <strong>&#128194; Media:</strong>
        <?= number_format($r['con_contenido']) ?> archivos con contenido |
        <?= number_format($r['stubs']) ?> stubs (0 bytes - Wasabi)
    </div>
    <?php endif; ?>
</div>

<?php else: ?>
<!-- ============ TOP 5 MAS PESADOS ============ -->
<div class="section">
    <h2>&#127942; Top 5 mas pesados</h2>
    <div class="top5">
    <?php foreach ($top5 as $i => $r): ?>
        <div class="top-card">
            <div class="rank">#<?= $i + 1 ?></div>
            <div class="name"><?= htmlspecialchars($r['carpeta']) ?></div>
            <div class="size"><?= formatBytes($r['total_size']) ?></div>
            <div class="detail">
                Media: <?= formatBytes($r['desglose']['data/media']['size'] ?? 0) ?> |
                Cache: <?= formatBytes($r['desglose']['data/cache']['size'] ?? 0) ?> |
                Attic: <?= formatBytes($r['desglose']['data/attic']['size'] ?? 0) ?>
            </div>
        </div>
    <?php endforeach; ?>
    </div>
</div>

<!-- ============ TABLA COMPLETA ============ -->
<div class="section">
    <h2>&#128203; Todos los sistemas (<?= count($resultados) ?>)</h2>
    <div class="filter-bar">
        <input type="text" id="filtro" placeholder="Buscar subdominio..." oninput="filtrar()">
    </div>
    <table id="tabla">
        <thead>
            <tr>
                <th>#</th>
                <th>Subdominio</th>
                <th>Peso Total</th>
                <th>Archivos</th>
                <th>Media</th>
                <th>Cache</th>
                <th>Attic</th>
                <th>Paginas</th>
                <th>Distribucion</th>
                <th>Categoria</th>
            </tr>
        </thead>
        <tbody>
        <?php $i = 0; foreach ($resultados as $r): $i++;
            $mediaSize = $r['desglose']['data/media']['size'] ?? 0;
            $cacheSize = $r['desglose']['data/cache']['size'] ?? 0;
            $atticSize = $r['desglose']['data/attic']['size'] ?? 0;
            $pagesSize = $r['desglose']['data/pages']['size'] ?? 0;

            // Categorizar por peso
            if ($r['total_size'] > 500 * 1024 * 1024) {
                $catClass = 'badge-heavy'; $catLabel = 'PESADO';
            } elseif ($r['total_size'] > 100 * 1024 * 1024) {
                $catClass = 'badge-medium'; $catLabel = 'MEDIO';
            } else {
                $catClass = 'badge-light'; $catLabel = 'LIVIANO';
            }

            // Barras proporcionales
            $total = max($r['total_size'], 1);
            $pctMedia = round(($mediaSize / $total) * 100);
            $pctCache = round(($cacheSize / $total) * 100);
            $pctAttic = round(($atticSize / $total) * 100);
            $pctPages = round(($pagesSize / $total) * 100);
        ?>
            <tr data-name="<?= htmlspecialchars(strtolower($r['carpeta'])) ?>">
                <td><?= $i ?></td>
                <td>
                    <a href="?sub=<?= urlencode($r['carpeta']) ?>" style="font-weight:700;color:#1e40af;text-decoration:none;">
                        <?= htmlspecialchars($r['carpeta']) ?>
                    </a>
                </td>
                <td><strong><?= formatBytes($r['total_size']) ?></strong></td>
                <td><?= number_format($r['total_files']) ?></td>
                <td><?= formatBytes($mediaSize) ?></td>
                <td><?= formatBytes($cacheSize) ?></td>
                <td><?= formatBytes($atticSize) ?></td>
                <td><?= formatBytes($pagesSize) ?></td>
                <td>
                    <div class="bar-container" title="Media:<?= $pctMedia ?>% Cache:<?= $pctCache ?>% Attic:<?= $pctAttic ?>% Pages:<?= $pctPages ?>%">
                        <div style="display:flex;height:100%;">
                            <div class="bar bar-media" style="width:<?= $pctMedia ?>%"></div>
                            <div class="bar bar-cache" style="width:<?= $pctCache ?>%"></div>
                            <div class="bar bar-attic" style="width:<?= $pctAttic ?>%; background:#f59e0b;"></div>
                            <div class="bar bar-pages" style="width:<?= $pctPages ?>%"></div>
                        </div>
                    </div>
                </td>
                <td><span class="badge <?= $catClass ?>"><?= $catLabel ?></span></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <div style="margin-top:12px;font-size:0.78em;color:#94a3b8;">
        Leyenda barra: <span style="color:#3b82f6;">&#9632;</span> Media
        <span style="color:#ef4444;">&#9632;</span> Cache
        <span style="color:#f59e0b;">&#9632;</span> Attic
        <span style="color:#22c55e;">&#9632;</span> Paginas
    </div>
</div>
<?php endif; ?>

</div><!-- /container -->

<script>
function filtrar() {
    var texto = document.getElementById('filtro').value.toLowerCase();
    var rows = document.querySelectorAll('#tabla tbody tr');
    rows.forEach(function(row) {
        var name = row.dataset.name || '';
        row.style.display = (!texto || name.indexOf(texto) !== -1) ? '' : 'none';
    });
}
</script>
</body>
</html>
