<?php
/**
 * Estado de Limpieza NICC v1 - estado.php
 * =========================================
 * Dashboard que muestra el estado de la limpieza por subdominio.
 * Lee el archivo de progreso y re-escanea para verificacion.
 */

require_once __DIR__ . '/config.php';

set_time_limit(60);
ini_set('memory_limit', MEMORY_LIMIT);

// ============================================================
// AUTENTICACION: Requiere token via GET o sesion
// ============================================================
session_start();

$tokenOk = false;

// Verificar token via parametro GET
if (isset($_GET['token']) && $_GET['token'] === SECURITY_TOKEN) {
    $_SESSION['limpieza_auth'] = true;
    $tokenOk = true;
}

// Verificar sesion previa (si ya se autentico en limpiar.php o antes)
if (isset($_SESSION['limpieza_auth']) && $_SESSION['limpieza_auth'] === true) {
    $tokenOk = true;
}

if (!$tokenOk) {
    http_response_code(403);
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Acceso denegado</title>';
    echo '<style>body{background:#1a1a2e;color:#ff6b6b;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;}';
    echo '.box{text-align:center;}.box a{color:#74b9ff;}</style></head>';
    echo '<body><div class="box"><h2>Acceso denegado</h2><p>Token requerido. Use: estado.php?token=XXXXX</p>';
    echo '<p>O acceda primero desde <a href="limpiar.php">limpiar.php</a></p></div></body></html>';
    exit;
}

// ============================================================
// FUNCIONES (reutilizadas de limpiar.php)
// ============================================================

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 scanDirectory($path) {
    $sites = [];
    if (!is_dir($path)) return $sites;
    $items = @scandir($path);
    if ($items === false) return $sites;
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        if ($item[0] === '_') continue;               // Ignorar carpetas internas
        $fullPath = $path . '/' . $item;
        if (!is_dir($fullPath)) continue;
        if (is_link($fullPath)) continue;              // Ignorar symlinks
        if (isDokuWiki($fullPath)) {
            $sites[] = $fullPath;
        }
    }
    return $sites;
}

function isExcludedByList($sitePath) {
    global $EXCLUSION_LIST;
    if (empty($EXCLUSION_LIST)) return false;
    $siteName = strtolower(basename($sitePath));
    foreach ($EXCLUSION_LIST as $excluded) {
        if ($siteName === strtolower($excluded)) return $excluded;
    }
    return false;
}

function getLetraFromNombre($nombre) {
    $first = strtoupper(substr($nombre, 0, 1));
    if (ctype_alpha($first)) return $first;
    return '#';
}

function formatBytes($bytes) {
    if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576) return number_format($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024) return number_format($bytes / 1024, 2) . ' KB';
    return $bytes . ' bytes';
}

/**
 * Verifica el estado de limpieza de un subdominio
 * Cuenta cuantos archivos/dirs del DELETE list todavia existen
 */
function verificarLimpieza($sitePath) {
    global $DELETE_ROOT_FILES, $DELETE_DIRS;

    $pendientes = 0;

    // Verificar archivos raiz
    foreach ($DELETE_ROOT_FILES as $file) {
        if (file_exists($sitePath . '/' . $file)) {
            $pendientes++;
        }
    }

    // Verificar directorios (solo primer nivel de contenido)
    foreach ($DELETE_DIRS as $dir) {
        $fullDir = $sitePath . '/' . $dir;
        if (is_dir($fullDir)) {
            $items = @scandir($fullDir);
            if ($items !== false) {
                $items = array_diff($items, ['.', '..']);
                // Si el directorio tiene contenido, contar como pendiente
                // (ignorar si solo tiene archivos protegidos)
                if (!empty($items)) {
                    $pendientes++;
                }
            }
        }
    }

    return $pendientes;
}

// ============================================================
// CARGAR DATOS
// ============================================================

// Progreso
$progress = null;
if (file_exists(PROGRESS_FILE)) {
    $progress = json_decode(file_get_contents(PROGRESS_FILE), true);
}

// Escanear sitios
$sites = scanDirectory(SEARCH_PATH);
sort($sites);
$totalSites = count($sites);

// Estado de cada sitio
$siteStatuses = [];
$countLimpio = 0;
$countExcluido = 0;
$countError = 0;
$countPendiente = 0;

foreach ($sites as $sitePath) {
    $siteName = basename($sitePath);
    $letra = getLetraFromNombre($siteName);

    // Verificar si fue procesado
    $procesado = $progress && isset($progress['procesados'][$sitePath]);
    $stats = $procesado ? $progress['procesados'][$sitePath] : null;

    // Verificar exclusion
    $excludedBy = isExcludedByList($sitePath);
    $hasExclFile = file_exists($sitePath . '/' . EXCLUSION_FILE);
    $isExcluded = ($excludedBy || $hasExclFile);

    // Determinar estado
    $estado = 'pendiente';
    if ($isExcluded) {
        $estado = 'excluido';
        $countExcluido++;
    } elseif ($procesado && $stats && $stats['errores'] > 0) {
        $estado = 'error';
        $countError++;
    } elseif ($procesado) {
        $estado = 'limpio';
        $countLimpio++;
    } else {
        $countPendiente++;
    }

    // Verificar cuantos items del DELETE list aun existen
    $pendientes = verificarLimpieza($sitePath);

    $siteStatuses[] = [
        'name'       => $siteName,
        'path'       => $sitePath,
        'letra'      => $letra,
        'estado'     => $estado,
        'excluido'   => $isExcluded,
        'motivo_excl'=> $excludedBy ? "lista ($excludedBy)" : ($hasExclFile ? 'exclusion.txt' : ''),
        'stats'      => $stats,
        'pendientes' => $pendientes,
    ];
}

// Totales del progreso
$totalEliminados = $progress ? ($progress['total_eliminados'] ?? 0) : 0;
$totalProtegidos = $progress ? ($progress['total_protegidos'] ?? 0) : 0;
$totalErrores    = $progress ? ($progress['total_errores'] ?? 0) : 0;
$totalSymlinks   = $progress ? ($progress['total_symlinks'] ?? 0) : 0;

// Leer logs recientes
$logLines = [];
$logDir = LOG_DIR;
if (is_dir($logDir)) {
    $logFiles = glob($logDir . '/limpieza_*.log');
    if (!empty($logFiles)) {
        rsort($logFiles); // Mas reciente primero
        $lastLog = $logFiles[0];
        $content = file_get_contents($lastLog);
        $logLines = array_slice(explode("\n", $content), -50);
    }
}

?><!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Estado - Limpieza NICC v1</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: 1000px; margin: 0 auto; }
        h1 { color: #ff6b6b; margin-bottom: 5px; font-size: 1.4em; }
        h2 { color: #ffd93d; font-size: 1.1em; margin: 15px 0 8px; }
        .subtitle { color: #888; font-size: 0.85em; margin-bottom: 15px; }
        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 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.8em; color: #888; }
        .val-red { color: #ff6b6b; }
        .val-green { color: #00b894; }
        .val-yellow { color: #ffd93d; }
        .val-blue { color: #74b9ff; }
        .val-purple { color: #a29bfe; }
        .val-orange { color: #e17055; }
        table { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 0.82em; }
        th { background: #2a2a4a; padding: 8px; text-align: left; color: #74b9ff; position: sticky; top: 0; }
        td { padding: 6px 8px; border-bottom: 1px solid #333; }
        tr:hover { background: #2a2a4a; }
        .badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 0.75em; font-weight: bold; }
        .badge-ok { background: #00b894; color: #000; }
        .badge-skip { background: #f39c12; color: #000; }
        .badge-pending { background: #636e72; color: #fff; }
        .badge-error { background: #d63031; color: #fff; }
        .btn { display: inline-block; padding: 8px 18px; border-radius: 6px; text-decoration: none; font-weight: bold; font-size: 0.9em; margin: 5px 3px; color: white; border: none; cursor: pointer; }
        .btn-primary { background: #0984e3; }
        .btn-danger { background: #d63031; }
        .btn-info { background: #6c5ce7; }
        .btn:hover { opacity: 0.9; }
        .table-wrap { max-height: 500px; overflow-y: auto; border: 1px solid #333; border-radius: 8px; }
        .log-box { background: #0d0d1a; border: 1px solid #333; padding: 10px; border-radius: 8px; max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 0.78em; line-height: 1.6; }
        .no-progress { background: #2a2a4a; padding: 20px; border-radius: 8px; text-align: center; color: #888; margin: 15px 0; }
        .filter-bar { margin: 10px 0; display: flex; gap: 8px; flex-wrap: wrap; }
        .filter-btn { padding: 4px 12px; border-radius: 15px; border: 1px solid #444; background: #2a2a4a; color: #888; cursor: pointer; font-size: 0.8em; }
        .filter-btn.active { border-color: #74b9ff; color: #74b9ff; background: #1a2a4a; }
    </style>
</head>
<body>
<div class="container">
    <h1>Estado de Limpieza NICC v1</h1>
    <p class="subtitle">Verificacion del estado de limpieza por subdominio</p>

    <!-- Stats globales -->
    <div class="stats">
        <div class="stat-box">
            <div class="stat-value val-blue"><?php echo $totalSites; ?></div>
            <div class="stat-label">Sitios DokuWiki</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-green"><?php echo $countLimpio; ?></div>
            <div class="stat-label">Limpios</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-yellow"><?php echo $countExcluido; ?></div>
            <div class="stat-label">Excluidos</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-orange"><?php echo $countError; ?></div>
            <div class="stat-label">Con errores</div>
        </div>
        <div class="stat-box">
            <div class="stat-value" style="color: #636e72;"><?php echo $countPendiente; ?></div>
            <div class="stat-label">Pendientes</div>
        </div>
    </div>

    <?php if ($progress): ?>
    <div class="stats">
        <div class="stat-box">
            <div class="stat-value val-red"><?php echo number_format($totalEliminados); ?></div>
            <div class="stat-label">Total eliminados</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-green"><?php echo number_format($totalProtegidos); ?></div>
            <div class="stat-label">Total protegidos</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-purple"><?php echo $totalSymlinks; ?></div>
            <div class="stat-label">Symlinks detectados</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-orange"><?php echo $totalErrores; ?></div>
            <div class="stat-label">Total errores</div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Tabla de subdominios -->
    <h2>Detalle por Subdominio</h2>

    <div class="filter-bar">
        <button class="filter-btn active" onclick="filtrar('todos', this)">Todos (<?php echo $totalSites; ?>)</button>
        <button class="filter-btn" onclick="filtrar('limpio', this)">Limpios (<?php echo $countLimpio; ?>)</button>
        <button class="filter-btn" onclick="filtrar('pendiente', this)">Pendientes (<?php echo $countPendiente; ?>)</button>
        <button class="filter-btn" onclick="filtrar('excluido', this)">Excluidos (<?php echo $countExcluido; ?>)</button>
        <button class="filter-btn" onclick="filtrar('error', this)">Errores (<?php echo $countError; ?>)</button>
    </div>

    <div class="table-wrap">
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Letra</th>
                <th>Subdominio</th>
                <th>Estado</th>
                <th>Eliminados</th>
                <th>Protegidos</th>
                <th>Errores</th>
                <th>Tiempo</th>
                <th>Pendientes</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($siteStatuses as $idx => $site): ?>
            <tr data-estado="<?php echo $site['estado']; ?>">
                <td><?php echo $idx + 1; ?></td>
                <td style="color: #74b9ff; font-weight: bold;"><?php echo htmlspecialchars($site['letra']); ?></td>
                <td style="color: #74b9ff;"><?php echo htmlspecialchars($site['name']); ?></td>
                <td>
                    <?php if ($site['estado'] === 'limpio'): ?>
                        <span class="badge badge-ok">LIMPIO</span>
                    <?php elseif ($site['estado'] === 'excluido'): ?>
                        <span class="badge badge-skip">EXCLUIDO</span>
                    <?php elseif ($site['estado'] === 'error'): ?>
                        <span class="badge badge-error">ERROR</span>
                    <?php else: ?>
                        <span class="badge badge-pending">PENDIENTE</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($site['stats']): ?>
                        <span style="color: #ff6b6b;"><?php echo number_format($site['stats']['eliminados']); ?></span>
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($site['stats']): ?>
                        <span style="color: #00b894;"><?php echo number_format($site['stats']['protegidos']); ?></span>
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($site['stats'] && $site['stats']['errores'] > 0): ?>
                        <span style="color: #ff6b6b;"><?php echo $site['stats']['errores']; ?></span>
                    <?php elseif ($site['stats']): ?>
                        <span style="color: #00b894;">0</span>
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($site['stats']): ?>
                        <?php echo $site['stats']['tiempo']; ?>s
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($site['pendientes'] > 0): ?>
                        <span style="color: #ff6b6b;"><?php echo $site['pendientes']; ?></span>
                    <?php elseif (!$site['excluido']): ?>
                        <span style="color: #00b894;">0</span>
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <?php if (!$progress): ?>
    <div class="no-progress">
        No se ha ejecutado ninguna limpieza aun.
    </div>
    <?php endif; ?>

    <!-- Log -->
    <?php if (!empty($logLines)): ?>
    <h2>Log Reciente</h2>
    <div class="log-box">
        <?php foreach ($logLines as $line):
            if (empty(trim($line))) continue;
        ?>
            <div><?php echo htmlspecialchars($line); ?></div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- Acciones -->
    <div style="margin-top: 15px;">
        <a href="limpiar.php" class="btn btn-danger">Ejecutar Limpieza</a>
        <a href="estado.php" class="btn btn-info">Actualizar</a>
    </div>

    <?php if ($progress): ?>
    <div style="margin-top: 10px; color: #888; font-size: 0.8em;">
        Inicio: <?php echo htmlspecialchars($progress['inicio'] ?? 'N/A'); ?>
        | Procesados: <?php echo count($progress['procesados'] ?? []); ?>/<?php echo $totalSites; ?>
    </div>
    <?php endif; ?>
</div>

<script>
function filtrar(estado, btn) {
    // Activar boton
    document.querySelectorAll('.filter-btn').forEach(function(b) { b.classList.remove('active'); });
    btn.classList.add('active');

    // Filtrar filas
    document.querySelectorAll('tbody tr').forEach(function(tr) {
        if (estado === 'todos') {
            tr.style.display = '';
        } else {
            tr.style.display = (tr.getAttribute('data-estado') === estado) ? '' : 'none';
        }
    });
}
</script>
</body>
</html>
