<?php
/**
 * Estado del Parche Tokens SIE-IA - estado.php
 * ===============================================
 * Muestra el estado de los tokens IA en cada subdominio.
 */

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 = array();
    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;
        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');
}

/**
 * Lee el valor actual de token_ia en conf/local.php
 */
function getTokenActual($sitePath) {
    $localFile = $sitePath . '/conf/local.php';
    if (!file_exists($localFile)) return null;

    $content = file_get_contents($localFile);
    if ($content === false) return null;

    $patron = '/\$conf\s*\[\s*[\'"]token_ia[\'"]\s*\]\s*=\s*\'([^\']*)\'/';
    if (preg_match($patron, $content, $matches)) {
        return $matches[1];
    }
    return null;
}

// Cargar 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 = array();
foreach ($sites as $sitePath) {
    $siteName = basename($sitePath);
    $tokenActual = getTokenActual($sitePath);
    $tieneToken = (!empty($tokenActual));

    $status = array(
        'name'         => $siteName,
        'path'         => $sitePath,
        'configurado'  => $progress && in_array($sitePath, isset($progress['configurados']) ? $progress['configurados'] : array()),
        'ya_tenia'     => $progress && in_array($sitePath, isset($progress['ya_tenian']) ? $progress['ya_tenian'] : array()),
        'error'        => $progress && isset($progress['errores'][$siteName]),
        'error_msg'    => ($progress && isset($progress['errores'][$siteName])) ? $progress['errores'][$siteName] : '',
        'tiene_token'  => $tieneToken,
        'token_preview' => $tieneToken ? substr($tokenActual, 0, 20) . '...' : '',
    );
    $siteStatuses[] = $status;
}

$configuradosCount = $progress ? count(isset($progress['configurados']) ? $progress['configurados'] : array()) : 0;
$yaTenianCount = $progress ? count(isset($progress['ya_tenian']) ? $progress['ya_tenian'] : array()) : 0;
$erroresCount = $progress ? count(isset($progress['errores']) ? $progress['errores'] : array()) : 0;
$conTokenCount = count(array_filter($siteStatuses, function($s) { return $s['tiene_token']; }));
$sinTokenCount = $totalSites - $conTokenCount;

?><!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Estado - Parche Tokens SIE-IA</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; }
        .btn-primary { background: #0984e3; color: white; }
        .btn-info { background: #6c5ce7; color: white; }
        .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; }
        .config-info { background: #1a2a4a; border: 1px solid #74b9ff; padding: 10px; border-radius: 8px; margin: 10px 0; }
    </style>
</head>
<body>
<div class="container">
    <h1>Estado - Parche Tokens SIE-IA</h1>
    <p class="subtitle">Verificacion de $conf['token_ia'] en cada subdominio</p>

    <div class="config-info">
        <strong>Sitios con token:</strong> <?php echo $conTokenCount; ?>/<?php echo $totalSites; ?>
        &nbsp;|&nbsp;
        <strong>Sin token:</strong> <?php echo $sinTokenCount; ?>
        &nbsp;|&nbsp;
        <strong>API:</strong> <?php echo URL_TOKEN; ?>
    </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 $conTokenCount; ?></div>
            <div class="stat-label">Con token</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-yellow"><?php echo $sinTokenCount; ?></div>
            <div class="stat-label">Sin token</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-green"><?php echo $configuradosCount; ?></div>
            <div class="stat-label">Configurados (parche)</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-purple"><?php echo $yaTenianCount; ?></div>
            <div class="stat-label">Ya tenian</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-red"><?php echo $erroresCount; ?></div>
            <div class="stat-label">Errores</div>
        </div>
    </div>

    <h2>Detalle por Subdominio</h2>
    <div class="table-wrap">
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Subdominio</th>
                <th>Estado</th>
                <th>Token</th>
                <th>Preview</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['configurado']): ?>
                        <span class="badge badge-ok">CONFIGURADO</span>
                    <?php elseif ($site['ya_tenia']): ?>
                        <span class="badge badge-skip">YA TENIA</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 if ($site['tiene_token']): ?>
                        <span style="color: #00b894;">Si</span>
                    <?php else: ?>
                        <span style="color: #ff6b6b;">No</span>
                    <?php endif; ?>
                </td>
                <td style="font-family: monospace; font-size: 0.8em; color: #888;">
                    <?php echo htmlspecialchars($site['token_preview']); ?>
                </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 parche de tokens?')">Ejecutar Parche</a>
        <a href="estado.php" class="btn btn-info">Actualizar</a>
    </div>
</div>
</body>
</html>
