<?php
/**
 * CAMBIO MASIVO DE CONTRASENA - USUARIO sie2
 * ============================================
 * Cambia la contrasena del usuario "sie2" en todos los subdominios SIE
 * o en uno especifico. Modifica conf/users.auth.php con backup automatico.
 *
 * FORMATO users.auth.php:
 *   login:passwordhash:Real Name:email:groups
 *   sie2:$2y$10$xxxxx:Usuario SIE2:email@dom.com:sie,user
 *
 * MODOS:
 *   ?modo=escanear           (default) - Solo detectar donde existe sie2
 *   ?modo=corregir&pw=NUEVA  - Cambiar contrasena en TODOS los que tienen sie2
 *   ?sub=nombre              - Limitar a un solo subdominio
 *
 * SEGURIDAD:
 *   Crea backup users.auth.php.bak_pw_* antes de modificar.
 *   Solo modifica la linea del usuario sie2, nada mas.
 */

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

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

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

$targetUser = 'sie2';  // Usuario fijo a modificar

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

$esCLI = (php_sapi_name() === 'cli');

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

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

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
// =====================================================================

/**
 * Genera hash de contrasena compatible con DokuWiki (bcrypt)
 * Replica auth_cryptPassword() de DokuWiki usando bcrypt
 */
function hashPassword($clear)
{
    return password_hash($clear, PASSWORD_BCRYPT);
}

/**
 * Analiza users.auth.php de un subdominio buscando el usuario sie2
 */
function analizarUsuario($subPath, $carpeta, $targetUser)
{
    $r = [
        'carpeta'     => $carpeta,
        'tiene_doku'  => false,
        'tiene_users' => false,
        'tiene_sie2'  => false,
        'linea_sie2'  => '',
        'grupos_sie2' => '',
        'email_sie2'  => '',
        'nombre_sie2' => '',
        'total_users' => 0,
        'estado'      => 'NO_DOKU',
    ];

    if (!file_exists($subPath . '/doku.php')) return $r;
    $r['tiene_doku'] = true;

    $usersFile = $subPath . '/conf/users.auth.php';
    if (!file_exists($usersFile)) {
        $r['estado'] = 'SIN_USERS';
        return $r;
    }

    $content = @file_get_contents($usersFile);
    if ($content === false) {
        $r['estado'] = 'ERROR_LEER';
        return $r;
    }

    $r['tiene_users'] = true;

    $lineas = explode("\n", $content);
    foreach ($lineas as $linea) {
        $linea = trim($linea);
        if ($linea === '' || $linea[0] === '#') continue;
        $r['total_users']++;

        $parts = explode(':', $linea);
        if (count($parts) >= 5 && $parts[0] === $targetUser) {
            $r['tiene_sie2']  = true;
            $r['linea_sie2']  = $linea;
            $r['nombre_sie2'] = urldecode($parts[2]);
            $r['email_sie2']  = $parts[3];
            $r['grupos_sie2'] = $parts[4];
        }
    }

    $r['estado'] = $r['tiene_sie2'] ? 'ENCONTRADO' : 'NO_EXISTE';
    return $r;
}

/**
 * Cambia la contrasena del usuario sie2 en users.auth.php
 * Crea backup automatico antes de modificar.
 */
function cambiarPassword($subPath, $carpeta, $targetUser, $newHash)
{
    $usersFile = $subPath . '/conf/users.auth.php';
    $confDir   = $subPath . '/conf';

    if (!file_exists($usersFile)) {
        return ['ok' => false, 'msg' => 'No existe users.auth.php'];
    }

    $content = @file_get_contents($usersFile);
    if ($content === false) {
        return ['ok' => false, 'msg' => 'No se puede leer users.auth.php'];
    }

    // Crear backup con timestamp
    $timestamp = date('Ymd_His');
    $backupName = "users.auth.php.bak_pw_{$timestamp}";
    $backupPath = $confDir . '/' . $backupName;
    if (!@copy($usersFile, $backupPath)) {
        return ['ok' => false, 'msg' => 'No se pudo crear backup'];
    }

    // Reemplazar la linea del usuario
    $lineas = explode("\n", $content);
    $encontrado = false;
    $nuevasLineas = [];

    foreach ($lineas as $linea) {
        $trimmed = trim($linea);
        if ($trimmed !== '' && $trimmed[0] !== '#') {
            $parts = explode(':', $trimmed);
            if (count($parts) >= 5 && $parts[0] === $targetUser) {
                // Reemplazar solo el hash (campo 1)
                $parts[1] = $newHash;
                $nuevasLineas[] = implode(':', $parts);
                $encontrado = true;
                continue;
            }
        }
        $nuevasLineas[] = $linea;
    }

    if (!$encontrado) {
        @unlink($backupPath);
        return ['ok' => false, 'msg' => 'Usuario sie2 no encontrado en el archivo'];
    }

    $nuevoContent = implode("\n", $nuevasLineas);
    if (@file_put_contents($usersFile, $nuevoContent) === false) {
        @copy($backupPath, $usersFile); // Restaurar si falla
        return ['ok' => false, 'msg' => 'No se pudo escribir users.auth.php'];
    }

    return [
        'ok'     => true,
        'msg'    => 'Contrasena actualizada. Backup: ' . $backupName,
        'backup' => $backupName,
    ];
}

// =====================================================================
//  EJECUCION
// =====================================================================

$tiempoInicio = microtime(true);
$resultados   = [];
$correcciones = [];
$errorMsg     = '';

// Validar contrasena nueva en modo corregir
if ($modo === 'corregir') {
    if (empty($newPw)) {
        $errorMsg = 'Debe ingresar la contrasena nueva.';
        $modo = 'escanear'; // Forzar escaneo
    } elseif (strlen($newPw) < 6) {
        $errorMsg = 'La contrasena debe tener al menos 6 caracteres.';
        $modo = 'escanear';
    }
}

// Generar hash una sola vez (mismo hash para todos)
$newHash = '';
if ($modo === 'corregir' && !empty($newPw)) {
    $newHash = hashPassword($newPw);
    if ($newHash === false || $newHash === null) {
        $errorMsg = 'Error al generar hash bcrypt. Verificar que PHP tenga soporte para bcrypt.';
        $modo = 'escanear';
        $newHash = '';
    }
}

// Obtener lista de carpetas
if (!empty($targetSub)) {
    $carpetas = [$targetSub];
} else {
    $carpetas = [];
    $scan = @scandir($basePath);
    if (!$scan) {
        echo $esCLI ? "ERROR: No se puede leer {$basePath}\n" : "<p style='color:red'>ERROR: No se puede leer {$basePath}</p>";
        exit(1);
    }
    foreach ($scan as $c) {
        if (in_array($c, $excluir)) continue;
        if (!is_dir($basePath . '/' . $c)) continue;
        $carpetas[] = $c;
    }
    sort($carpetas);
}

// Escanear
foreach ($carpetas as $carpeta) {
    $subPath = $basePath . '/' . $carpeta;
    $r = analizarUsuario($subPath, $carpeta, $targetUser);
    if (!$r['tiene_doku']) continue;
    $resultados[] = $r;

    // Corregir si esta en modo corregir y tiene el usuario
    if ($modo === 'corregir' && $r['tiene_sie2'] && !empty($newHash)) {
        $fix = cambiarPassword($subPath, $carpeta, $targetUser, $newHash);
        $correcciones[$carpeta] = $fix;
    }
}

$tiempoFin = round(microtime(true) - $tiempoInicio, 2);

// Estadisticas
$totalEncontrado = count(array_filter($resultados, fn($r) => $r['estado'] === 'ENCONTRADO'));
$totalNoExiste   = count(array_filter($resultados, fn($r) => $r['estado'] === 'NO_EXISTE'));
$totalSinUsers   = count(array_filter($resultados, fn($r) => $r['estado'] === 'SIN_USERS'));
$totalError      = count(array_filter($resultados, fn($r) => $r['estado'] === 'ERROR_LEER'));

// =====================================================================
//  SALIDA CLI
// =====================================================================

if ($esCLI) {
    echo "================================================================\n";
    echo " CAMBIO MASIVO DE CONTRASENA - USUARIO {$targetUser}\n";
    echo " " . date('Y-m-d H:i:s') . " | Modo: {$modo} | Tiempo: {$tiempoFin}s\n";
    echo "================================================================\n\n";

    echo "Total: " . count($resultados) . " | Con {$targetUser}: {$totalEncontrado} | Sin {$targetUser}: {$totalNoExiste} | Sin users.auth: {$totalSinUsers}\n\n";

    if ($modo === 'corregir' && !empty($correcciones)) {
        echo "=== RESULTADOS ===\n";
        foreach ($correcciones as $carpeta => $fix) {
            echo sprintf("  %-30s %s\n", $carpeta, $fix['ok'] ? 'OK: ' . $fix['msg'] : 'ERROR: ' . $fix['msg']);
        }
    } else {
        echo "=== SISTEMAS CON {$targetUser} ===\n";
        foreach ($resultados as $r) {
            if ($r['tiene_sie2']) {
                echo sprintf("  %-30s [%s] grupos: %s\n", $r['carpeta'], $r['estado'], $r['grupos_sie2']);
            }
        }
    }
    exit(0);
}

// =====================================================================
//  SALIDA HTML
// =====================================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Cambio Contrasena sie2 - SIE</title>
<style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f1f5f9; color: #1e293b; padding: 20px; }
    .container { max-width: 1400px; margin: 0 auto; }
    h1 { font-size: 1.5em; color: #0f172a; margin-bottom: 4px; }
    .subtitle { color: #64748b; font-size: 0.88em; margin-bottom: 20px; }

    .summary { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 20px; }
    .card { background: #fff; border-radius: 10px; padding: 14px; text-align: center; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
    .card .num { font-size: 1.8em; font-weight: 700; }
    .card .label { font-size: 0.8em; color: #64748b; }
    .green { color: #16a34a; } .red { color: #dc2626; } .yellow { color: #d97706; } .blue { color: #2563eb; }

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

    .explain { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 10px; padding: 16px; margin-bottom: 20px; }
    .explain h2 { color: #1e40af; margin-bottom: 8px; font-size: 1em; }
    .explain p { font-size: 0.86em; color: #334155; margin-bottom: 4px; }
    .explain code { background: #dbeafe; color: #1e40af; padding: 1px 4px; border-radius: 3px; font-size: 0.9em; }

    .form-box { background: #fff; border: 2px solid #2563eb; border-radius: 12px; padding: 20px; margin-bottom: 20px; }
    .form-box h2 { color: #1e40af; margin-bottom: 14px; font-size: 1.1em; }
    .form-row { display: flex; gap: 12px; align-items: end; flex-wrap: wrap; }
    .form-group { flex: 1; min-width: 200px; }
    .form-group label { display: block; font-size: 0.85em; font-weight: 600; color: #475569; margin-bottom: 4px; }
    .form-group input { width: 100%; padding: 10px 14px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 1em; }
    .form-group input:focus { outline: none; border-color: #2563eb; box-shadow: 0 0 0 3px rgba(37,99,235,0.15); }
    .form-group select { width: 100%; padding: 10px 14px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 1em; }

    .actions { display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; align-items: center; }
    .btn { padding: 10px 20px; border: none; border-radius: 8px; font-size: 0.9em; cursor: pointer; text-decoration: none; display: inline-block; font-weight: 600; }
    .btn-blue { background: #2563eb; color: #fff; } .btn-blue:hover { background: #1d4ed8; }
    .btn-red { background: #dc2626; color: #fff; } .btn-red:hover { background: #b91c1c; }
    .btn-green { background: #16a34a; color: #fff; } .btn-gray { background: #64748b; color: #fff; }

    .result-box { border-radius: 10px; padding: 16px; margin-bottom: 20px; }
    .result-ok { background: #f0fdf4; border: 1px solid #86efac; }
    .result-ok strong { color: #166534; }
    .result-err { background: #fef2f2; border: 1px solid #fecaca; }
    .result-err strong { color: #991b1b; }

    .error-msg { background: #fef2f2; border: 1px solid #fecaca; border-radius: 10px; padding: 14px; margin-bottom: 16px; color: #991b1b; font-weight: 600; }

    .pw-strength { font-size: 0.8em; margin-top: 4px; height: 18px; }

    table { width: 100%; border-collapse: collapse; font-size: 0.83em; }
    th { text-align: left; padding: 8px 6px; border-bottom: 2px solid #e2e8f0; color: #475569; font-size: 0.85em; }
    td { padding: 7px 6px; border-bottom: 1px solid #f1f5f9; }
    tr:hover { background: #f8fafc; }
    tr.row-found { background: #eff6ff; }
    tr.row-found:hover { background: #dbeafe; }

    .badge { display: inline-block; padding: 2px 7px; border-radius: 4px; font-size: 0.76em; font-weight: 600; }
    .badge-ok { background: #dcfce7; color: #166534; }
    .badge-found { background: #dbeafe; color: #1e40af; }
    .badge-no { background: #f1f5f9; color: #64748b; }
    .badge-err { background: #fee2e2; color: #991b1b; }
    .badge-fix { background: #dbeafe; color: #1e40af; }
    .badge-warn { background: #fef3c7; color: #92400e; }

    .filter-bar { margin-bottom: 12px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
    .filter-bar input, .filter-bar select { padding: 6px 10px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.86em; }
    .filter-bar input { width: 200px; }

    .toggle-pw { cursor: pointer; padding: 2px 8px; background: #e2e8f0; border: none; border-radius: 4px; font-size: 0.8em; }
</style>
</head>
<body>
<div class="container">

<h1>&#128273; Cambio Masivo de Contrasena — Usuario <code><?= htmlspecialchars($targetUser) ?></code></h1>
<p class="subtitle">
    <?= date('Y-m-d H:i:s') ?> |
    Modo: <strong><?= $modo === 'corregir' ? '&#9888;&#65039; APLICAR CAMBIO' : '&#128269; ESCANEAR' ?></strong> |
    Tiempo: <?= $tiempoFin ?>s |
    Sistemas: <?= count($resultados) ?>
    <?php if (!empty($targetSub)): ?> | Subdominio: <strong><?= htmlspecialchars($targetSub) ?></strong><?php endif; ?>
</p>

<div class="explain">
    <h2>&#128273; Que hace este script</h2>
    <p><strong>Funcion:</strong> Busca el usuario <code><?= htmlspecialchars($targetUser) ?></code> en <code>conf/users.auth.php</code> de cada subdominio y cambia su contrasena.</p>
    <p><strong>Escanear:</strong> Muestra donde existe el usuario y sus datos actuales (grupos, email).</p>
    <p><strong>Aplicar:</strong> Genera hash bcrypt de la contrasena nueva y actualiza la linea del usuario. Crea backup automatico.</p>
    <p><strong>Seguridad:</strong> Solo modifica la linea del usuario <code><?= htmlspecialchars($targetUser) ?></code>. No toca ningun otro usuario.</p>
</div>

<?php if ($errorMsg): ?>
<div class="error-msg">&#9888;&#65039; <?= htmlspecialchars($errorMsg) ?></div>
<?php endif; ?>

<!-- Resumen -->
<div class="summary">
    <div class="card"><div class="num blue"><?= count($resultados) ?></div><div class="label">Total DokuWiki</div></div>
    <div class="card"><div class="num <?= $totalEncontrado > 0 ? 'blue' : 'yellow' ?>"><?= $totalEncontrado ?></div><div class="label">Con <?= htmlspecialchars($targetUser) ?></div></div>
    <div class="card"><div class="num" style="color:#64748b;"><?= $totalNoExiste ?></div><div class="label">Sin <?= htmlspecialchars($targetUser) ?></div></div>
    <div class="card"><div class="num <?= $totalSinUsers > 0 ? 'red' : 'green' ?>"><?= $totalSinUsers ?></div><div class="label">Sin users.auth</div></div>
</div>

<!-- Formulario de cambio de contrasena -->
<div class="form-box">
    <h2>&#128273; Cambiar contrasena de <code><?= htmlspecialchars($targetUser) ?></code></h2>
    <form method="post" action="?" id="formPw" onsubmit="return validarFormulario()">
        <input type="hidden" name="modo" value="corregir" />
        <div class="form-row">
            <div class="form-group">
                <label for="pw">Nueva contrasena</label>
                <div style="position:relative;">
                    <input type="password" name="pw" id="pw" placeholder="Minimo 6 caracteres" required minlength="6" autocomplete="new-password" />
                    <button type="button" class="toggle-pw" onclick="togglePw()" style="position:absolute;right:8px;top:50%;transform:translateY(-50%);">&#128065;</button>
                </div>
                <div class="pw-strength" id="pwStrength"></div>
            </div>
            <div class="form-group" style="max-width:260px;">
                <label for="subSelect">Aplicar a</label>
                <select name="sub" id="subSelect">
                    <option value="">TODOS los sistemas (<?= $totalEncontrado ?>)</option>
                    <?php foreach ($resultados as $r): ?>
                        <?php if ($r['tiene_sie2']): ?>
                        <option value="<?= htmlspecialchars($r['carpeta']) ?>" <?= $targetSub === $r['carpeta'] ? 'selected' : '' ?>><?= htmlspecialchars($r['carpeta']) ?></option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="display:flex;gap:8px;">
                <button type="submit" class="btn btn-red" id="btnAplicar">
                    &#128273; Aplicar cambio
                </button>
                <a href="?<?= !empty($targetSub) ? 'sub=' . urlencode($targetSub) : '' ?>" class="btn btn-blue">&#128269; Escanear</a>
            </div>
        </div>
    </form>
</div>

<?php if ($modo === 'corregir' && !empty($correcciones)): ?>
<!-- Resultado de correcciones -->
<?php
$fixOK = count(array_filter($correcciones, fn($f) => $f['ok']));
$fixErr = count(array_filter($correcciones, fn($f) => !$f['ok']));
?>
<div class="result-box <?= $fixErr > 0 ? 'result-err' : 'result-ok' ?>">
    <strong>&#9989; Resultado: <?= $fixOK ?> actualizado(s), <?= $fixErr ?> error(es)</strong>
    <table style="margin-top:10px;">
        <thead><tr><th>Subdominio</th><th>Resultado</th><th>Detalle</th></tr></thead>
        <tbody>
        <?php foreach ($correcciones as $carpeta => $fix): ?>
            <tr>
                <td><strong><?= htmlspecialchars($carpeta) ?></strong></td>
                <td><span class="badge <?= $fix['ok'] ? 'badge-ok' : 'badge-err' ?>"><?= $fix['ok'] ? 'ACTUALIZADO' : 'ERROR' ?></span></td>
                <td><?= htmlspecialchars($fix['msg']) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<!-- Tabla completa -->
<div class="section">
    <h2>&#128203; Todos los sistemas (<?= count($resultados) ?>)</h2>
    <div class="filter-bar">
        <input type="text" id="filtro" placeholder="Buscar..." oninput="filtrar()">
        <select id="filtroEstado" onchange="filtrar()">
            <option value="">Todos</option>
            <option value="found">Con <?= htmlspecialchars($targetUser) ?></option>
            <option value="no">Sin <?= htmlspecialchars($targetUser) ?></option>
        </select>
    </div>
    <table id="tabla">
        <thead>
            <tr>
                <th>#</th>
                <th>Subdominio</th>
                <th>Estado</th>
                <th>Nombre</th>
                <th>Email</th>
                <th>Grupos</th>
                <th>Total usuarios</th>
                <?php if ($modo === 'corregir'): ?><th>Resultado</th><?php endif; ?>
            </tr>
        </thead>
        <tbody>
        <?php $i = 0; foreach ($resultados as $r): $i++; ?>
            <?php
                $rowClass = $r['tiene_sie2'] ? 'row-found' : '';
                $fix = $correcciones[$r['carpeta']] ?? null;
            ?>
            <tr class="<?= $rowClass ?>" data-name="<?= htmlspecialchars(strtolower($r['carpeta'])) ?>" data-estado="<?= $r['tiene_sie2'] ? 'found' : 'no' ?>">
                <td><?= $i ?></td>
                <td>
                    <strong><?= htmlspecialchars($r['carpeta']) ?></strong>
                </td>
                <td>
                    <?php if ($r['estado'] === 'ENCONTRADO'): ?>
                        <span class="badge badge-found">ENCONTRADO</span>
                    <?php elseif ($r['estado'] === 'NO_EXISTE'): ?>
                        <span class="badge badge-no">No existe</span>
                    <?php elseif ($r['estado'] === 'SIN_USERS'): ?>
                        <span class="badge badge-err">Sin users.auth</span>
                    <?php else: ?>
                        <span class="badge badge-err"><?= htmlspecialchars($r['estado']) ?></span>
                    <?php endif; ?>
                </td>
                <td><?= $r['tiene_sie2'] ? htmlspecialchars($r['nombre_sie2']) : '<span style="color:#94a3b8;">—</span>' ?></td>
                <td><?= $r['tiene_sie2'] ? htmlspecialchars($r['email_sie2']) : '<span style="color:#94a3b8;">—</span>' ?></td>
                <td><?= $r['tiene_sie2'] ? htmlspecialchars($r['grupos_sie2']) : '<span style="color:#94a3b8;">—</span>' ?></td>
                <td><?= $r['tiene_users'] ? $r['total_users'] : '—' ?></td>
                <?php if ($modo === 'corregir'): ?>
                <td>
                    <?php if ($fix): ?>
                        <span class="badge <?= $fix['ok'] ? 'badge-fix' : 'badge-err' ?>">
                            <?= $fix['ok'] ? 'ACTUALIZADO' : 'ERROR' ?>
                        </span>
                        <span style="font-size:0.8em;"><?= htmlspecialchars($fix['msg']) ?></span>
                    <?php elseif ($r['tiene_sie2']): ?>
                        <span style="color:#94a3b8;">—</span>
                    <?php endif; ?>
                </td>
                <?php endif; ?>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

</div><!-- /container -->

<script>
function filtrar() {
    var texto = document.getElementById('filtro').value.toLowerCase();
    var estado = document.getElementById('filtroEstado').value;
    var rows = document.querySelectorAll('#tabla tbody tr');
    rows.forEach(function(row) {
        var name = row.dataset.name || '';
        var est = row.dataset.estado || '';
        var showText = !texto || name.indexOf(texto) !== -1;
        var showEstado = !estado || est === estado;
        row.style.display = (showText && showEstado) ? '' : 'none';
    });
}

function togglePw() {
    var pw = document.getElementById('pw');
    pw.type = pw.type === 'password' ? 'text' : 'password';
}

function validarFormulario() {
    var pw = document.getElementById('pw').value;
    if (pw.length < 6) {
        alert('La contrasena debe tener al menos 6 caracteres.');
        return false;
    }

    var sel = document.getElementById('subSelect');
    var target = sel.value ? sel.options[sel.selectedIndex].text : 'TODOS los sistemas con <?= htmlspecialchars($targetUser) ?>';

    return confirm(
        'ATENCION: Esto cambiara la contrasena del usuario "<?= htmlspecialchars($targetUser) ?>" en:\n\n' +
        '   ' + target + '\n\n' +
        'Se creara backup automatico de users.auth.php antes de modificar.\n\n' +
        'Continuar?'
    );
}

// Indicador de fortaleza de contrasena
document.getElementById('pw').addEventListener('input', function() {
    var pw = this.value;
    var el = document.getElementById('pwStrength');
    if (pw.length === 0) { el.innerHTML = ''; return; }
    if (pw.length < 6) { el.innerHTML = '<span style="color:#dc2626;">Muy corta</span>'; return; }
    var score = 0;
    if (pw.length >= 8) score++;
    if (pw.length >= 12) score++;
    if (/[A-Z]/.test(pw)) score++;
    if (/[0-9]/.test(pw)) score++;
    if (/[^a-zA-Z0-9]/.test(pw)) score++;

    var labels = ['Debil', 'Regular', 'Aceptable', 'Buena', 'Fuerte'];
    var colors = ['#dc2626', '#d97706', '#d97706', '#16a34a', '#16a34a'];
    var idx = Math.min(score, 4);
    el.innerHTML = '<span style="color:' + colors[idx] + ';">' + labels[idx] + '</span>';
});
</script>
</body>
</html>
