<?php
/**
 * ESTADO DEL MANTENIMIENTO NICC
 * Muestra el estado actual sin modificar nada
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/config.php';

class EstadoMantenimiento {
    private $sites = [];

    public function check() {
        foreach (SEARCH_PATHS as $basePath) {
            if (!is_dir($basePath)) continue;
            $this->scanDirectory($basePath);
        }
        return $this->sites;
    }

    /**
     * Escanea SOLO el nivel inmediato de $path buscando instalaciones DokuWiki.
     * No recursa en subdirectorios para evitar duplicados.
     */
    private function scanDirectory($path) {
        if (!is_dir($path)) return;

        $items = @scandir($path);
        if (!$items) return;

        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;

            if (file_exists($fullPath . '/doku.php') && $this->isDokuWiki($fullPath)) {
                $this->sites[] = [
                    'path' => $fullPath,
                    'maintenance' => file_exists($fullPath . '/' . FLAG_FILE),
                    'backup' => file_exists($fullPath . '/doku.php' . BACKUP_SUFFIX),
                    'html' => file_exists($fullPath . '/' . MAINTENANCE_HTML),
                ];
            }
        }
    }

    private function isDokuWiki($path) {
        return file_exists($path . '/inc/init.php')
            || file_exists($path . '/conf/local.php')
            || file_exists($path . '/lib/exe/css.php');
    }
}

// === EJECUTAR ===
$estado = new EstadoMantenimiento();
$sites = $estado->check();

$activeCount = 0;
foreach ($sites as $site) {
    if ($site['maintenance']) $activeCount++;
}

// === OUTPUT ===
$isCLI = php_sapi_name() === 'cli';

if ($isCLI) {
    echo "=== ESTADO DEL MANTENIMIENTO NICC ===\n";
    echo "Fecha: " . date('Y-m-d H:i:s') . "\n";
    echo "Sitios encontrados: " . count($sites) . "\n";
    echo "Sitios en mantenimiento: $activeCount\n\n";

    foreach ($sites as $site) {
        $status = $site['maintenance'] ? '🔴 ACTIVO' : '🟢 Normal';
        echo "$status - {$site['path']}\n";
    }
} else {
    header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Estado Mantenimiento NICC</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #1a1a2e; color: #eee; padding: 20px; }
        .container { max-width: 1000px; margin: 0 auto; }
        h1 { text-align: center; color: #fff; }
        .summary { background: #16213e; padding: 20px; border-radius: 8px; margin-bottom: 20px; text-align: center; }
        .summary .count { font-size: 3em; font-weight: bold; }
        .summary.active .count { color: #ff6b6b; }
        .summary.normal .count { color: #6bcb77; }
        table { width: 100%; border-collapse: collapse; background: #16213e; border-radius: 8px; overflow: hidden; }
        th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #2a2a4a; }
        th { background: #0f3460; color: #fff; }
        tr:hover { background: #1f4068; }
        .status { padding: 4px 12px; border-radius: 20px; font-size: 0.85em; font-weight: bold; }
        .status.active { background: #ff6b6b; color: #fff; }
        .status.normal { background: #6bcb77; color: #000; }
        .check { color: #6bcb77; }
        .cross { color: #ff6b6b; }
        .actions { text-align: center; margin-top: 20px; }
        .btn { display: inline-block; padding: 12px 24px; margin: 5px; border-radius: 8px; text-decoration: none; font-weight: bold; }
        .btn-danger { background: #ff6b6b; color: #fff; }
        .btn-success { background: #6bcb77; color: #000; }
        .btn:hover { opacity: 0.9; }
        .info { background: #16213e; padding: 15px; border-radius: 8px; margin-top: 20px; }
        .info h3 { margin-top: 0; color: #4d96ff; }
        code { background: #0f3460; padding: 2px 6px; border-radius: 4px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📊 Estado del Mantenimiento NICC</h1>

        <div class="summary <?= $activeCount > 0 ? 'active' : 'normal' ?>">
            <div class="count"><?= $activeCount ?> / <?= count($sites) ?></div>
            <div><?= $activeCount > 0 ? 'Sitio(s) en Mantenimiento' : 'Todos los sitios operativos' ?></div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>Sitio</th>
                    <th>Estado</th>
                    <th>Backup</th>
                    <th>HTML</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($sites as $site): ?>
                <tr>
                    <td><?= htmlspecialchars($site['path']) ?></td>
                    <td>
                        <span class="status <?= $site['maintenance'] ? 'active' : 'normal' ?>">
                            <?= $site['maintenance'] ? '🔴 MANTENIMIENTO' : '🟢 Normal' ?>
                        </span>
                    </td>
                    <td class="<?= $site['backup'] ? 'check' : 'cross' ?>">
                        <?= $site['backup'] ? '✓' : '✗' ?>
                    </td>
                    <td class="<?= $site['html'] ? 'check' : 'cross' ?>">
                        <?= $site['html'] ? '✓' : '✗' ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <div class="actions">
            <?php if ($activeCount > 0): ?>
                <a href="desactivar.php" class="btn btn-success">🔓 Desactivar (Rápido)</a>
                <a href="desactivar.php?full=1" class="btn btn-success">🔓 Desactivar (Completo)</a>
            <?php else: ?>
                <a href="activar.php" class="btn btn-danger">🔒 Activar Mantenimiento</a>
            <?php endif; ?>
        </div>

        <div class="info">
            <h3>ℹ️ Información</h3>
            <p><strong>IPs con acceso durante mantenimiento:</strong></p>
            <?php if (empty(ADMIN_IPS)): ?>
                <p>⚠️ <strong>Ninguna IP configurada.</strong> Edite <code>config.php</code> para agregar IPs.</p>
            <?php else: ?>
                <ul>
                <?php foreach (ADMIN_IPS as $ip): ?>
                    <li><code><?= htmlspecialchars($ip) ?></code></li>
                <?php endforeach; ?>
                </ul>
            <?php endif; ?>
            <p><strong>Su IP actual:</strong> <code><?= $_SERVER['REMOTE_ADDR'] ?? 'Desconocida' ?></code></p>
        </div>
    </div>
</body>
</html>
<?php
}
