<?php
/**
 * DIAGNOSTICO: Limites de Upload del Servidor
 * =============================================
 * Muestra todos los limites que afectan la subida de archivos:
 * - PHP (upload_max_filesize, post_max_size, memory_limit, etc.)
 * - Cloudflare (deteccion automatica)
 * - DokuWiki (configuracion interna)
 * - Apache/Nginx
 * - Test real de upload con archivo de prueba
 *
 * Subir a: lib/plugins/siedeployer/diagnosticos/
 */

error_reporting(E_ALL);
ini_set('display_errors', '1');

header('Content-Type: text/html; charset=UTF-8');

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

function phpToBytes($val) {
    $val = trim($val);
    if ($val === '' || $val === '-1') return -1;
    $num = (float)$val;
    $unit = strtolower(substr($val, -1));
    switch ($unit) {
        case 'g': $num *= 1073741824; break;
        case 'm': $num *= 1048576; break;
        case 'k': $num *= 1024; break;
    }
    return (int)$num;
}

function formatSize($bytes) {
    if ($bytes < 0) return 'Sin limite (-1)';
    if ($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576) return round($bytes / 1048576, 1) . ' MB';
    if ($bytes >= 1024) return round($bytes / 1024, 1) . ' KB';
    return $bytes . ' B';
}

function getStatus($bytes, $target = 104857600) { // 100MB default
    if ($bytes < 0) return ['ok', 'Sin limite'];
    if ($bytes >= $target) return ['ok', 'Suficiente'];
    return ['fail', 'INSUFICIENTE — bloquea uploads > ' . formatSize($bytes)];
}

function statusBadge($status) {
    if ($status[0] === 'ok') return '<span style="background:#065f46;color:#4ade80;padding:3px 10px;border-radius:4px;font-size:0.82em;font-weight:600;">✓ ' . $status[1] . '</span>';
    return '<span style="background:#7f1d1d;color:#f87171;padding:3px 10px;border-radius:4px;font-size:0.82em;font-weight:600;">✗ ' . $status[1] . '</span>';
}

// =====================================================================
//  RECOPILAR DATOS
// =====================================================================

$uploadMax     = ini_get('upload_max_filesize');
$uploadMaxB    = phpToBytes($uploadMax);
$postMax       = ini_get('post_max_size');
$postMaxB      = phpToBytes($postMax);
$memoryLimit   = ini_get('memory_limit');
$memoryLimitB  = phpToBytes($memoryLimit);
$maxExecTime   = ini_get('max_execution_time');
$maxInputTime  = ini_get('max_input_time');
$maxFileUploads = ini_get('max_file_uploads');
$suhosinPost   = ini_get('suhosin.post.max_value_length');
$suhosinPostB  = $suhosinPost ? phpToBytes($suhosinPost) : -1;

// Limite real efectivo (minimo de todos)
$efectivo = PHP_INT_MAX;
if ($uploadMaxB > 0 && $uploadMaxB < $efectivo) $efectivo = $uploadMaxB;
if ($postMaxB > 0 && $postMaxB < $efectivo) $efectivo = $postMaxB;
if ($suhosinPostB > 0 && $suhosinPostB < $efectivo) $efectivo = $suhosinPostB;
if ($efectivo === PHP_INT_MAX) $efectivo = -1;

// Cloudflare
$isCloudflare = isset($_SERVER['HTTP_CF_RAY']) || isset($_SERVER['HTTP_CF_CONNECTING_IP']);
$cfRay = $_SERVER['HTTP_CF_RAY'] ?? '';
$cfIP  = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? '';

// PHP info
$phpVersion = phpversion();
$sapi       = php_sapi_name();
$phpIniPath = php_ini_loaded_file();
$extraIni   = php_ini_scanned_files();

// DokuWiki
$dokuBase = realpath(__DIR__ . '/../../../../');
$dokuConf = $dokuBase . '/conf/local.php';
$dokuConfExists = file_exists($dokuConf);
$dokuUploadSize = '';
if ($dokuConfExists) {
    $confContent = file_get_contents($dokuConf);
    if (preg_match("/\\\$conf\['uploadsize'\]\s*=\s*(\d+)/", $confContent, $m)) {
        $dokuUploadSize = $m[1];
    }
}

// Apache
$htaccessFile = $dokuBase . '/.htaccess';
$htaccessLRB  = '';
if (file_exists($htaccessFile)) {
    $htContent = file_get_contents($htaccessFile);
    if (preg_match('/LimitRequestBody\s+(\d+)/i', $htContent, $m)) {
        $htaccessLRB = $m[1];
    }
}

// mod_security
$modSecurity = function_exists('apache_get_modules') ? in_array('mod_security', apache_get_modules()) : 'No detectable';

// Servidor
$serverSoftware = $_SERVER['SERVER_SOFTWARE'] ?? 'Desconocido';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';

// Target para evaluar (100MB)
$target = 100 * 1048576; // 100 MB

// =====================================================================
//  TEST DE UPLOAD REAL
// =====================================================================

$testResult = null;
$testError  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'test_upload') {
    if (isset($_FILES['test_file'])) {
        $f = $_FILES['test_file'];
        $testResult = [
            'name'     => $f['name'],
            'size'     => $f['size'],
            'tmp_name' => $f['tmp_name'],
            'error'    => $f['error'],
            'type'     => $f['type'],
        ];

        switch ($f['error']) {
            case UPLOAD_ERR_OK:
                $testError = '';
                // Verificar que el archivo temporal existe y tiene el tamaño correcto
                if (file_exists($f['tmp_name'])) {
                    $realSize = filesize($f['tmp_name']);
                    $testResult['real_size'] = $realSize;
                    $testResult['match'] = ($realSize == $f['size']);
                }
                // Limpiar — NO guardar el archivo
                break;
            case UPLOAD_ERR_INI_SIZE:
                $testError = 'PHP rechazó el archivo: excede upload_max_filesize (' . $uploadMax . ')';
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $testError = 'PHP rechazó el archivo: excede MAX_FILE_SIZE del formulario';
                break;
            case UPLOAD_ERR_PARTIAL:
                $testError = 'El archivo se subió parcialmente (conexión interrumpida)';
                break;
            case UPLOAD_ERR_NO_FILE:
                $testError = 'No se seleccionó ningún archivo';
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $testError = 'Falta carpeta temporal en el servidor';
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $testError = 'No se pudo escribir en disco';
                break;
            case UPLOAD_ERR_EXTENSION:
                $testError = 'Extensión de PHP bloqueó el upload';
                break;
            default:
                $testError = 'Error desconocido: ' . $f['error'];
        }
    } elseif (empty($_FILES)) {
        // $_FILES vacío = POST excedió post_max_size
        $testError = 'POST rechazado completamente: el archivo probablemente excede post_max_size (' . $postMax . '). PHP descarta todo el POST cuando se supera este limite.';
        $testResult = ['error' => -1, 'name' => '(descartado)', 'size' => 0];
    }
}

?><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diagnostico Upload - <?= htmlspecialchars($host) ?></title>
<style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0f172a; color: #e2e8f0; padding: 20px; }
    .container { max-width: 900px; margin: 0 auto; }
    h1 { color: #38bdf8; margin-bottom: 4px; font-size: 1.5em; }
    h2 { color: #fbbf24; font-size: 1.1em; margin: 20px 0 10px; }
    .subtitle { color: #64748b; font-size: 0.85em; margin-bottom: 20px; }

    .section { background: #1e293b; border-radius: 10px; padding: 18px; margin-bottom: 14px; border: 1px solid #334155; }
    table { width: 100%; border-collapse: collapse; font-size: 0.88em; }
    th { text-align: left; padding: 8px; color: #94a3b8; border-bottom: 1px solid #334155; font-size: 0.82em; }
    td { padding: 8px; border-bottom: 1px solid #1e293b; }
    tr:hover { background: #334155; }

    .val { font-weight: 700; color: #38bdf8; font-family: monospace; font-size: 1.05em; }
    .val-big { font-size: 1.8em; font-weight: 700; }
    .green { color: #4ade80; }
    .red { color: #f87171; }
    .yellow { color: #fbbf24; }
    .blue { color: #38bdf8; }

    .alert-ok { background: #052e16; border: 1px solid #16a34a; border-radius: 10px; padding: 14px; margin-bottom: 14px; color: #4ade80; }
    .alert-fail { background: #450a0a; border: 1px solid #dc2626; border-radius: 10px; padding: 14px; margin-bottom: 14px; color: #f87171; }
    .alert-warn { background: #422006; border: 1px solid #d97706; border-radius: 10px; padding: 14px; margin-bottom: 14px; color: #fbbf24; }
    .alert-info { background: #0c2d48; border: 1px solid #2563eb; border-radius: 10px; padding: 14px; margin-bottom: 14px; color: #93c5fd; }

    .test-box { background: #334155; border-radius: 10px; padding: 20px; margin-top: 12px; }
    .test-box input[type=file] { margin: 10px 0; }
    .btn { display: inline-block; padding: 10px 20px; border-radius: 8px; font-weight: 600; font-size: 0.9em;
           cursor: pointer; border: none; color: #fff; }
    .btn-blue { background: #2563eb; }
    .btn-blue:hover { background: #1d4ed8; }
    .btn-green { background: #16a34a; }

    .fix-box { background: #1a1a2e; border: 1px solid #475569; border-radius: 8px; padding: 14px; margin-top: 10px;
               font-family: monospace; font-size: 0.85em; line-height: 1.8; white-space: pre-wrap; color: #e2e8f0; }

    .meter { display: flex; align-items: center; gap: 10px; margin: 10px 0; }
    .meter-bar { flex: 1; height: 24px; background: #334155; border-radius: 6px; overflow: hidden; position: relative; }
    .meter-fill { height: 100%; border-radius: 6px; transition: width 0.3s; display: flex; align-items: center; justify-content: center;
                  font-size: 0.75em; font-weight: 700; color: #fff; }
    .meter-label { min-width: 100px; font-size: 0.85em; color: #94a3b8; }
</style>
</head>
<body>
<div class="container">

<h1>&#128269; Diagnostico de Limites de Upload</h1>
<p class="subtitle"><?= htmlspecialchars($host) ?> | PHP <?= $phpVersion ?> (<?= $sapi ?>) | <?= date('Y-m-d H:i:s') ?></p>

<!-- ============================================================ -->
<!-- VEREDICTO PRINCIPAL -->
<!-- ============================================================ -->

<?php
$efectivoMB = $efectivo > 0 ? round($efectivo / 1048576) : 0;
$cfBloquea = $isCloudflare && $efectivo > $target;
?>

<?php if ($efectivo < 0 || $efectivo >= $target): ?>
    <?php if ($cfBloquea): ?>
    <div class="alert-warn">
        <strong>&#9888; PHP permite >100MB pero Cloudflare lo bloquea.</strong><br>
        PHP acepta hasta <?= formatSize($efectivo) ?>, pero este dominio pasa por Cloudflare que tiene limite de 100MB.
        El script <code>niccadminmenu/script.js</code> deberia redirigir al dominio directo automaticamente.
    </div>
    <?php else: ?>
    <div class="alert-ok">
        <strong>&#9989; El servidor PERMITE uploads >100MB.</strong><br>
        Limite efectivo: <strong><?= formatSize($efectivo) ?></strong>
        <?= $isCloudflare ? '' : '(sin Cloudflare)' ?>
    </div>
    <?php endif; ?>
<?php else: ?>
    <div class="alert-fail">
        <strong>&#10060; El servidor BLOQUEA uploads >100MB.</strong><br>
        Limite efectivo: <strong><?= formatSize($efectivo) ?></strong> — cualquier archivo mayor sera rechazado por PHP.
        <br>Vea la seccion "Como solucionarlo" mas abajo.
    </div>
<?php endif; ?>

<!-- ============================================================ -->
<!-- LIMITES PHP -->
<!-- ============================================================ -->

<div class="section">
    <h2>&#9881; Limites PHP</h2>
    <table>
        <thead><tr><th>Directiva</th><th>Valor</th><th>En bytes</th><th>Estado para >100MB</th></tr></thead>
        <tbody>
            <tr>
                <td><strong>upload_max_filesize</strong><br><small style="color:#64748b;">Tamaño maximo por archivo</small></td>
                <td class="val"><?= htmlspecialchars($uploadMax) ?></td>
                <td><?= formatSize($uploadMaxB) ?></td>
                <td><?= statusBadge(getStatus($uploadMaxB, $target)) ?></td>
            </tr>
            <tr>
                <td><strong>post_max_size</strong><br><small style="color:#64748b;">Tamaño maximo del POST completo</small></td>
                <td class="val"><?= htmlspecialchars($postMax) ?></td>
                <td><?= formatSize($postMaxB) ?></td>
                <td><?= statusBadge(getStatus($postMaxB, $target + 1048576)) ?></td>
            </tr>
            <tr>
                <td><strong>memory_limit</strong><br><small style="color:#64748b;">RAM disponible para PHP</small></td>
                <td class="val"><?= htmlspecialchars($memoryLimit) ?></td>
                <td><?= formatSize($memoryLimitB) ?></td>
                <td><?= statusBadge(getStatus($memoryLimitB, 134217728)) ?></td>
            </tr>
            <tr>
                <td><strong>max_execution_time</strong><br><small style="color:#64748b;">Tiempo maximo de ejecucion (seg)</small></td>
                <td class="val"><?= $maxExecTime ?>s</td>
                <td>—</td>
                <td><?= statusBadge($maxExecTime == 0 || $maxExecTime >= 120 ? ['ok', 'Suficiente'] : ['fail', 'Muy bajo para archivos grandes']) ?></td>
            </tr>
            <tr>
                <td><strong>max_input_time</strong><br><small style="color:#64748b;">Tiempo maximo para recibir datos (seg)</small></td>
                <td class="val"><?= $maxInputTime ?>s</td>
                <td>—</td>
                <td><?= statusBadge($maxInputTime == -1 || $maxInputTime >= 120 ? ['ok', 'Suficiente'] : ['fail', 'Puede cortar uploads lentos']) ?></td>
            </tr>
            <tr>
                <td><strong>max_file_uploads</strong><br><small style="color:#64748b;">Archivos simultaneos por POST</small></td>
                <td class="val"><?= $maxFileUploads ?></td>
                <td>—</td>
                <td><?= statusBadge(['ok', 'OK']) ?></td>
            </tr>
            <?php if ($suhosinPost): ?>
            <tr>
                <td><strong>suhosin.post.max_value_length</strong><br><small style="color:#64748b;">Limite Suhosin</small></td>
                <td class="val"><?= htmlspecialchars($suhosinPost) ?></td>
                <td><?= formatSize($suhosinPostB) ?></td>
                <td><?= statusBadge(getStatus($suhosinPostB, $target)) ?></td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Barra visual del limite efectivo -->
    <div style="margin-top:16px;">
        <strong style="color:#94a3b8;">Limite efectivo vs objetivo (100MB):</strong>
        <?php
        $pct = $efectivo > 0 ? min(100, round(($efectivo / max($efectivo, $target)) * 100)) : 100;
        $barColor = $efectivo < 0 || $efectivo >= $target ? '#4ade80' : '#f87171';
        $pctTarget = $efectivo > 0 ? min(100, round(($target / max($efectivo, $target)) * 100)) : 50;
        ?>
        <div class="meter">
            <span class="meter-label">Actual: <strong style="color:<?= $barColor ?>;"><?= formatSize($efectivo) ?></strong></span>
            <div class="meter-bar">
                <div class="meter-fill" style="width:<?= $pct ?>%;background:<?= $barColor ?>;"><?= formatSize($efectivo) ?></div>
            </div>
        </div>
        <div class="meter">
            <span class="meter-label">Objetivo: <strong class="yellow">100 MB</strong></span>
            <div class="meter-bar">
                <div class="meter-fill" style="width:<?= $pctTarget ?>%;background:#fbbf24;">100 MB</div>
            </div>
        </div>
    </div>
</div>

<!-- ============================================================ -->
<!-- CLOUDFLARE -->
<!-- ============================================================ -->

<div class="section">
    <h2>&#9729; Cloudflare</h2>
    <table>
        <thead><tr><th>Parametro</th><th>Valor</th><th>Impacto</th></tr></thead>
        <tbody>
            <tr>
                <td><strong>Conexion via Cloudflare</strong></td>
                <td class="val"><?= $isCloudflare ? '<span class="yellow">SI</span>' : '<span class="green">NO (conexion directa)</span>' ?></td>
                <td><?= $isCloudflare ? '<span class="yellow">Limite 100MB en uploads</span>' : '<span class="green">Sin limite de Cloudflare</span>' ?></td>
            </tr>
            <?php if ($isCloudflare): ?>
            <tr>
                <td>CF-RAY</td>
                <td style="font-family:monospace;font-size:0.85em;"><?= htmlspecialchars($cfRay) ?></td>
                <td>Identificador del request</td>
            </tr>
            <tr>
                <td>IP real del cliente</td>
                <td style="font-family:monospace;font-size:0.85em;"><?= htmlspecialchars($cfIP) ?></td>
                <td>—</td>
            </tr>
            <?php endif; ?>
            <tr>
                <td>Dominio actual</td>
                <td class="val"><?= htmlspecialchars($host) ?></td>
                <td>—</td>
            </tr>
            <tr>
                <td>Servidor</td>
                <td style="font-size:0.85em;"><?= htmlspecialchars($serverSoftware) ?></td>
                <td>—</td>
            </tr>
        </tbody>
    </table>
</div>

<!-- ============================================================ -->
<!-- DOKUWIKI -->
<!-- ============================================================ -->

<div class="section">
    <h2>&#128214; DokuWiki</h2>
    <table>
        <thead><tr><th>Parametro</th><th>Valor</th><th>Impacto</th></tr></thead>
        <tbody>
            <tr>
                <td><strong>$conf['uploadsize']</strong></td>
                <td class="val"><?= $dokuUploadSize ? $dokuUploadSize . ' MB' : '<span class="green">No configurado (sin limite DokuWiki)</span>' ?></td>
                <td><?= $dokuUploadSize ? statusBadge(getStatus($dokuUploadSize * 1048576, $target)) : statusBadge(['ok', 'No bloquea']) ?></td>
            </tr>
            <tr>
                <td>conf/local.php</td>
                <td><?= $dokuConfExists ? '<span class="green">Existe</span>' : '<span class="yellow">No existe</span>' ?></td>
                <td>—</td>
            </tr>
            <tr>
                <td>Ruta DokuWiki</td>
                <td style="font-size:0.82em;font-family:monospace;"><?= htmlspecialchars($dokuBase) ?></td>
                <td>—</td>
            </tr>
        </tbody>
    </table>
</div>

<!-- ============================================================ -->
<!-- APACHE -->
<!-- ============================================================ -->

<div class="section">
    <h2>&#128737; Apache / Web Server</h2>
    <table>
        <thead><tr><th>Parametro</th><th>Valor</th><th>Impacto</th></tr></thead>
        <tbody>
            <tr>
                <td><strong>LimitRequestBody</strong> (.htaccess)</td>
                <td class="val"><?= $htaccessLRB ? formatSize((int)$htaccessLRB) : '<span class="green">No configurado (sin limite)</span>' ?></td>
                <td><?= $htaccessLRB ? statusBadge(getStatus((int)$htaccessLRB, $target)) : statusBadge(['ok', 'No bloquea']) ?></td>
            </tr>
            <tr>
                <td>mod_security</td>
                <td><?= is_bool($modSecurity) ? ($modSecurity ? '<span class="yellow">Activo</span>' : '<span class="green">No activo</span>') : '<span style="color:#64748b;">No detectable (CGI/FPM)</span>' ?></td>
                <td><?= is_bool($modSecurity) && $modSecurity ? '<span class="yellow">Puede bloquear uploads grandes</span>' : '—' ?></td>
            </tr>
            <tr>
                <td>php.ini cargado</td>
                <td style="font-size:0.82em;font-family:monospace;"><?= htmlspecialchars($phpIniPath ?: 'No detectado') ?></td>
                <td>—</td>
            </tr>
        </tbody>
    </table>
</div>

<!-- ============================================================ -->
<!-- TEST DE UPLOAD REAL -->
<!-- ============================================================ -->

<div class="section">
    <h2>&#128295; Test de Upload Real</h2>
    <p style="color:#94a3b8;font-size:0.85em;margin-bottom:10px;">
        Suba un archivo para verificar que PHP lo acepta. El archivo NO se guarda — solo se verifica que llegue completo.
    </p>

    <?php if ($testResult !== null): ?>
        <?php if ($testResult['error'] === 0 || $testResult['error'] === UPLOAD_ERR_OK): ?>
        <div class="alert-ok">
            <strong>&#9989; Upload exitoso!</strong><br>
            Archivo: <strong><?= htmlspecialchars($testResult['name']) ?></strong><br>
            Tamaño reportado: <strong><?= formatSize($testResult['size']) ?></strong><br>
            Tamaño real en tmp: <strong><?= formatSize($testResult['real_size'] ?? 0) ?></strong><br>
            Coincide: <?= !empty($testResult['match']) ? '<span class="green">SI</span>' : '<span class="red">NO</span>' ?>
        </div>
        <?php else: ?>
        <div class="alert-fail">
            <strong>&#10060; Upload fallido!</strong><br>
            <?= htmlspecialchars($testError) ?><br>
            Error code: <?= $testResult['error'] ?>
        </div>
        <?php endif; ?>
    <?php endif; ?>

    <div class="test-box">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="test_upload" />
            <label style="font-weight:600;">Seleccione un archivo para probar:</label><br>
            <input type="file" name="test_file" style="margin:10px 0;" /><br>
            <small style="color:#64748b;">Tip: Para probar >100MB, cree un archivo grande con: <code style="color:#38bdf8;">fsutil file createnew test100mb.bin 104857600</code> (Windows)</small><br><br>
            <button type="submit" class="btn btn-blue">&#128640; Subir archivo de prueba</button>
        </form>
    </div>
</div>

<!-- ============================================================ -->
<!-- COMO SOLUCIONARLO -->
<!-- ============================================================ -->

<?php if ($efectivo > 0 && $efectivo < $target): ?>
<div class="section">
    <h2 style="color:#f87171;">&#128736; Como solucionarlo</h2>
    <p style="color:#94a3b8;font-size:0.88em;margin-bottom:12px;">
        Necesita aumentar los limites de PHP. Hay varias formas segun el tipo de servidor:
    </p>

    <h3 style="color:#38bdf8;font-size:0.95em;margin:12px 0 6px;">Opcion 1: .htaccess (Apache + mod_php)</h3>
    <div class="fix-box">php_value upload_max_filesize 200M
php_value post_max_size 210M
php_value memory_limit 512M
php_value max_execution_time 300
php_value max_input_time 300</div>

    <h3 style="color:#38bdf8;font-size:0.95em;margin:12px 0 6px;">Opcion 2: .user.ini (PHP-FPM / CGI)</h3>
    <div class="fix-box">upload_max_filesize = 200M
post_max_size = 210M
memory_limit = 512M
max_execution_time = 300
max_input_time = 300</div>

    <h3 style="color:#38bdf8;font-size:0.95em;margin:12px 0 6px;">Opcion 3: cPanel → MultiPHP INI Editor</h3>
    <div class="fix-box">1. Ir a cPanel → MultiPHP INI Editor
2. Seleccionar el dominio
3. Cambiar:
   upload_max_filesize = 200M
   post_max_size = 210M
   memory_limit = 512M
   max_execution_time = 300
   max_input_time = 300
4. Guardar</div>

    <h3 style="color:#38bdf8;font-size:0.95em;margin:12px 0 6px;">Opcion 4: ini_set() en PHP (solo memory_limit y max_execution_time)</h3>
    <div class="fix-box">&lt;?php
// Agregar al inicio de conf/local.php o en un preload
@ini_set('memory_limit', '512M');
@set_time_limit(300);
// NOTA: upload_max_filesize y post_max_size NO se pueden cambiar con ini_set()</div>

    <p style="color:#fbbf24;font-size:0.85em;margin-top:12px;">
        <strong>Importante:</strong> <code>upload_max_filesize</code> y <code>post_max_size</code> solo se pueden cambiar
        en <code>php.ini</code>, <code>.htaccess</code> (mod_php), <code>.user.ini</code> (FPM) o cPanel.
        <strong>NO funcionan con ini_set().</strong>
    </p>
</div>
<?php endif; ?>

<!-- ============================================================ -->
<!-- RESUMEN RAPIDO -->
<!-- ============================================================ -->

<div class="section" style="border-color:#475569;">
    <h2>&#128203; Resumen rapido</h2>
    <table>
        <tbody>
            <tr>
                <td style="width:250px;"><strong>Limite efectivo PHP</strong></td>
                <td><span class="val-big <?= $efectivo < 0 || $efectivo >= $target ? 'green' : 'red' ?>"><?= formatSize($efectivo) ?></span></td>
            </tr>
            <tr>
                <td><strong>Cloudflare activo</strong></td>
                <td><span class="val-big <?= $isCloudflare ? 'yellow' : 'green' ?>"><?= $isCloudflare ? 'SI (100MB max)' : 'NO' ?></span></td>
            </tr>
            <tr>
                <td><strong>¿Puede subir >100MB?</strong></td>
                <td>
                    <?php
                    if ($efectivo > 0 && $efectivo < $target) {
                        echo '<span class="val-big red">NO — PHP limita a ' . formatSize($efectivo) . '</span>';
                    } elseif ($isCloudflare) {
                        echo '<span class="val-big yellow">Solo via dominio directo (bypass Cloudflare)</span>';
                    } else {
                        echo '<span class="val-big green">SI</span>';
                    }
                    ?>
                </td>
            </tr>
        </tbody>
    </table>
</div>

<p style="text-align:center;color:#475569;font-size:0.8em;margin-top:20px;">
    Diagnostico generado el <?= date('Y-m-d H:i:s') ?> | PHP <?= $phpVersion ?> | SAPI: <?= $sapi ?>
</p>

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