<?php
/**
 * Estado del Backup SIE - estado.php
 * ====================================
 * Muestra el estado del respaldo de archivos de cada subdominio.
 */

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/config.php';

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

/**
 * 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 respaldo/ y todo su contenido
        $backupReal = realpath(BACKUP_DIR);
        $fullReal   = realpath($fullPath);
        if ($backupReal && $fullReal && strpos($fullReal, $backupReal) === 0) 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';
}

/**
 * Lee info de un archivo ZIP de backup: numero de archivos y tamano del ZIP
 */
function getZipInfo($zipPath) {
    if (!file_exists($zipPath)) return [0, 0];
    $size = @filesize($zipPath) ?: 0;
    $count = 0;
    $zip = new ZipArchive();
    if ($zip->open($zipPath, ZipArchive::RDONLY) === true) {
        $count = $zip->numFiles;
        $zip->close();
    }
    return [$count, $size];
}

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

$backupExists = is_dir(BACKUP_DIR);

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

// Estado de cada sitio
$siteStatuses = [];
$totalBackupFiles = 0;
$totalBackupSize  = 0;

foreach ($sites as $sitePath) {
    $siteName = basename($sitePath);
    $zipFilePath = BACKUP_DIR . '/' . $siteName . '.zip';
    $hasBackup = file_exists($zipFilePath);

    $backupFileCount = 0;
    $backupSize = 0;
    if ($hasBackup) {
        list($backupFileCount, $backupSize) = getZipInfo($zipFilePath);
        $totalBackupFiles += $backupFileCount;
        $totalBackupSize  += $backupSize;
    }

    $detalle = ($progress && isset($progress['detalle'][$siteName])) ? $progress['detalle'][$siteName] : null;

    $status = [
        'name'            => $siteName,
        'path'            => $sitePath,
        'respaldado'      => $progress && in_array($sitePath, $progress['respaldados'] ?? []),
        'error'           => $progress && isset($progress['errores'][$siteName]),
        'error_msg'       => ($progress && isset($progress['errores'][$siteName])) ? $progress['errores'][$siteName] : '',
        'has_backup'      => $hasBackup,
        'backup_files'    => $backupFileCount,
        'backup_size'     => $backupSize,
        'archivos'        => $detalle ? $detalle['archivos'] : 0,
        'no_encontrados'  => $detalle ? $detalle['no_encontrados'] : 0,
        'errores_copia'   => $detalle ? $detalle['errores_copia'] : 0,
        'tiempo'          => $detalle ? $detalle['tiempo'] : 0,
    ];

    $siteStatuses[] = $status;
}

$respaldadosCount = $progress ? count($progress['respaldados'] ?? []) : 0;
$erroresCount     = $progress ? count($progress['errores'] ?? []) : 0;

?><!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Estado - Backup SIE</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.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; }
        .val-orange { color: #fdcb6e; }
        table { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 0.8em; }
        th { background: #2a2a4a; padding: 8px; text-align: left; color: #fdcb6e; 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-pending { background: #636e72; color: #fff; }
        .badge-error { background: #d63031; color: #fff; }
        .badge-partial { background: #f39c12; color: #000; }
        .btn { display: inline-block; padding: 8px 18px; border-radius: 6px; text-decoration: none; font-weight: bold; font-size: 0.9em; margin: 5px 3px; }
        .btn-primary { background: #0984e3; color: white; }
        .btn-info { background: #6c5ce7; color: white; }
        .btn-success { background: #00b894; color: #000; }
        .btn-warning { background: #f39c12; color: #000; }
        .btn-danger { background: #d63031; color: white; }
        .btn-dl { padding: 2px 8px; font-size: 0.72em; border-radius: 4px; background: #0984e3; color: white; text-decoration: none; }
        .btn-dl:hover { background: #74b9ff; }
        .msg-box { background: #1a3a1a; border: 1px solid #00b894; padding: 10px; border-radius: 8px; margin: 10px 0; color: #00b894; }
        .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; }
        .backup-info { background: #1a2a1a; border: 1px solid #00b894; padding: 10px; border-radius: 8px; margin: 10px 0; }
    </style>
</head>
<body>
<div class="container">
    <h1>Estado del Backup SIE</h1>
    <p class="subtitle">Verificacion de archivos respaldados de cada subdominio</p>

    <?php if (isset($_GET['msg'])): ?>
    <div class="msg-box"><?php echo htmlspecialchars($_GET['msg']); ?></div>
    <?php endif; ?>

    <div class="backup-info">
        <strong>Carpeta backup:</strong>
        <?php if ($backupExists): ?>
            respaldo/ (<?php echo number_format($totalBackupFiles); ?> archivos en ZIPs, <?php echo formatBytes($totalBackupSize); ?>)
        <?php else: ?>
            No existe aun
        <?php endif; ?>
        <?php if ($progress): ?>
        &nbsp;|&nbsp;
        <strong>Media:</strong> <?php echo (isset($progress['incluir_media']) && $progress['incluir_media']) ? 'Incluido' : 'No incluido'; ?>
        &nbsp;|&nbsp;
        <strong>Inicio:</strong> <?php echo htmlspecialchars($progress['inicio'] ?? '—'); ?>
        <?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 $respaldadosCount; ?></div>
            <div class="stat-label">Respaldados</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-red"><?php echo $erroresCount; ?></div>
            <div class="stat-label">Con errores</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-orange"><?php echo number_format($totalBackupFiles); ?></div>
            <div class="stat-label">Archivos en ZIPs</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-purple"><?php echo formatBytes($totalBackupSize); ?></div>
            <div class="stat-label">Tamano total ZIPs</div>
        </div>
        <?php if ($progress): ?>
        <div class="stat-box">
            <div class="stat-value val-yellow"><?php echo number_format($progress['archivos_no_encontrados'] ?? 0); ?></div>
            <div class="stat-label">No encontrados (saltados)</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>Archivos</th>
                <th>No encontrados</th>
                <th>Tamano</th>
                <th>Tiempo</th>
                <th>Descargar</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($siteStatuses as $idx => $site): ?>
            <tr>
                <td><?php echo $idx; ?></td>
                <td style="color: #fdcb6e;"><?php echo htmlspecialchars($site['name']); ?></td>
                <td>
                    <?php if ($site['error'] && !$site['respaldado']): ?>
                        <span class="badge badge-error">ERROR</span>
                    <?php elseif ($site['respaldado'] && $site['errores_copia'] > 0): ?>
                        <span class="badge badge-partial">PARCIAL</span>
                    <?php elseif ($site['respaldado']): ?>
                        <span class="badge badge-ok">OK</span>
                    <?php else: ?>
                        <span class="badge badge-pending">PENDIENTE</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($site['has_backup']): ?>
                        <?php echo number_format($site['backup_files']); ?>
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($site['no_encontrados'] > 0): ?>
                        <span style="color: #ffd93d;"><?php echo $site['no_encontrados']; ?></span>
                    <?php else: ?>
                        <?php echo $site['respaldado'] ? '0' : '—'; ?>
                    <?php endif; ?>
                </td>
                <td>
                    <?php echo $site['has_backup'] ? formatBytes($site['backup_size']) : '—'; ?>
                </td>
                <td>
                    <?php echo $site['tiempo'] > 0 ? $site['tiempo'] . 's' : '—'; ?>
                </td>
                <td>
                    <?php if ($site['has_backup']): ?>
                        <a href="descargar.php?file=<?php echo urlencode($site['name'] . '.zip'); ?>" class="btn-dl">ZIP</a>
                    <?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 (file_exists(LOG_FILE)): ?>
    <h2>Log</h2>
    <div class="log-box">
        <?php
        $logLines = array_slice(explode("\n", file_get_contents(LOG_FILE)), -50);
        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" onclick="return confirm('Iniciar/continuar el backup?')">Ejecutar Backup</a>
        <a href="estado.php" class="btn btn-info">Actualizar</a>
        <?php if ($totalBackupSize > 0): ?>
        <a href="descargar.php?todo=1" class="btn btn-success">Descargar TODO (<?php echo formatBytes($totalBackupSize); ?>)</a>
        <a href="descargar.php?limpiar=1" class="btn btn-danger" onclick="return confirm('Borrar TODOS los ZIPs de respaldo/ y reiniciar progreso?')">Limpiar respaldo/</a>
        <?php endif; ?>
        <a href="?logout=1" class="btn" style="background:#636e72;color:#fff;float:right;">Cerrar sesion</a>
    </div>
</div>
</body>
</html>
