<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/credenciales_wasabi_error.log');

/**
 * APLICADOR MASIVO DE CREDENCIALES WASABI S3
 * ============================================
 * Configura las credenciales del plugin wasabisync en conf/local.php
 * de TODOS los subdominios con sistema SIE.
 *
 * MODOS:
 *   ?modo=escanear   (default) - Muestra que subdominios necesitan credenciales
 *   ?modo=corregir              - Aplica credenciales a todos los pendientes
 *   ?sub=nombre                 - Solo un subdominio
 *
 * SEGURIDAD: Crea backup de conf/local.php antes de modificar
 */

// =====================================================================
//  CONFIGURACION
// =====================================================================

$basePath = '/home/systeng3/public_html';

$excluir = ['.', '..', 'cgi-bin', '.well-known', '.trash', '.htaccess',
            'respaldo', 'diagnosticos', 'tmp', 'error_log'];

// Credenciales Wasabi (se pasan por formulario POST o se leen del campo)
$wasabiConfig = [
    'enabled'        => 1,
    'wasabi_key'     => '',
    'wasabi_secret'  => '',
    'wasabi_bucket'  => 'nicc-archivos',
    'wasabi_region'  => 'us-east-1',
    'wasabi_endpoint'=> 's3.wasabisys.com',
    'url_expiry'     => 3600,
];

// =====================================================================
//  PARAMETROS
// =====================================================================

$esCLI = (php_sapi_name() === 'cli');
if (!$esCLI) header('Content-Type: text/html; charset=UTF-8');

@set_time_limit(300);
@ini_set('max_execution_time', 300);
@ini_set('memory_limit', '256M');

$modo      = $esCLI ? ($argv[1] ?? 'escanear') : ($_GET['modo'] ?? $_POST['modo'] ?? 'escanear');
$targetSub = $esCLI ? ($argv[2] ?? '')          : ($_GET['sub'] ?? $_POST['sub'] ?? '');

// Leer credenciales del POST
if (isset($_POST['wasabi_key']) && $_POST['wasabi_key'] !== '') {
    $wasabiConfig['wasabi_key']    = trim($_POST['wasabi_key']);
    $wasabiConfig['wasabi_secret'] = trim($_POST['wasabi_secret']);
    $wasabiConfig['wasabi_bucket'] = trim($_POST['wasabi_bucket'] ?: 'nicc-archivos');
    $wasabiConfig['wasabi_region'] = trim($_POST['wasabi_region'] ?: 'us-east-1');
    $wasabiConfig['wasabi_endpoint'] = trim($_POST['wasabi_endpoint'] ?: 's3.wasabisys.com');
}

if (!empty($targetSub)) {
    if (preg_match('#^https?://#i', $targetSub)) {
        $parsed = parse_url($targetSub);
        if (isset($parsed['host'])) {
            $parts = explode('.', $parsed['host']);
            $targetSub = $parts[0];
        }
    }
    $targetSub = basename(preg_replace('/[^a-zA-Z0-9._-]/', '', $targetSub));
}

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

/**
 * Crea backup de conf/local.php
 */
function crearBackup($filePath)
{
    if (!file_exists($filePath)) return false;
    $timestamp = date('Ymd_His');
    $backupPath = $filePath . '.bak_wasabi_' . $timestamp;
    return @copy($filePath, $backupPath) ? $backupPath : false;
}

/**
 * Analiza un subdominio para determinar estado de credenciales Wasabi
 */
function analizarSubdominio($subPath, $carpeta)
{
    $r = [
        'carpeta'       => $carpeta,
        'tiene_sie'     => false,
        'tiene_plugin'  => false,
        'tiene_config'  => false,
        'config_actual' => [],
        'estado'        => 'sin_sie', // sin_sie, sin_plugin, sin_config, parcial, ok
    ];

    // Verificar si es un sistema SIE/DokuWiki
    if (!file_exists($subPath . '/doku.php') && !file_exists($subPath . '/inc/init.php')) {
        return $r;
    }
    $r['tiene_sie'] = true;

    // Verificar si tiene el plugin wasabisync
    if (is_dir($subPath . '/lib/plugins/wasabisync')) {
        $r['tiene_plugin'] = true;
    }

    // Verificar conf/local.php
    $localPhp = $subPath . '/conf/local.php';
    if (!file_exists($localPhp)) {
        $r['estado'] = $r['tiene_plugin'] ? 'sin_config' : 'sin_plugin';
        return $r;
    }

    $contenido = @file_get_contents($localPhp);
    if ($contenido === false) {
        $r['estado'] = 'error_lectura';
        return $r;
    }

    // Buscar configuracion wasabisync existente
    $claves = ['enabled', 'wasabi_key', 'wasabi_secret', 'wasabi_bucket', 'wasabi_region', 'wasabi_endpoint'];
    $encontradas = 0;
    foreach ($claves as $clave) {
        if (preg_match('/\$conf\s*\[\s*[\'"]plugin[\'"]\s*\]\s*\[\s*[\'"]wasabisync[\'"]\s*\]\s*\[\s*[\'"]\s*' . preg_quote($clave, '/') . '\s*[\'"]\s*\]\s*=\s*[\'"]?([^\'";]*)[\'"]?\s*;/', $contenido, $m)) {
            $r['config_actual'][$clave] = $m[1];
            $encontradas++;
        }
    }

    if ($encontradas === 0) {
        $r['estado'] = $r['tiene_plugin'] ? 'sin_config' : 'sin_plugin';
    } elseif ($encontradas < count($claves)) {
        $r['tiene_config'] = true;
        $r['estado'] = 'parcial';
    } else {
        $r['tiene_config'] = true;
        // Verificar si las credenciales estan vacias
        if (empty($r['config_actual']['wasabi_key']) || empty($r['config_actual']['wasabi_secret'])) {
            $r['estado'] = 'parcial';
        } else {
            $r['estado'] = 'ok';
        }
    }

    return $r;
}

/**
 * Aplica credenciales Wasabi a conf/local.php de un subdominio
 */
function aplicarCredenciales($subPath, $carpeta, $wasabiConfig)
{
    $localPhp = $subPath . '/conf/local.php';

    // Crear conf/local.php si no existe
    if (!file_exists($localPhp)) {
        if (!is_dir(dirname($localPhp))) {
            @mkdir(dirname($localPhp), 0755, true);
        }
        @file_put_contents($localPhp, "<?php\n");
    }

    $contenido = @file_get_contents($localPhp);
    if ($contenido === false) {
        return ['ok' => false, 'msg' => 'No se pudo leer conf/local.php'];
    }

    // Backup
    $backup = crearBackup($localPhp);
    if (!$backup && filesize($localPhp) > 0) {
        return ['ok' => false, 'msg' => 'No se pudo crear backup'];
    }

    // Construir bloque de configuracion
    $bloque = "\n// === Wasabi S3 Sync (aplicado " . date('Y-m-d H:i:s') . ") ===\n";
    foreach ($wasabiConfig as $clave => $valor) {
        $linea = "\$conf['plugin']['wasabisync']['" . $clave . "']";
        if (is_int($valor)) {
            $linea .= " = " . $valor . ";";
        } else {
            $linea .= " = '" . addslashes($valor) . "';";
        }
        $bloque .= $linea . "\n";
    }

    // Eliminar configuracion wasabisync existente (si hay)
    $contenidoLimpio = preg_replace(
        '/\n?\/\/\s*===\s*Wasabi S3.*?(?=\n\/\/\s*===|\n\$conf\[(?!\'plugin\'\]\[\'wasabisync)|\Z)/s',
        '',
        $contenido
    );
    // Tambien eliminar lineas individuales de wasabisync
    $contenidoLimpio = preg_replace(
        '/\n?\$conf\s*\[\s*[\'"]plugin[\'"]\s*\]\s*\[\s*[\'"]wasabisync[\'"]\s*\].*?;\n?/',
        '',
        $contenidoLimpio
    );

    // Limpiar tag de cierre PHP si existe
    $contenidoLimpio = rtrim($contenidoLimpio);
    $tieneCloseTag = (substr($contenidoLimpio, -2) === '?>');
    if ($tieneCloseTag) {
        $contenidoLimpio = rtrim(substr($contenidoLimpio, 0, -2));
    }

    // Agregar bloque
    $nuevoContenido = $contenidoLimpio . $bloque;
    if ($tieneCloseTag) {
        $nuevoContenido .= "\n?>";
    }

    // Escribir
    if (@file_put_contents($localPhp, $nuevoContenido) === false) {
        // Restaurar backup
        if ($backup) @copy($backup, $localPhp);
        return ['ok' => false, 'msg' => 'No se pudo escribir conf/local.php'];
    }

    return [
        'ok' => true,
        'msg' => 'Credenciales configuradas',
        'backup' => $backup ? basename($backup) : 'sin backup (archivo nuevo)',
    ];
}

// =====================================================================
//  ESCANEAR SUBDOMINIOS
// =====================================================================

$resultados = [];

if (!empty($targetSub)) {
    $carpetas = [$targetSub];
} else {
    $carpetas = [];
    $scan = @scandir($basePath);
    if ($scan) {
        foreach ($scan as $c) {
            if (in_array($c, $excluir)) continue;
            if (!is_dir($basePath . '/' . $c)) continue;
            $carpetas[] = $c;
        }
        sort($carpetas);
    }
}

foreach ($carpetas as $carpeta) {
    $subPath = $basePath . '/' . $carpeta;
    $r = analizarSubdominio($subPath, $carpeta);
    if (!$r['tiene_sie']) continue;
    $resultados[] = $r;
}

// =====================================================================
//  MODO CORREGIR
// =====================================================================

if ($modo === 'corregir') {
    // Verificar que tenemos credenciales
    if (empty($wasabiConfig['wasabi_key']) || empty($wasabiConfig['wasabi_secret'])) {
        if (!$esCLI) {
            echo '<!DOCTYPE html><html><head><title>Error</title></head><body>';
            echo '<h1 style="color:red;">Error: No se proporcionaron credenciales</h1>';
            echo '<p>Debe enviar las credenciales via el formulario de la pagina de escaneo.</p>';
            echo '<a href="?modo=escanear">Volver al escaneo</a></body></html>';
        } else {
            echo "ERROR: Credenciales vacias\n";
        }
        exit(1);
    }

    @set_time_limit(600);

    if (!$esCLI) {
        while (ob_get_level()) ob_end_flush();
        @ini_set('output_buffering', 'off');
        @ini_set('zlib.output_compression', false);
        echo "<!DOCTYPE html><html><head><title>Aplicando credenciales Wasabi...</title>";
        echo '<style>body{font-family:monospace;background:#1e293b;color:#e2e8f0;padding:20px;} ';
        echo '.ok{color:#4ade80;} .err{color:#f87171;} .skip{color:#94a3b8;} h1{color:#38bdf8;}</style>';
        echo "</head><body><h1>Aplicando Credenciales Wasabi S3</h1><pre>\n";
    }

    $pendientes = array_filter($resultados, function($r) {
        return $r['estado'] !== 'ok';
    });
    $totalPendientes = count($pendientes);

    echo "Fecha: " . date('Y-m-d H:i:s') . "\n";
    echo "Bucket: " . $wasabiConfig['wasabi_bucket'] . "\n";
    echo "Region: " . $wasabiConfig['wasabi_region'] . "\n";
    echo "Total sistemas SIE: " . count($resultados) . "\n";
    echo "Pendientes: {$totalPendientes}\n";
    echo "========================================\n\n";
    if (!$esCLI) flush();

    $exitos = 0;
    $errores = 0;
    $i = 0;

    foreach ($pendientes as $r) {
        $i++;
        $subPath = $basePath . '/' . $r['carpeta'];
        echo "[{$i}/{$totalPendientes}] {$r['carpeta']} ... ";
        if (!$esCLI) flush();

        if (!$r['tiene_plugin']) {
            echo "<span class='skip'>OMITIDO (plugin wasabisync no instalado)</span>\n";
            if (!$esCLI) flush();
            continue;
        }

        try {
            $fix = aplicarCredenciales($subPath, $r['carpeta'], $wasabiConfig);
            if ($fix['ok']) {
                echo "<span class='ok'>OK</span> - {$fix['msg']} (backup: {$fix['backup']})\n";
                $exitos++;
            } else {
                echo "<span class='err'>ERROR</span> - {$fix['msg']}\n";
                $errores++;
            }
        } catch (\Throwable $e) {
            echo "<span class='err'>EXCEPTION</span> - " . $e->getMessage() . "\n";
            $errores++;
        }
        if (!$esCLI) flush();
    }

    echo "\n========================================\n";
    echo "COMPLETADO: {$exitos} exitosos, {$errores} errores\n";
    if (!$esCLI) echo "</pre></body></html>";
    exit(0);
}

// =====================================================================
//  MODO ESCANEAR (HTML)
// =====================================================================

// Estadisticas
$totalSIE = count($resultados);
$totalOk = count(array_filter($resultados, fn($r) => $r['estado'] === 'ok'));
$totalSinPlugin = count(array_filter($resultados, fn($r) => !$r['tiene_plugin'] && $r['tiene_sie']));
$totalSinConfig = count(array_filter($resultados, fn($r) => in_array($r['estado'], ['sin_config', 'parcial'])));

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Credenciales Wasabi S3 - Aplicador Masivo</title>
<style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f1f5f9; color: #334155; padding: 20px; }
    .container { max-width: 1100px; margin: 0 auto; }
    h1 { color: #0f172a; margin-bottom: 8px; font-size: 1.6em; }
    .subtitle { color: #64748b; margin-bottom: 20px; }

    .summary { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 24px; }
    .card { background: #fff; border-radius: 10px; padding: 16px; text-align: center; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
    .card .num { font-size: 2em; font-weight: 700; }
    .card .label { color: #64748b; font-size: 0.85em; margin-top: 4px; }
    .blue { color: #3b82f6; } .green { color: #10b981; } .red { color: #ef4444; } .amber { color: #f59e0b; }

    .section { background: #fff; border-radius: 10px; padding: 20px; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
    .section h2 { margin-bottom: 12px; font-size: 1.15em; }

    .form-group { margin-bottom: 12px; }
    .form-group label { display: block; font-weight: 600; margin-bottom: 4px; font-size: 0.9em; }
    .form-group input { width: 100%; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.95em; font-family: monospace; }
    .form-group input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,0.15); }
    .form-row { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; }
    .form-note { font-size: 0.8em; color: #64748b; margin-top: 2px; }

    .btn { display: inline-block; padding: 10px 20px; border-radius: 8px; font-weight: 600; font-size: 0.9em;
           text-decoration: none; cursor: pointer; border: none; transition: all 0.2s; }
    .btn-blue { background: #3b82f6; color: #fff; } .btn-blue:hover { background: #2563eb; }
    .btn-green { background: #10b981; color: #fff; } .btn-green:hover { background: #059669; }
    .btn-red { background: #ef4444; color: #fff; } .btn-red:hover { background: #dc2626; }
    .btn:disabled { opacity: 0.5; cursor: not-allowed; }

    table { width: 100%; border-collapse: collapse; font-size: 0.88em; }
    th { text-align: left; padding: 8px; border-bottom: 2px solid #e2e8f0; font-weight: 600; color: #475569; }
    td { padding: 8px; border-bottom: 1px solid #f1f5f9; }
    tr:hover { background: #f8fafc; }
    .badge { display: inline-block; padding: 2px 8px; border-radius: 9999px; font-size: 0.8em; font-weight: 600; }
    .badge-ok { background: #d1fae5; color: #065f46; }
    .badge-warn { background: #fef3c7; color: #92400e; }
    .badge-err { background: #fee2e2; color: #991b1b; }
    .badge-gray { background: #f1f5f9; color: #64748b; }
</style>
</head>
<body>
<div class="container">
    <h1>&#9729; Credenciales Wasabi S3 - Aplicador Masivo</h1>
    <p class="subtitle">Configura el plugin wasabisync en todos los subdominios SIE</p>

    <!-- Resumen -->
    <div class="summary">
        <div class="card"><div class="num blue"><?= $totalSIE ?></div><div class="label">Sistemas SIE</div></div>
        <div class="card"><div class="num green"><?= $totalOk ?></div><div class="label">Configurados OK</div></div>
        <div class="card"><div class="num amber"><?= $totalSinConfig ?></div><div class="label">Sin credenciales</div></div>
        <div class="card"><div class="num red"><?= $totalSinPlugin ?></div><div class="label">Sin plugin instalado</div></div>
    </div>

    <!-- Formulario de credenciales -->
    <div class="section">
        <h2>&#128273; Credenciales Wasabi</h2>
        <p style="margin-bottom:12px;color:#64748b;font-size:0.9em;">Ingrese las credenciales que se aplicaran a todos los subdominios. Estas se guardan en <code>conf/local.php</code> de cada wiki.</p>

        <form method="POST" action="" id="formWasabi">
            <input type="hidden" name="modo" value="corregir" />
            <?php if ($targetSub): ?>
                <input type="hidden" name="sub" value="<?= htmlspecialchars($targetSub) ?>" />
            <?php endif; ?>

            <div class="form-row">
                <div class="form-group">
                    <label>Access Key *</label>
                    <input type="text" name="wasabi_key" required placeholder="Ej: 6BS5CH0SFZO5A3IX9RIS"
                           value="<?= htmlspecialchars($wasabiConfig['wasabi_key']) ?>" />
                </div>
                <div class="form-group">
                    <label>Secret Key *</label>
                    <input type="password" name="wasabi_secret" required placeholder="Secret key de Wasabi"
                           value="<?= htmlspecialchars($wasabiConfig['wasabi_secret']) ?>" />
                </div>
                <div class="form-group">
                    <label>Bucket</label>
                    <input type="text" name="wasabi_bucket" value="<?= htmlspecialchars($wasabiConfig['wasabi_bucket']) ?>" />
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Region</label>
                    <input type="text" name="wasabi_region" value="<?= htmlspecialchars($wasabiConfig['wasabi_region']) ?>" />
                </div>
                <div class="form-group">
                    <label>Endpoint</label>
                    <input type="text" name="wasabi_endpoint" value="<?= htmlspecialchars($wasabiConfig['wasabi_endpoint']) ?>" />
                </div>
                <div class="form-group">
                    <label>&nbsp;</label>
                    <?php if ($totalSinConfig > 0 || $totalOk < $totalSIE): ?>
                        <button type="submit" class="btn btn-green"
                                onclick="return confirm('Aplicar credenciales a <?= $totalSinConfig ?> subdominios pendientes?')">
                            &#9889; Aplicar a pendientes (<?= $totalSinConfig ?>)
                        </button>
                    <?php else: ?>
                        <button type="submit" class="btn btn-blue"
                                onclick="return confirm('Reescribir credenciales en TODOS los subdominios?')">
                            &#128260; Reescribir en todos
                        </button>
                    <?php endif; ?>
                </div>
            </div>
            <p class="form-note">Las credenciales se envian por POST (no quedan en la URL). Use HTTPS.</p>
        </form>
    </div>

    <!-- Tabla de resultados -->
    <div class="section">
        <h2>Estado de subdominios (<?= $totalSIE ?> sistemas SIE)</h2>
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Subdominio</th>
                    <th>Plugin</th>
                    <th>Credenciales</th>
                    <th>Estado</th>
                    <th>Detalles</th>
                </tr>
            </thead>
            <tbody>
            <?php $n = 0; foreach ($resultados as $r): $n++; ?>
                <tr>
                    <td><?= $n ?></td>
                    <td><strong><?= htmlspecialchars($r['carpeta']) ?></strong></td>
                    <td>
                        <?php if ($r['tiene_plugin']): ?>
                            <span class="badge badge-ok">Instalado</span>
                        <?php else: ?>
                            <span class="badge badge-err">No instalado</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($r['estado'] === 'ok'): ?>
                            <span class="badge badge-ok">Configurado</span>
                        <?php elseif ($r['estado'] === 'parcial'): ?>
                            <span class="badge badge-warn">Parcial</span>
                        <?php elseif ($r['estado'] === 'sin_config'): ?>
                            <span class="badge badge-err">Sin configurar</span>
                        <?php else: ?>
                            <span class="badge badge-gray">N/A</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php
                        $estados = [
                            'ok' => ['OK', 'green'],
                            'parcial' => ['Incompleto', 'amber'],
                            'sin_config' => ['Pendiente', 'red'],
                            'sin_plugin' => ['Sin plugin', 'gray'],
                            'error_lectura' => ['Error', 'red'],
                        ];
                        $e = $estados[$r['estado']] ?? ['?', 'gray'];
                        echo "<span style='color:var(--{$e[1]}, #64748b);font-weight:600;'>{$e[0]}</span>";
                        ?>
                    </td>
                    <td style="font-size:0.85em;color:#64748b;">
                        <?php if (!empty($r['config_actual']['wasabi_key'])): ?>
                            Key: <?= substr($r['config_actual']['wasabi_key'], 0, 6) ?>...
                        <?php elseif ($r['estado'] === 'sin_plugin'): ?>
                            Instale el plugin primero
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div style="text-align:center;padding:20px;color:#94a3b8;font-size:0.8em;">
        SIE Deployer - Credenciales Wasabi S3 | <?= date('Y-m-d H:i:s') ?>
    </div>
</div>
</body>
</html>
