<?php
/**
 * DETECTOR Y CORRECTOR DE LOCAL.PHP - SUBDOMINIOS SIE
 * ====================================================
 * 1. Escanea TODOS los subdominios DokuWiki
 * 2. Detecta los que NO tienen basedir = '/' o tienen problemas de config
 * 3. Corrige reemplazando local.php completo con plantilla estandar,
 *    conservando solo los valores especificos de cada sistema
 *
 * MODOS:
 *   ?modo=escanear   (default) - Solo detectar, no modificar nada
 *   ?modo=corregir              - Corregir TODOS los afectados
 *   ?sub=nombre                 - Verificar/corregir uno solo
 *
 * VALORES QUE SE CONSERVAN DEL ORIGINAL:
 *   - title, template, notify, registernotify, mailfrom, mailreturnpath
 *   - groq_api_key, groq_model, ia_tope_mes (si existen)
 *
 * VALORES QUE SE AJUSTAN:
 *   - basedir = '/' (siempre)
 *   - baseurl = 'https://{carpeta}.{dominio}/' (corregido si no corresponde)
 *
 * TODO LO DEMAS: valores fijos de la plantilla estandar
 */

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

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

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

// Dominios conocidos del sistema SIE
$dominiosConocidos = [
    'sistemavirtualdegestion.com',
    'systemsie.site',
    'susprofesionales.com',
    'sieasesorias.com',
    'gestioncontrolada.com',
];

// Dominio por defecto para baseurl cuando no se puede determinar
$dominioPorDefecto = 'sistemavirtualdegestion.com';

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

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

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

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

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));
}

// =====================================================================
//  PLANTILLA LOCAL.PHP
// =====================================================================

/**
 * Genera el contenido de local.php usando la plantilla estandar
 * con los valores especificos del sistema
 */
function generarLocalPhp($valores)
{
    $title          = addcslashes($valores['title'], "'");
    $template       = addcslashes($valores['template'], "'");
    $baseurl        = addcslashes($valores['baseurl'], "'");
    $notify         = addcslashes($valores['notify'], "'");
    $registernotify = addcslashes($valores['registernotify'], "'");
    $mailfrom       = addcslashes($valores['mailfrom'], "'");
    $mailreturnpath = addcslashes($valores['mailreturnpath'], "'");

    $contenido = <<<'TEMPLATE_START'
<?php
/*
 * Dokuwiki's Main Configuration File - Local Settings
 * Auto-generated by config plugin
 * Run for user: sie2
 * Date: Sat, 25 Jan 2025 02:31:42 -0700
 */
date_default_timezone_set('America/Bogota');

TEMPLATE_START;

    $contenido .= "\$conf['title'] = '{$title}';\n";
    $contenido .= "\$conf['start'] = 'inicio';\n";
    $contenido .= "\$conf['lang'] = 'es';\n";
    $contenido .= "\$conf['template'] = '{$template}';\n";
    $contenido .= "\$conf['sidebar'] = 'menu1';\n";
    $contenido .= "\$conf['license'] = 'cc-by-sa';\n";
    $contenido .= "\$conf['basedir'] = '/';\n";
    $contenido .= "\$conf['baseurl'] = '{$baseurl}';\n";
    $contenido .= "\$conf['useheading'] = '1';\n";
    $contenido .= "\$conf['useacl'] = 1;\n";
    $contenido .= "\$conf['passcrypt'] = 'smd5';\n";
    $contenido .= "\$conf['defaultgroup'] = '';\n";
    $contenido .= "\$conf['superuser'] = '@sie';\n";
    $contenido .= "\$conf['manager'] = 'manager';\n";
    $contenido .= "\$conf['disableactions'] = 'register,profile_delete';\n";
    $contenido .= "\$conf['subscribers'] = 1;\n";
    $contenido .= "\$conf['notify'] = '{$notify}';\n";
    $contenido .= "\$conf['registernotify'] = '{$registernotify}';\n";
    $contenido .= "\$conf['mailfrom'] = '{$mailfrom}';\n";
    $contenido .= "\$conf['mailreturnpath'] = '{$mailreturnpath}';\n";
    $contenido .= "\$conf['mailprefix'] = 'Reporte de cambio documental sistema- SIE';\n";
    $contenido .= "\$conf['dontlog'] = 'error,debug';\n";
    $contenido .= "\$conf['updatecheck'] = 0;\n";
    $contenido .= "\$conf['defer_js'] = 0;\n";
    $contenido .= "\$conf['hidewarnings'] = 1;\n";
    $contenido .= "\$conf['proxy']['user'] = 'manager';\n";
    $contenido .= "\$conf['plugin']['authldap']['attributes'] = array();\n";
    $contenido .= "\$conf['plugin']['authldap']['groupscope'] = 'one';\n";
    $contenido .= "\$conf['plugin']['authorlist']['heading'] = 'Autores';\n";
    $contenido .= "\$conf['plugin']['authorlist']['intro'] = '<p><b>Autores:</b></p>';\n";
    $contenido .= "\$conf['plugin']['authorlist']['creatortext'] = '<p>Creado por <i>%CREATOR%</i> on %DATE%.</p>';\n";
    $contenido .= "\$conf['plugin']['ckgedit']['open_upload'] = 1;\n";
    $contenido .= "\$conf['plugin']['ckgedit']['allow_ckg_filebrowser'] = 'dokuwiki';\n";
    $contenido .= "\$conf['plugin']['ckgedit']['default_ckg_filebrowser'] = 'dokuwiki';\n";
    $contenido .= "\$conf['plugin']['ckgedit']['scayt_lang'] = 'Spanish/es_ES';\n";
    $contenido .= "\$conf['plugin']['ckgedit']['style_sheet'] = 1;\n";
    $contenido .= "\$conf['plugin']['dropfiles']['insertFileLink'] = 1;\n";
    $contenido .= "\$conf['plugin']['include']['order'] = 'title';\n";
    $contenido .= "\$conf['plugin']['indexmenu']['aclcache'] = 'none';\n";
    $contenido .= "\$conf['plugin']['pagetitle']['usePersistent'] = 1;\n";
    $contenido .= "\$conf['plugin']['publish']['hide_approved_banner'] = 1;\n";
    $contenido .= "\$conf['plugin']['publish']['apr_approved_text'] = 'Aprobado';\n";
    $contenido .= "\$conf['plugin']['tag']['toolbar_icon'] = 1;\n";
    $contenido .= "\$conf['plugin']['tag']['list_tags_of_subns'] = 1;\n";
    $contenido .= "\$conf['plugin']['templatepagename']['current_pagename_tpl'] = '_template';\n";
    $contenido .= "\$conf['plugin']['templatepagename']['inherited_pagename_tpl'] = '_template2';\n";
    $contenido .= "\$conf['plugin']['versionswitch']['regexes'] = '|{{tag>VERSIÓN';\n";
    $contenido .= "\$conf['token_ia'] = '';\n";

    // Agregar configuracion IA si existe en el original
    if (!empty($valores['groq_api_key'])) {
        $groqKey = addcslashes($valores['groq_api_key'], "'");
        $contenido .= "\$conf['groq_api_key'] = '{$groqKey}';\n";
    }
    if (!empty($valores['groq_model'])) {
        $groqModel = addcslashes($valores['groq_model'], "'");
        $contenido .= "\$conf['groq_model'] = '{$groqModel}';\n";
    }
    if (!empty($valores['ia_tope_mes'])) {
        $contenido .= "\$conf['ia_tope_mes'] = {$valores['ia_tope_mes']};\n";
    }

    $contenido .= "\n";
    $contenido .= "// SIE-IA Engine (motor local PHP - reemplaza API Python/Render)\n";
    $contenido .= "// IMPORTANTE: Estos 3 valores deben configurarse en conf/local.php de cada sistema:\n";
    $contenido .= "// \$conf['groq_api_key'] = 'gsk_XXXX...';  // Clave API de Groq (obligatorio para IA)\n";
    $contenido .= "// \$conf['groq_model']   = 'llama-3.3-70b-versatile'; // Modelo LLM de Groq\n";
    $contenido .= "// \$conf['ia_tope_mes']  = 50;              // Cupo maximo de consultas IA por mes (default: 10)\n";

    return $contenido;
}

// =====================================================================
//  FUNCIONES DE ANALISIS
// =====================================================================

/**
 * Lee TODOS los valores de configuracion del local.php actual
 */
function leerConfigActual($subPath)
{
    $config = [
        'title'          => '',
        'template'       => '',
        'basedir'        => '',
        'baseurl'        => '',
        'notify'         => '',
        'registernotify' => '',
        'mailfrom'       => '',
        'mailreturnpath' => '',
        'groq_api_key'   => '',
        'groq_model'     => '',
        'ia_tope_mes'    => '',
    ];

    foreach (['conf/local.php', 'conf/local_act.php'] as $confFile) {
        $path = $subPath . '/' . $confFile;
        if (!file_exists($path)) continue;
        $content = @file_get_contents($path);
        if ($content === false) continue;

        // Valores string
        if (preg_match_all("/\\\$conf\['([^']+)'\]\s*=\s*'([^']*)'\s*;/", $content, $m)) {
            for ($i = 0; $i < count($m[1]); $i++) {
                if (array_key_exists($m[1][$i], $config)) {
                    $config[$m[1][$i]] = $m[2][$i];
                }
            }
        }
        // Valores numericos
        if (preg_match_all("/\\\$conf\['([^']+)'\]\s*=\s*(\d+)\s*;/", $content, $m)) {
            for ($i = 0; $i < count($m[1]); $i++) {
                if (array_key_exists($m[1][$i], $config)) {
                    $config[$m[1][$i]] = $m[2][$i];
                }
            }
        }
    }

    return $config;
}

/**
 * Verifica si basedir esta definido explicitamente
 */
function tieneBasedirExplicito($subPath)
{
    foreach (['conf/local.php', 'conf/local_act.php'] as $confFile) {
        $path = $subPath . '/' . $confFile;
        if (!file_exists($path)) continue;
        $content = @file_get_contents($path);
        if ($content !== false && preg_match("/\\\$conf\['basedir'\]/", $content)) {
            return true;
        }
    }
    return false;
}

/**
 * Determina el baseurl correcto para un subdominio
 */
function calcularBaseurlCorrecto($carpeta, $baseurlActual, $dominiosConocidos, $dominioPorDefecto)
{
    $dominioActual = '';

    if (!empty($baseurlActual)) {
        $parsed = parse_url($baseurlActual);
        if (isset($parsed['host'])) {
            $host = $parsed['host'];
            $parts = explode('.', $host);
            $dominioActual = count($parts) >= 3 ? implode('.', array_slice($parts, 1)) : $host;
        }
    }

    // Si el dominio actual es conocido, mantenerlo
    if (!empty($dominioActual) && in_array($dominioActual, $dominiosConocidos)) {
        return 'https://' . $carpeta . '.' . $dominioActual . '/';
    }

    // Si no se puede determinar, usar dominio por defecto
    return 'https://' . $carpeta . '.' . $dominioPorDefecto . '/';
}

/**
 * Analiza un subdominio y retorna su estado
 */
function analizarSubdominio($subPath, $carpeta, $dominiosConocidos, $dominioPorDefecto)
{
    $r = [
        'carpeta'       => $carpeta,
        'tiene_doku'    => false,
        'config_actual' => [],
        'problemas'     => [],
        'estado'        => 'NO_DOKU',
        'baseurl_nuevo' => '',
    ];

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

    $config = leerConfigActual($subPath);
    $r['config_actual'] = $config;

    $basedirExplicito = tieneBasedirExplicito($subPath);

    // --- CHECK 1: basedir ---
    if (!$basedirExplicito) {
        $r['problemas'][] = 'BASEDIR_NO_DEFINIDO';
    } elseif ($config['basedir'] !== '/') {
        if (strtolower(trim($config['basedir'], '/')) === strtolower($carpeta)) {
            $r['problemas'][] = 'BASEDIR_DUPLICADO';
        } else {
            $r['problemas'][] = 'BASEDIR_OTRO';
        }
    }

    // --- CHECK 2: baseurl ---
    $baseurlCorrecto = calcularBaseurlCorrecto($carpeta, $config['baseurl'], $dominiosConocidos, $dominioPorDefecto);
    $r['baseurl_nuevo'] = $baseurlCorrecto;

    if (empty($config['baseurl'])) {
        $r['problemas'][] = 'BASEURL_VACIO';
    } else {
        $baseurlLimpio = rtrim($config['baseurl'], '/') . '/';
        if ($baseurlLimpio !== $baseurlCorrecto) {
            // Verificar que problemas especificos
            $parsed = parse_url($config['baseurl']);
            $host = $parsed['host'] ?? '';
            $parts = explode('.', $host);
            $subEnUrl = $parts[0] ?? '';
            $scheme = $parsed['scheme'] ?? 'http';

            if ($subEnUrl !== $carpeta) {
                $r['problemas'][] = 'BASEURL_SUBDOMINIO_MAL';
            }
            if ($scheme !== 'https') {
                $r['problemas'][] = 'BASEURL_HTTP';
            }
        }
    }

    // --- CHECK 3: template ---
    $tpl = $config['template'] ?: 'dokuwiki';
    if (!is_dir($subPath . '/lib/tpl/' . $tpl)) {
        $r['problemas'][] = 'TEMPLATE_NO_EXISTE';
    }

    // Determinar estado general
    if (empty($r['problemas'])) {
        $r['estado'] = 'OK';
    } else {
        $r['estado'] = 'PROBLEMA';
    }

    return $r;
}

/**
 * Corrige un subdominio reemplazando local.php con la plantilla
 */
function corregirSubdominio($subPath, $carpeta, $configActual, $baseurlNuevo, $dominiosConocidos, $dominioPorDefecto)
{
    $localPhp = $subPath . '/conf/local.php';

    if (!file_exists($localPhp)) {
        return ['ok' => false, 'msg' => 'conf/local.php no existe'];
    }

    // Crear backup con timestamp
    $timestamp = date('Ymd_His');
    $backupName = "local.php.bak_{$timestamp}";
    $backupPath = $subPath . '/conf/' . $backupName;
    if (!@copy($localPhp, $backupPath)) {
        return ['ok' => false, 'msg' => 'No se pudo crear backup'];
    }

    // Preparar valores para la plantilla
    $valores = [
        'title'          => $configActual['title'] ?: $carpeta,
        'template'       => $configActual['template'] ?: '20cones',
        'baseurl'        => $baseurlNuevo,
        'notify'         => $configActual['notify'] ?: 'proyect@sieasesorias.com',
        'registernotify' => $configActual['registernotify'] ?: 'proyect@sieasesorias.com',
        'mailfrom'       => $configActual['mailfrom'] ?: 'proyect@sieasesorias.com',
        'mailreturnpath' => $configActual['mailreturnpath'] ?: 'proyect@sieasesorias.com',
        'groq_api_key'   => $configActual['groq_api_key'] ?? '',
        'groq_model'     => $configActual['groq_model'] ?? '',
        'ia_tope_mes'    => $configActual['ia_tope_mes'] ?? '',
    ];

    // Generar nuevo local.php
    $nuevoContenido = generarLocalPhp($valores);

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

    // Tambien corregir local_act.php si existe
    $localAct = $subPath . '/conf/local_act.php';
    $actCorregido = false;
    if (file_exists($localAct)) {
        $actContent = @file_get_contents($localAct);
        if ($actContent !== false) {
            $actModificado = false;
            $actNuevo = $actContent;

            // Corregir basedir si existe y no es '/'
            if (preg_match("/\\\$conf\['basedir'\]\s*=\s*'[^']*'\s*;/", $actNuevo)) {
                $actNuevo = preg_replace(
                    "/\\\$conf\['basedir'\]\s*=\s*'[^']*'\s*;/",
                    "\$conf['basedir'] = '/';",
                    $actNuevo
                );
                $actModificado = true;
            }

            // Corregir baseurl si existe y no corresponde
            if (preg_match("/\\\$conf\['baseurl'\]\s*=\s*'([^']*)'\s*;/", $actNuevo, $m)) {
                $actBaseurl = rtrim($m[1], '/') . '/';
                if ($actBaseurl !== $baseurlNuevo) {
                    $actNuevo = preg_replace(
                        "/\\\$conf\['baseurl'\]\s*=\s*'[^']*'\s*;/",
                        "\$conf['baseurl'] = '" . addcslashes($baseurlNuevo, "'") . "';",
                        $actNuevo
                    );
                    $actModificado = true;
                }
            }

            if ($actModificado) {
                $actBackup = $subPath . '/conf/local_act.php.bak_' . $timestamp;
                @copy($localAct, $actBackup);
                @file_put_contents($localAct, $actNuevo);
                $actCorregido = true;
            }
        }
    }

    $msg = "OK. Backup: {$backupName}";
    if ($actCorregido) $msg .= ' + local_act.php corregido';

    return ['ok' => true, 'msg' => $msg];
}

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

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

// 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</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 = analizarSubdominio($subPath, $carpeta, $dominiosConocidos, $dominioPorDefecto);
    if (!$r['tiene_doku']) continue;
    $resultados[] = $r;

    // Corregir si esta en modo corregir y tiene problemas
    if ($modo === 'corregir' && $r['estado'] !== 'OK') {
        $fix = corregirSubdominio($subPath, $carpeta, $r['config_actual'], $r['baseurl_nuevo'], $dominiosConocidos, $dominioPorDefecto);
        $correcciones[$carpeta] = $fix;
    }
}

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

// Estadisticas
$totalOK       = count(array_filter($resultados, fn($r) => $r['estado'] === 'OK'));
$totalProblema = count(array_filter($resultados, fn($r) => $r['estado'] !== 'OK'));
$afectados     = array_filter($resultados, fn($r) => $r['estado'] !== 'OK');

// Contar por tipo de problema
$conteoProblemas = [];
foreach ($resultados as $r) {
    foreach ($r['problemas'] as $p) {
        if (!isset($conteoProblemas[$p])) $conteoProblemas[$p] = 0;
        $conteoProblemas[$p]++;
    }
}

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

if ($esCLI) {
    echo "================================================================\n";
    echo " CORRECTOR DE LOCAL.PHP - SUBDOMINIOS SIE\n";
    echo " " . date('Y-m-d H:i:s') . " | Modo: {$modo} | Tiempo: {$tiempoFin}s\n";
    echo "================================================================\n\n";

    echo "Total: " . count($resultados) . " | OK: {$totalOK} | Problemas: {$totalProblema}\n\n";

    if (!empty($conteoProblemas)) {
        echo "Tipos de problema encontrados:\n";
        foreach ($conteoProblemas as $tipo => $count) {
            echo "  {$tipo}: {$count}\n";
        }
        echo "\n";
    }

    if (!empty($afectados)) {
        echo "=== SISTEMAS CON PROBLEMAS ===\n";
        foreach ($afectados as $r) {
            $fix = $correcciones[$r['carpeta']] ?? null;
            echo sprintf("  %-30s [%s] %s\n",
                $r['carpeta'],
                implode(', ', $r['problemas']),
                $fix ? ($fix['ok'] ? '-> ' . $fix['msg'] : '-> ERROR: ' . $fix['msg']) : ''
            );
        }
    }
    exit(0);
}

// =====================================================================
//  SALIDA HTML
// =====================================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Corrector local.php - 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(130px, 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 #93c5fd; 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; }

    .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; }

    .problema-grupo { margin-bottom: 14px; padding: 12px 14px; border-radius: 8px; }
    .pg-basedir { background: #fee2e2; border: 1px solid #fecaca; }
    .pg-baseurl { background: #fef3c7; border: 1px solid #fde68a; }
    .pg-template { background: #fce7f3; border: 1px solid #f9a8d4; }
    .pg-title { font-weight: 700; font-size: 0.92em; margin-bottom: 6px; }
    .pg-lista { font-size: 0.85em; line-height: 1.9; }
    .pg-lista span { display: inline-block; margin-right: 10px; }

    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-err { background: #fef2f2; }
    tr.row-err:hover { background: #fee2e2; }

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

    code { background: #f1f5f9; padding: 1px 4px; border-radius: 3px; font-size: 0.86em; }
    code.err { background: #fee2e2; color: #991b1b; }
    code.ok { background: #dcfce7; color: #166534; }
    code.new { background: #dbeafe; color: #1e40af; }

    .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; }

    .detalle-cambio { font-size: 0.82em; margin-top: 4px; }
    .detalle-cambio .antes { color: #991b1b; text-decoration: line-through; }
    .detalle-cambio .despues { color: #166534; font-weight: 600; }
</style>
</head>
<body>
<div class="container">

<h1>&#128295; Corrector de local.php - Subdominios SIE</h1>
<p class="subtitle">
    <?= date('Y-m-d H:i:s') ?> |
    Modo: <strong><?= $modo === 'corregir' ? '&#9888;&#65039; CORREGIR' : '&#128269; ESCANEAR' ?></strong> |
    Tiempo: <?= $tiempoFin ?>s |
    Sistemas: <?= count($resultados) ?>
</p>

<div class="explain">
    <h2>&#128161; Que hace este script</h2>
    <p><strong>Escanear:</strong> Detecta sistemas donde <code>basedir</code> no es <code>'/'</code>, <code>baseurl</code> no corresponde, o el template no existe.</p>
    <p><strong>Corregir:</strong> Reemplaza <code>conf/local.php</code> con una plantilla estandar. Conserva: <code>title</code>, <code>template</code>, <code>notify</code>, <code>registernotify</code>, <code>mailfrom</code>, <code>mailreturnpath</code>, y config IA (groq). Crea backup antes de modificar.</p>
    <p>Fija <code>basedir = '/'</code> y ajusta <code>baseurl</code> a <code>https://{carpeta}.{dominio}/</code>.</p>
</div>

<!-- 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 green"><?= $totalOK ?></div><div class="label">OK</div></div>
    <div class="card"><div class="num <?= $totalProblema > 0 ? 'red' : 'green' ?>"><?= $totalProblema ?></div><div class="label">Con problemas</div></div>
    <?php foreach ($conteoProblemas as $tipo => $cnt): ?>
    <div class="card"><div class="num <?= $cnt > 0 ? 'yellow' : 'green' ?>"><?= $cnt ?></div><div class="label"><?= htmlspecialchars($tipo) ?></div></div>
    <?php endforeach; ?>
</div>

<!-- Botones -->
<div class="actions">
    <a href="?modo=escanear" class="btn btn-blue">&#128269; Escanear todos</a>
    <?php if ($totalProblema > 0 && $modo !== 'corregir'): ?>
        <a href="?modo=corregir" class="btn btn-red"
           onclick="return confirm('ATENCION: Esto va a reemplazar local.php en <?= $totalProblema ?> sistemas con la plantilla estandar.\n\nSe creara backup de cada archivo antes de modificar.\n\nValores conservados: title, template, notify, mailfrom, mailreturnpath, config IA.\n\nContinuar?')">
            &#128295; Corregir <?= $totalProblema ?> sistemas
        </a>
    <?php endif; ?>
    <?php if (!empty($targetSub)): ?>
        <a href="?" class="btn btn-gray">Ver todos</a>
    <?php endif; ?>
</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 de correcciones: <?= $fixOK ?> exitosas, <?= $fixErr ?> errores</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'] ? 'CORREGIDO' : 'ERROR' ?></span></td>
                <td><?= htmlspecialchars($fix['msg']) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<?php if ($totalProblema > 0 && $modo !== 'corregir'): ?>
<!-- Problemas agrupados -->
<div class="section">
    <h2>&#9888;&#65039; Sistemas con problemas (<?= $totalProblema ?>)</h2>

    <?php
    // Agrupar por tipo de problema
    $porTipo = [];
    foreach ($afectados as $r) {
        foreach ($r['problemas'] as $p) {
            if (!isset($porTipo[$p])) $porTipo[$p] = [];
            $porTipo[$p][] = $r;
        }
    }
    ?>

    <?php if (!empty($porTipo['BASEDIR_NO_DEFINIDO'])): ?>
    <div class="problema-grupo pg-basedir">
        <div class="pg-title">&#9940; BASEDIR NO DEFINIDO (<?= count($porTipo['BASEDIR_NO_DEFINIDO']) ?>) — CSS/JS no cargan</div>
        <div class="pg-lista">
            <?php foreach ($porTipo['BASEDIR_NO_DEFINIDO'] as $r): ?>
                <span>&#8226; <strong><?= htmlspecialchars($r['carpeta']) ?></strong></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($porTipo['BASEDIR_DUPLICADO'])): ?>
    <div class="problema-grupo pg-basedir">
        <div class="pg-title">&#9940; BASEDIR DUPLICADO (<?= count($porTipo['BASEDIR_DUPLICADO']) ?>) — CSS/JS no cargan</div>
        <div class="pg-lista">
            <?php foreach ($porTipo['BASEDIR_DUPLICADO'] as $r): ?>
                <span>&#8226; <strong><?= htmlspecialchars($r['carpeta']) ?></strong> <code class="err"><?= htmlspecialchars($r['config_actual']['basedir']) ?></code></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($porTipo['BASEURL_SUBDOMINIO_MAL'])): ?>
    <div class="problema-grupo pg-baseurl">
        <div class="pg-title">&#9888;&#65039; BASEURL SUBDOMINIO INCORRECTO (<?= count($porTipo['BASEURL_SUBDOMINIO_MAL']) ?>)</div>
        <div class="pg-lista">
            <?php foreach ($porTipo['BASEURL_SUBDOMINIO_MAL'] as $r): ?>
                <span>&#8226; <strong><?= htmlspecialchars($r['carpeta']) ?></strong>
                <code class="err" style="font-size:0.8em;"><?= htmlspecialchars($r['config_actual']['baseurl']) ?></code>
                &#8594; <code class="new" style="font-size:0.8em;"><?= htmlspecialchars($r['baseurl_nuevo']) ?></code></span><br>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($porTipo['BASEURL_VACIO'])): ?>
    <div class="problema-grupo pg-baseurl">
        <div class="pg-title">&#9888;&#65039; BASEURL VACIO (<?= count($porTipo['BASEURL_VACIO']) ?>)</div>
        <div class="pg-lista">
            <?php foreach ($porTipo['BASEURL_VACIO'] as $r): ?>
                <span>&#8226; <strong><?= htmlspecialchars($r['carpeta']) ?></strong> &#8594; <code class="new"><?= htmlspecialchars($r['baseurl_nuevo']) ?></code></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($porTipo['BASEURL_HTTP'])): ?>
    <div class="problema-grupo pg-baseurl">
        <div class="pg-title">&#9888;&#65039; BASEURL USA HTTP (<?= count($porTipo['BASEURL_HTTP']) ?>)</div>
        <div class="pg-lista">
            <?php foreach ($porTipo['BASEURL_HTTP'] as $r): ?>
                <span>&#8226; <strong><?= htmlspecialchars($r['carpeta']) ?></strong></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($porTipo['TEMPLATE_NO_EXISTE'])): ?>
    <div class="problema-grupo pg-template">
        <div class="pg-title">&#10060; TEMPLATE NO EXISTE (<?= count($porTipo['TEMPLATE_NO_EXISTE']) ?>)</div>
        <div class="pg-lista">
            <?php foreach ($porTipo['TEMPLATE_NO_EXISTE'] as $r): ?>
                <span>&#8226; <strong><?= htmlspecialchars($r['carpeta']) ?></strong> <code class="err"><?= htmlspecialchars($r['config_actual']['template']) ?></code></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</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="err">Con problemas</option>
            <option value="OK">Solo OK</option>
        </select>
    </div>
    <table id="tabla">
        <thead>
            <tr>
                <th>#</th>
                <th>Subdominio</th>
                <th>Title</th>
                <th>basedir</th>
                <th>baseurl actual</th>
                <th>baseurl correcto</th>
                <th>Template</th>
                <th>Problemas</th>
                <?php if ($modo === 'corregir'): ?><th>Fix</th><?php endif; ?>
            </tr>
        </thead>
        <tbody>
        <?php $i = 0; foreach ($resultados as $r): $i++; ?>
            <?php $fix = $correcciones[$r['carpeta']] ?? null; ?>
            <tr class="<?= $r['estado'] !== 'OK' ? 'row-err' : '' ?>"
                data-nombre="<?= strtolower($r['carpeta']) ?>"
                data-estado="<?= $r['estado'] ?>">
                <td><?= $i ?></td>
                <td><strong><?= htmlspecialchars($r['carpeta']) ?></strong></td>
                <td style="max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:0.82em;">
                    <?= htmlspecialchars($r['config_actual']['title'] ?: '(vacio)') ?>
                </td>
                <td>
                    <?php if (in_array('BASEDIR_NO_DEFINIDO', $r['problemas'])): ?>
                        <code class="err">(no definido)</code>
                    <?php elseif ($r['config_actual']['basedir'] === '/'): ?>
                        <code class="ok">/</code>
                    <?php else: ?>
                        <code class="err"><?= htmlspecialchars($r['config_actual']['basedir']) ?></code>
                    <?php endif; ?>
                </td>
                <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                    <code style="font-size:0.78em;<?= !empty($r['problemas']) ? 'color:#991b1b;' : '' ?>"><?= htmlspecialchars($r['config_actual']['baseurl'] ?: '(vacio)') ?></code>
                </td>
                <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                    <?php if ($r['estado'] !== 'OK'): ?>
                        <code class="new" style="font-size:0.78em;"><?= htmlspecialchars($r['baseurl_nuevo']) ?></code>
                    <?php else: ?>
                        <span style="color:#16a34a;">&#10004;</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php
                    $tpl = $r['config_actual']['template'] ?: 'default';
                    $tplErr = in_array('TEMPLATE_NO_EXISTE', $r['problemas']);
                    ?>
                    <code class="<?= $tplErr ? 'err' : '' ?>"><?= htmlspecialchars($tpl) ?></code>
                </td>
                <td>
                    <?php if (empty($r['problemas'])): ?>
                        <span class="badge badge-ok">OK</span>
                    <?php else: ?>
                        <?php foreach ($r['problemas'] as $p): ?>
                            <span class="badge badge-err" style="margin-bottom:2px;display:inline-block;"><?= htmlspecialchars($p) ?></span>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </td>
                <?php if ($modo === 'corregir'): ?>
                <td>
                    <?php if ($fix): ?>
                        <span class="badge <?= $fix['ok'] ? 'badge-ok' : 'badge-err' ?>"><?= $fix['ok'] ? '&#10004;' : '&#10008;' ?></span>
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
                <?php endif; ?>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

</div>

<script>
function filtrar() {
    var texto = document.getElementById('filtro').value.toLowerCase();
    var estado = document.getElementById('filtroEstado').value;
    document.querySelectorAll('#tabla tbody tr').forEach(function(f) {
        var mostrar = true;
        if (texto && f.getAttribute('data-nombre').indexOf(texto) === -1) mostrar = false;
        if (estado === 'err') {
            if (f.getAttribute('data-estado') === 'OK') mostrar = false;
        } else if (estado === 'OK') {
            if (f.getAttribute('data-estado') !== 'OK') mostrar = false;
        }
        f.style.display = mostrar ? '' : 'none';
    });
}
</script>
</body>
</html>
<?php
