<?php
/**
 * Estado del Parche de Distribucion NICC v2 - estado.php
 * ========================================================
 * Muestra el estado de la distribucion de archivos del sistema.
 * Requiere autenticacion via sesion (desde copiar.php) o token GET.
 */

require_once __DIR__ . '/config.php';

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

// ============================================================
// AUTENTICACION (sesion compartida con copiar.php + token GET)
// ============================================================
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$tokenOk = false;

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

// Verificar sesion (autenticado desde copiar.php)
if (isset($_SESSION['distribucion_auth']) && $_SESSION['distribucion_auth'] === true) {
    $tokenOk = true;
}

if (!$tokenOk) {
    http_response_code(403);
    ?><!DOCTYPE html>
    <html lang="es">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Acceso Denegado - Distribucion NICC v2</title>
        <style>
            body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #1a1a2e; color: #e0e0e0; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; }
            .denied { background: #3d0d0d; border: 2px solid #ff6b6b; padding: 40px; border-radius: 12px; text-align: center; max-width: 400px; }
            .denied h2 { color: #ff6b6b; margin-bottom: 15px; }
            .denied p { color: #888; font-size: 0.9em; margin: 10px 0; }
            .denied a { color: #74b9ff; text-decoration: none; }
            .denied a:hover { text-decoration: underline; }
        </style>
    </head>
    <body>
        <div class="denied">
            <h2>Acceso Denegado</h2>
            <p>Debe autenticarse primero en <a href="copiar.php">copiar.php</a></p>
            <p style="color: #636e72; font-size: 0.8em;">O use ?token=CLAVE en la URL</p>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// ============================================================
// FUNCIONES
// ============================================================

/**
 * Escanea SOLO el nivel inmediato de $path buscando instalaciones DokuWiki.
 * No recursa en subdirectorios para evitar duplicados.
 */
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;
        $fullPath = $path . '/' . $item;
        if (is_link($fullPath)) continue;
        if (!is_dir($fullPath)) continue;

        // Saltar la carpeta sistema/ (fuente de copiado) para no copiarse a si misma
        if (realpath($fullPath) === realpath(SOURCE_DIR)) continue;

        if (isDokuWiki($fullPath)) {
            $sites[] = $fullPath;
        }
    }
    return $sites;
}

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

/**
 * Obtiene la lista de archivos de primer nivel en sistema/ para verificacion rapida
 */
function getSourceTopItems() {
    if (!is_dir(SOURCE_DIR)) return [];
    $items = [];
    $scan = @scandir(SOURCE_DIR);
    if ($scan === false) return [];
    foreach ($scan as $item) {
        if ($item === '.' || $item === '..') continue;
        $items[] = $item;
    }
    return $items;
}

// ============================================================
// DATOS
// ============================================================

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

$zipExists = file_exists(SOURCE_ZIP);
$dirExists = is_dir(SOURCE_DIR);
$sourceTopItems = getSourceTopItems();

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

// Estado de cada sitio
$siteStatuses = [];
foreach ($sites as $sitePath) {
    $siteName = basename($sitePath);
    $status = [
        'name'          => $siteName,
        'path'          => $sitePath,
        'has_exclusion' => file_exists($sitePath . '/' . EXCLUSION_FILE),
        'copiado'       => $progress && in_array($sitePath, $progress['copiados'] ?? []),
        'excluido'      => $progress && in_array($sitePath, $progress['excluidos'] ?? []),
        'error'         => $progress && isset($progress['errores'][$siteName]),
        'items_present' => 0,
    ];

    // Verificar cuantos archivos/carpetas del fuente existen en el destino
    foreach ($sourceTopItems as $item) {
        if (file_exists($sitePath . '/' . $item) || is_dir($sitePath . '/' . $item)) {
            $status['items_present']++;
        }
    }
    $status['items_total'] = count($sourceTopItems);

    $siteStatuses[] = $status;
}

$copiadosCount = $progress ? count($progress['copiados'] ?? []) : 0;
$excluidosCount = $progress ? count($progress['excluidos'] ?? []) : 0;
$erroresCount = $progress ? count($progress['errores'] ?? []) : 0;
$withExclusion = count(array_filter($siteStatuses, function($s) { return $s['has_exclusion']; }));

// Leer logs (rotacion diaria en LOG_DIR)
$logLines = [];
if (is_dir(LOG_DIR)) {
    $logFiles = glob(LOG_DIR . '/distribucion_*.log');
    if (!empty($logFiles)) {
        rsort($logFiles); // mas reciente primero
        $lastLog = $logFiles[0];
        $content = file_get_contents($lastLog);
        if ($content !== false) {
            $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 - Distribucion NICC v2</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: #74b9ff; 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(150px, 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; }
        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; }
        .btn-primary { background: #0984e3; }
        .btn-info { background: #6c5ce7; }
        .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; }
        .source-info { background: #1a2a4a; border: 1px solid #74b9ff; padding: 10px; border-radius: 8px; margin: 10px 0; }
    </style>
</head>
<body>
<div class="container">
    <h1>Estado de Distribucion NICC v2</h1>
    <p class="subtitle">Verificacion de archivos del sistema copiados a cada subdominio</p>

    <div class="source-info">
        <strong>sistema.zip:</strong> <?php echo $zipExists ? 'Presente' : '-- No encontrado'; ?>
        &nbsp;|&nbsp;
        <strong>sistema/:</strong>
        <?php if ($dirExists): ?>
            <?php echo count($sourceTopItems); ?> elementos de primer nivel
        <?php else: ?>
            No existe
        <?php endif; ?>
    </div>

    <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 $copiadosCount; ?></div>
            <div class="stat-label">Copiados</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-yellow"><?php echo $excluidosCount; ?></div>
            <div class="stat-label">Excluidos</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-red"><?php echo $erroresCount; ?></div>
            <div class="stat-label">Errores</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-yellow"><?php echo $withExclusion; ?></div>
            <div class="stat-label">Con exclusion.txt</div>
        </div>
        <?php if ($progress): ?>
        <div class="stat-box">
            <div class="stat-value val-purple"><?php echo formatBytes($progress['bytes_total_copiados'] ?? 0); ?></div>
            <div class="stat-label">Total distribuido</div>
        </div>
        <?php endif; ?>
    </div>

    <h2>Detalle por Subdominio</h2>
    <div class="table-wrap">
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Subdominio</th>
                <th>Estado</th>
                <th>exclusion.txt</th>
                <th>Verificacion</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($siteStatuses as $idx => $site): ?>
            <tr>
                <td><?php echo $idx; ?></td>
                <td style="color: #74b9ff;"><?php echo htmlspecialchars($site['name']); ?></td>
                <td>
                    <?php if ($site['excluido']): ?>
                        <span class="badge badge-skip">EXCLUIDO</span>
                    <?php elseif ($site['copiado']): ?>
                        <span class="badge badge-ok">COPIADO</span>
                    <?php elseif ($site['error']): ?>
                        <span class="badge badge-error">ERROR</span>
                    <?php else: ?>
                        <span class="badge badge-pending">PENDIENTE</span>
                    <?php endif; ?>
                </td>
                <td><?php echo $site['has_exclusion'] ? 'Si' : '--'; ?></td>
                <td>
                    <?php if ($site['items_total'] > 0): ?>
                        <?php echo $site['items_present']; ?>/<?php echo $site['items_total']; ?> elementos
                        <?php echo ($site['items_present'] === $site['items_total']) ? 'OK' : '!!'; ?>
                    <?php else: ?>
                        --
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <?php if ($progress && !empty($progress['errores'])): ?>
    <h2>Errores</h2>
    <div class="log-box">
    <?php foreach ($progress['errores'] as $site => $err): ?>
        <div style="color: #ff6b6b;"><?php echo htmlspecialchars($site); ?>: <?php echo htmlspecialchars($err); ?></div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <?php if (!empty($logLines)): ?>
    <h2>Log (ultimas 50 lineas)</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; ?>

    <div style="margin-top: 15px;">
        <a href="copiar.php" class="btn btn-primary">Ejecutar Distribucion</a>
        <a href="estado.php" class="btn btn-info">Actualizar</a>
    </div>
</div>
</body>
</html>
