<?php
/**
 * Parche Tokens SIE-IA - copiar.php
 * ====================================
 * Genera un token JWT por cada subdominio DokuWiki llamando a la API
 * y lo escribe en conf/local.php como $conf['token_ia'].
 *
 * Procesa UN subdominio por ejecucion para evitar timeouts.
 * Auto-continua al siguiente con meta-refresh de 2 segundos.
 *
 * Uso: copiar.php          -> Inicia
 *      copiar.php?i=5      -> Procesa el subdominio #5
 *      copiar.php?reset=1  -> Reinicia el progreso
 */

require_once __DIR__ . '/config.php';

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

// ============================================================
// FUNCIONES DE ESCANEO (patron probado NICC)
// ============================================================

/**
 * 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');
}

// ============================================================
// FUNCIONES DE PROGRESO
// ============================================================

function loadProgress() {
    if (file_exists(PROGRESS_FILE)) {
        $data = json_decode(file_get_contents(PROGRESS_FILE), true);
        if (is_array($data)) return $data;
    }
    return array(
        'configurados' => array(),
        'ya_tenian'    => array(),
        'errores'      => array(),
        'inicio'       => date('Y-m-d H:i:s'),
    );
}

function saveProgress($progress) {
    file_put_contents(PROGRESS_FILE, json_encode($progress, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function writeLog($message) {
    file_put_contents(LOG_FILE, date('[Y-m-d H:i:s] ') . $message . "\n", FILE_APPEND);
}

// ============================================================
// FUNCIONES DE TOKEN
// ============================================================

/**
 * Verifica si conf/local.php ya tiene un token_ia configurado (no vacio).
 */
function verificarTokenExistente($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)) {
        if (!empty($matches[1])) {
            return $matches[1];
        }
    }
    return null;
}

/**
 * Llama a la API para generar un token JWT.
 */
function generarToken($proyecto) {
    if (!function_exists('curl_init')) {
        return array('error' => 'Extension curl no disponible', 'token' => null);
    }

    $ch = curl_init(URL_TOKEN);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('proyecto' => $proyecto, 'api_key' => ADMIN_API_KEY));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, API_TIMEOUT);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, API_CONNECT_TIMEOUT);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        return array('error' => 'CURL: ' . $curlError, 'token' => null);
    }

    if ($httpCode !== 200) {
        return array('error' => 'HTTP ' . $httpCode . ' | Enviado: proyecto=' . $proyecto . ' | Resp: ' . substr($response, 0, 200), 'token' => null);
    }

    $data = json_decode($response, true);
    if (!$data) {
        return array('error' => 'Respuesta invalida: ' . substr($response, 0, 200), 'token' => null);
    }

    $token = null;
    if (!empty($data['token'])) {
        $token = $data['token'];
    } elseif (!empty($data['access_token'])) {
        $token = $data['access_token'];
    }

    if (!$token) {
        return array('error' => 'Sin token en respuesta: ' . substr($response, 0, 200), 'token' => null);
    }

    return array('error' => null, 'token' => $token);
}

/**
 * Escribe el token en conf/local.php de forma segura.
 */
function escribirToken($sitePath, $token) {
    $localFile = $sitePath . '/conf/local.php';

    if (!file_exists($localFile)) {
        return array('error' => 'conf/local.php no existe');
    }

    // Backup
    $backupPath = $localFile . '.bak-token-ia';
    @copy($localFile, $backupPath);

    $contenido = file_get_contents($localFile);
    if ($contenido === false) {
        return array('error' => 'No se pudo leer conf/local.php');
    }

    $lineaNueva = '$conf[\'token_ia\'] = \'' . $token . '\';';

    // Buscar si ya existe token_ia
    $patron = '/\$conf\s*\[\s*[\'"]token_ia[\'"]\s*\]\s*=\s*\'[^\']*\'\s*;/';

    if (preg_match($patron, $contenido)) {
        // Reemplazar el existente
        $nuevoContenido = preg_replace($patron, $lineaNueva, $contenido, 1);
    } else {
        // Agregar al final
        $nuevoContenido = rtrim($contenido) . "\n" . $lineaNueva . "\n";
    }

    if (file_put_contents($localFile, $nuevoContenido) === false) {
        // Restaurar backup
        @copy($backupPath, $localFile);
        return array('error' => 'No se pudo escribir conf/local.php');
    }

    return array('error' => null);
}

/**
 * Procesa un sitio: genera token y lo escribe.
 * Retorna: ['status' => 'configurado'|'ya_tenia'|'error', 'message' => string]
 */
function procesarSitio($sitePath) {
    $siteName = basename($sitePath);

    // Extraer nombre limpio del subdominio
    $nombreProyecto = $siteName;
    if (strpos($nombreProyecto, '.') !== false) {
        $partes = explode('.', $nombreProyecto);
        $nombreProyecto = $partes[0];
    }

    // Generar token via API (siempre renueva, sin importar si ya tiene)
    $resultado = generarToken($nombreProyecto);

    if ($resultado['error']) {
        return array(
            'status' => 'error',
            'message' => 'API: ' . $resultado['error']
        );
    }

    // Escribir token en local.php
    $escritura = escribirToken($sitePath, $resultado['token']);

    if ($escritura['error']) {
        return array(
            'status' => 'error',
            'message' => 'Escritura: ' . $escritura['error']
        );
    }

    return array(
        'status' => 'configurado',
        'message' => 'Token generado y configurado (' . substr($resultado['token'], 0, 15) . '...)'
    );
}

// ============================================================
// LOGICA PRINCIPAL
// ============================================================

// Reset si se solicita
if (isset($_GET['reset'])) {
    if (file_exists(PROGRESS_FILE)) unlink(PROGRESS_FILE);
    if (file_exists(LOG_FILE)) unlink(LOG_FILE);
    header('Location: copiar.php');
    exit;
}

// Cargar progreso
$progress = loadProgress();

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

// Indice actual
$i = isset($_GET['i']) ? intval($_GET['i']) : 0;

// Auto-refresh (2 segundos para dar tiempo a la API)
$autoRefresh = ($i < $totalSites);

?><!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php if ($autoRefresh): ?>
    <meta http-equiv="refresh" content="2;url=copiar.php?i=<?php echo $i + 1; ?>">
    <?php endif; ?>
    <title>Parche Tokens IA - <?php echo ($i + 1); ?>/<?php echo $totalSites; ?></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: 900px; 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; }
        .progress-bar { background: #2a2a4a; border-radius: 8px; height: 30px; margin: 10px 0; overflow: hidden; }
        .progress-fill { height: 100%; border-radius: 8px; transition: width 0.3s; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 0.85em; }
        .fill-ok { background: linear-gradient(90deg, #00b894, #00cec9); }
        .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; }
        .site-current { background: #2a2a4a; border-left: 4px solid #74b9ff; padding: 12px; margin: 10px 0; border-radius: 0 8px 8px 0; }
        .site-name { color: #74b9ff; font-weight: bold; word-break: break-all; }
        .log-box { background: #0d0d1a; border: 1px solid #333; padding: 10px; border-radius: 8px; max-height: 300px; overflow-y: auto; font-family: monospace; font-size: 0.78em; line-height: 1.6; margin: 10px 0; }
        .log-ok { color: #00b894; }
        .log-skip { color: #ffd93d; }
        .log-err { color: #ff6b6b; }
        .log-info { color: #74b9ff; }
        .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-warning { background: #f39c12; color: white; }
        .btn-info { background: #6c5ce7; color: white; }
        .complete { background: #0d3320; border: 2px solid #00b894; padding: 20px; border-radius: 10px; text-align: center; margin: 20px 0; }
        .complete h2 { color: #00b894; font-size: 1.3em; }
        .warning-box { background: #3d1f00; border: 1px solid #f39c12; padding: 10px; border-radius: 8px; margin: 10px 0; font-size: 0.85em; }
        .config-info { background: #1a2a4a; border: 1px solid #74b9ff; padding: 12px; border-radius: 8px; margin: 10px 0; }
    </style>
</head>
<body>
<div class="container">
    <h1>Parche Tokens SIE-IA</h1>
    <p class="subtitle">Genera tokens JWT y los configura en conf/local.php de cada subdominio</p>

    <div class="config-info">
        <strong>API:</strong> <?php echo URL_TOKEN; ?>
        &nbsp;|&nbsp;
        <strong>Clave:</strong> $conf['token_ia']
        &nbsp;|&nbsp;
        <strong>Escaneo:</strong> <?php echo SEARCH_PATH; ?>
    </div>

<?php

// ============================================================
// PROCESAR SUBDOMINIO ACTUAL
// ============================================================

if ($i < $totalSites) {
    $sitePath = $sites[$i];
    $siteName = basename($sitePath);

    // Verificar si ya fue procesado
    $alreadyProcessed = in_array($sitePath, $progress['configurados'])
        || in_array($sitePath, $progress['ya_tenian'])
        || array_key_exists($siteName, $progress['errores']);

    if ($alreadyProcessed) {
        echo "<div class='site-current'>";
        echo "<span class='site-name'>#" . $i . " - " . htmlspecialchars($siteName) . "</span> ";
        echo "<span class='log-info'>Ya procesado, saltando...</span>";
        echo "</div>";

    } else {
        $result = procesarSitio($sitePath);

        switch ($result['status']) {
            case 'configurado':
                $progress['configurados'][] = $sitePath;
                saveProgress($progress);
                writeLog("CONFIGURADO: " . $siteName . " | " . $result['message']);

                echo "<div class='site-current'>";
                echo "<span class='site-name'>#" . $i . " - " . htmlspecialchars($siteName) . "</span> ";
                echo "<span class='log-ok'>" . htmlspecialchars($result['message']) . "</span>";
                echo "</div>";
                break;

            case 'ya_tenia':
                $progress['ya_tenian'][] = $sitePath;
                saveProgress($progress);
                writeLog("YA TENIA: " . $siteName . " | " . $result['message']);

                echo "<div class='site-current'>";
                echo "<span class='site-name'>#" . $i . " - " . htmlspecialchars($siteName) . "</span> ";
                echo "<span class='log-skip'>" . htmlspecialchars($result['message']) . "</span>";
                echo "</div>";
                break;

            case 'error':
                $progress['errores'][$siteName] = $result['message'];
                saveProgress($progress);
                writeLog("ERROR: " . $siteName . " | " . $result['message']);

                echo "<div class='site-current'>";
                echo "<span class='site-name'>#" . $i . " - " . htmlspecialchars($siteName) . "</span> ";
                echo "<span class='log-err'>" . htmlspecialchars($result['message']) . "</span>";
                echo "</div>";
                break;
        }
    }
}

// ============================================================
// ESTADISTICAS GLOBALES
// ============================================================

$configuradosCount = count($progress['configurados']);
$yaTenianCount = count($progress['ya_tenian']);
$erroresCount = count($progress['errores']);
$processedTotal = $configuradosCount + $yaTenianCount + $erroresCount;
$pctComplete = $totalSites > 0 ? round(($processedTotal / $totalSites) * 100, 1) : 0;

?>

    <h2>Progreso Global</h2>
    <div class="progress-bar">
        <div class="progress-fill fill-ok" style="width: <?php echo $pctComplete; ?>%">
            <?php echo $pctComplete; ?>% (<?php echo $processedTotal; ?>/<?php echo $totalSites; ?>)
        </div>
    </div>

    <div class="stats">
        <div class="stat-box">
            <div class="stat-value val-blue"><?php echo $totalSites; ?></div>
            <div class="stat-label">Sitios encontrados</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-green"><?php echo $configuradosCount; ?></div>
            <div class="stat-label">Tokens generados</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-purple"><?php echo $yaTenianCount; ?></div>
            <div class="stat-label">Ya tenian token</div>
        </div>
        <div class="stat-box">
            <div class="stat-value val-red"><?php echo $erroresCount; ?></div>
            <div class="stat-label">Errores</div>
        </div>
    </div>

<?php if ($i >= $totalSites && $totalSites > 0): ?>
    <div class="complete">
        <h2>PARCHE COMPLETADO</h2>
        <p>Se procesaron <?php echo $totalSites; ?> subdominios</p>
        <p>Configurados: <?php echo $configuradosCount; ?> | Ya tenian: <?php echo $yaTenianCount; ?> | Errores: <?php echo $erroresCount; ?></p>
    </div>
<?php endif; ?>

<?php if ($erroresCount > 0): ?>
    <h2>Errores (<?php echo $erroresCount; ?>)</h2>
    <div class="log-box">
    <?php foreach ($progress['errores'] as $site => $err): ?>
        <div class="log-err"><?php echo htmlspecialchars($site); ?>: <?php echo htmlspecialchars($err); ?></div>
    <?php endforeach; ?>
    </div>
<?php endif; ?>

    <div style="margin-top: 15px;">
        <a href="estado.php" class="btn btn-info">Ver Estado</a>
        <a href="copiar.php?reset=1" class="btn btn-warning" onclick="return confirm('Reiniciar progreso? Se borrara el avance.')">Reiniciar</a>
        <?php if ($i < $totalSites): ?>
        <a href="copiar.php?i=<?php echo $i; ?>" class="btn btn-primary">Reanudar</a>
        <?php endif; ?>
    </div>

    <div class="warning-box" style="margin-top: 15px;">
        <strong>Auto-refresh:</strong>
        <?php if ($autoRefresh && $i < $totalSites): ?>
            Procesando... siguiente sitio en 2 segundos (espera por API).
            <a href="estado.php" style="color: #ffd93d;">Detener y ver estado</a>
        <?php else: ?>
            Proceso finalizado o pausado.
        <?php endif; ?>
    </div>

</div>
</body>
</html>
