<?php
/**
 * Plataforma Ganadera - Diagnostico rapido para cPanel
 * 
 * Subir a public_html y abrir en navegador:
 *   tu-dominio.com/diagnostico.php
 * 
 * ELIMINAR DESPUES DE USAR
 */
header('Content-Type: text/html; charset=utf-8');
?><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Diagnostico - Plataforma Ganadera</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:system-ui,-apple-system,sans-serif;background:#0f0f23;color:#e0e0e0;padding:1.5em;min-height:100vh}
.c{max-width:800px;margin:0 auto}
h1{color:#4ecdc4;font-size:1.5em;margin-bottom:.3em}
h2{color:#ffd93d;font-size:1em;margin:1.5em 0 .5em;padding-bottom:.3em;border-bottom:1px solid #333}
.sub{color:#888;font-size:.85em;margin-bottom:1.5em}
table{width:100%;border-collapse:collapse;margin:.5em 0 1em;font-size:.85em}
th{text-align:left;padding:8px 10px;background:#1a1a3e;color:#4ecdc4;font-weight:600}
td{padding:6px 10px;border-bottom:1px solid #1a1a3e}
tr:hover td{background:#16163a}
.ok{color:#4ecdc4;font-weight:600}
.fail{color:#ff6b6b;font-weight:600}
.warn{color:#ffd93d}
code{background:#1a1a3e;padding:2px 6px;border-radius:4px;font-size:.85em}
.box{background:#1a1a3e;border-radius:8px;padding:1em;margin:.5em 0;overflow:auto;font-size:.82em;font-family:monospace;max-height:300px}
</style>
</head>
<body>
<div class="c">
<h1>Diagnostico - Plataforma Ganadera</h1>
<p class="sub">Verificacion del entorno del servidor</p>

<?php
// ── 1. PHP ──
echo '<h2>1. PHP</h2>';
echo '<table>';
echo '<tr><td>Version</td><td>' . PHP_VERSION . '</td><td class="' . (version_compare(PHP_VERSION, '8.0.0', '>=') ? 'ok' : 'fail') . '">' . (version_compare(PHP_VERSION, '8.0.0', '>=') ? 'OK' : 'Requiere 8.0+') . '</td></tr>';
echo '<tr><td>SAPI</td><td>' . php_sapi_name() . '</td><td class="ok">Info</td></tr>';
echo '<tr><td>OS</td><td>' . PHP_OS . '</td><td class="ok">Info</td></tr>';

$exts = ['pdo_mysql', 'mbstring', 'gd', 'json', 'curl'];
foreach ($exts as $ext) {
    $loaded = extension_loaded($ext);
    echo '<tr><td>ext: ' . $ext . '</td><td>' . ($loaded ? 'Cargada' : 'No cargada') . '</td><td class="' . ($loaded ? 'ok' : 'fail') . '">' . ($loaded ? 'OK' : 'FALTA') . '</td></tr>';
}
echo '<tr><td>upload_max_filesize</td><td>' . ini_get('upload_max_filesize') . '</td><td class="ok">Info</td></tr>';
echo '<tr><td>post_max_size</td><td>' . ini_get('post_max_size') . '</td><td class="ok">Info</td></tr>';
echo '<tr><td>display_errors</td><td>' . ini_get('display_errors') . '</td><td class="ok">Info</td></tr>';
echo '</table>';

// ── 2. Rutas ──
echo '<h2>2. Rutas del servidor</h2>';
echo '<table>';
echo '<tr><td>DOCUMENT_ROOT</td><td><code>' . htmlspecialchars($_SERVER['DOCUMENT_ROOT'] ?? 'N/A') . '</code></td></tr>';
echo '<tr><td>SCRIPT_FILENAME</td><td><code>' . htmlspecialchars($_SERVER['SCRIPT_FILENAME'] ?? 'N/A') . '</code></td></tr>';
echo '<tr><td>__DIR__</td><td><code>' . htmlspecialchars(__DIR__) . '</code></td></tr>';
echo '<tr><td>dirname(__DIR__)</td><td><code>' . htmlspecialchars(dirname(__DIR__)) . '</code></td></tr>';
echo '<tr><td>SERVER_NAME</td><td><code>' . htmlspecialchars($_SERVER['SERVER_NAME'] ?? 'N/A') . '</code></td></tr>';
echo '<tr><td>REQUEST_URI</td><td><code>' . htmlspecialchars($_SERVER['REQUEST_URI'] ?? 'N/A') . '</code></td></tr>';
echo '<tr><td>SCRIPT_NAME</td><td><code>' . htmlspecialchars($_SERVER['SCRIPT_NAME'] ?? 'N/A') . '</code></td></tr>';
echo '</table>';

// ── 3. Buscar directorio privado ──
echo '<h2>3. Directorio privado</h2>';
$parentDir = dirname(__DIR__);
$privatePaths = [
    $parentDir . '/private',
    $parentDir . '/ganadera_private',
    dirname($parentDir) . '/private',
    dirname($parentDir) . '/ganadera_private',
    __DIR__ . '/../private',
    __DIR__ . '/private',
];

$foundPrivate = null;
echo '<table>';
echo '<tr><th>Ruta</th><th>Existe?</th><th>app/Core/?</th></tr>';
foreach ($privatePaths as $path) {
    $exists = is_dir($path);
    $hasApp = $exists && file_exists($path . '/app/Core/Application.php');
    if ($hasApp && !$foundPrivate) $foundPrivate = realpath($path);
    echo '<tr>';
    echo '<td><code>' . htmlspecialchars($path) . '</code></td>';
    echo '<td class="' . ($exists ? 'ok' : 'fail') . '">' . ($exists ? 'SI' : 'NO') . '</td>';
    echo '<td class="' . ($hasApp ? 'ok' : 'fail') . '">' . ($hasApp ? 'SI' : 'NO') . '</td>';
    echo '</tr>';
}
echo '</table>';

if ($foundPrivate) {
    echo '<p class="ok">Directorio privado encontrado: <code>' . htmlspecialchars($foundPrivate) . '</code></p>';
} else {
    echo '<p class="fail">NO se encontro el directorio privado. Debes subir la carpeta private/ a alguna de las rutas de arriba.</p>';
    
    // Listar contenido del padre para ayudar
    echo '<h2>3b. Contenido de dirname(__DIR__)</h2>';
    $pDir = dirname(__DIR__);
    echo '<p><code>' . htmlspecialchars($pDir) . '</code></p>';
    if (is_dir($pDir) && is_readable($pDir)) {
        $items = @scandir($pDir);
        if ($items) {
            echo '<div class="box">';
            foreach ($items as $item) {
                if ($item === '.' || $item === '..') continue;
                $full = $pDir . '/' . $item;
                $type = is_dir($full) ? '[DIR]' : '[FILE]';
                echo htmlspecialchars("$type $item") . "\n";
            }
            echo '</div>';
        }
    } else {
        echo '<p class="warn">No se puede listar el directorio padre</p>';
    }
}

// ── 4. Archivos publicos ──
echo '<h2>4. Archivos en public_html</h2>';
$publicFiles = ['index.php', '.htaccess', '.user.ini', 'install.php', 'sw.js', 'manifest.php', 'offline.html', 'clear-sw.html'];
echo '<table>';
echo '<tr><th>Archivo</th><th>Existe?</th><th>Tamano</th><th>Permisos</th></tr>';
foreach ($publicFiles as $f) {
    $full = __DIR__ . '/' . $f;
    $exists = file_exists($full);
    echo '<tr>';
    echo '<td><code>' . $f . '</code></td>';
    echo '<td class="' . ($exists ? 'ok' : 'fail') . '">' . ($exists ? 'SI' : 'NO') . '</td>';
    echo '<td>' . ($exists ? number_format(filesize($full)) . ' bytes' : '-') . '</td>';
    echo '<td>' . ($exists ? decoct(fileperms($full) & 0777) : '-') . '</td>';
    echo '</tr>';
}
echo '</table>';

// ── 5. Directorios publicos ──
echo '<h2>5. Directorios publicos</h2>';
$pubDirs = ['assets', 'assets/css', 'assets/js', 'assets/img', 'uploads', 'uploads/photos', 'uploads/evidence', 'uploads/documents'];
echo '<table>';
echo '<tr><th>Directorio</th><th>Existe?</th><th>Escribible?</th><th>Permisos</th></tr>';
foreach ($pubDirs as $d) {
    $full = __DIR__ . '/' . $d;
    $exists = is_dir($full);
    $writable = $exists && is_writable($full);
    echo '<tr>';
    echo '<td><code>' . $d . '/</code></td>';
    echo '<td class="' . ($exists ? 'ok' : 'fail') . '">' . ($exists ? 'SI' : 'NO') . '</td>';
    echo '<td class="' . ($writable ? 'ok' : 'warn') . '">' . ($writable ? 'SI' : 'NO') . '</td>';
    echo '<td>' . ($exists ? decoct(fileperms($full) & 0777) : '-') . '</td>';
    echo '</tr>';
}
echo '</table>';

// ── 6. Directorios privados ──
if ($foundPrivate) {
    echo '<h2>6. Directorios privados</h2>';
    $privDirs = ['app', 'app/Core', 'app/Controllers', 'app/Views', 'config', 'database', 'storage', 'storage/logs'];
    echo '<table>';
    echo '<tr><th>Directorio</th><th>Existe?</th><th>Escribible?</th><th>Permisos</th></tr>';
    foreach ($privDirs as $d) {
        $full = $foundPrivate . '/' . $d;
        $exists = is_dir($full);
        $writable = $exists && is_writable($full);
        echo '<tr>';
        echo '<td><code>' . $d . '/</code></td>';
        echo '<td class="' . ($exists ? 'ok' : 'fail') . '">' . ($exists ? 'SI' : 'NO') . '</td>';
        echo '<td class="' . ($writable ? 'ok' : 'warn') . '">' . ($writable ? 'SI' : 'NO') . '</td>';
        echo '<td>' . ($exists ? decoct(fileperms($full) & 0777) : '-') . '</td>';
        echo '</tr>';
    }
    echo '</table>';

    // Verificar schema.sql
    $schema = $foundPrivate . '/database/schema.sql';
    echo '<p>schema.sql: ' . (file_exists($schema) ? '<span class="ok">Existe (' . number_format(filesize($schema)) . ' bytes)</span>' : '<span class="fail">NO existe</span>') . '</p>';
    
    // Verificar installed.php
    $installed = $foundPrivate . '/config/installed.php';
    echo '<p>installed.php: ' . (file_exists($installed) ? '<span class="ok">Existe (ya instalado)</span>' : '<span class="warn">No existe (no instalado aun)</span>') . '</p>';
}

// ── 7. Apache ──
echo '<h2>7. Apache</h2>';
if (function_exists('apache_get_modules')) {
    $mods = apache_get_modules();
    $important = ['mod_rewrite', 'mod_headers', 'mod_deflate', 'mod_expires', 'mod_authz_core'];
    echo '<table>';
    foreach ($important as $m) {
        $loaded = in_array($m, $mods);
        echo '<tr><td>' . $m . '</td><td class="' . ($loaded ? 'ok' : 'warn') . '">' . ($loaded ? 'Cargado' : 'No cargado') . '</td></tr>';
    }
    echo '</table>';
} else {
    echo '<p class="warn">apache_get_modules() no disponible (PHP-FPM). mod_rewrite probablemente esta activo.</p>';
}

// ── 8. Test de .htaccess ──
echo '<h2>8. .htaccess</h2>';
$htFile = __DIR__ . '/.htaccess';
if (file_exists($htFile)) {
    $htContent = file_get_contents($htFile);
    $htSize = strlen($htContent);
    echo '<p class="ok">.htaccess existe (' . $htSize . ' bytes)</p>';
    
    // Check for UTF-8 BOM
    if (substr($htContent, 0, 3) === "\xEF\xBB\xBF") {
        echo '<p class="fail">PROBLEMA: .htaccess tiene BOM UTF-8. Esto causa error 500.</p>';
    }
    
    // Check for non-ASCII characters
    if (preg_match('/[^\x00-\x7F]/', $htContent)) {
        echo '<p class="warn">Advertencia: .htaccess contiene caracteres no-ASCII. Esto puede causar problemas en algunos servidores.</p>';
    } else {
        echo '<p class="ok">.htaccess es ASCII puro</p>';
    }
    
    echo '<p>Contenido:</p>';
    echo '<div class="box">' . htmlspecialchars($htContent) . '</div>';
} else {
    echo '<p class="fail">.htaccess NO existe. Las rutas no funcionaran.</p>';
}

// ── 9. Recomendacion ──
echo '<h2>9. Siguiente paso</h2>';
if ($foundPrivate) {
    echo '<p>El directorio privado fue encontrado. ';
    $installed = $foundPrivate . '/config/installed.php';
    if (file_exists($installed)) {
        echo '<span class="ok">El sistema ya esta instalado.</span> <a href="/" style="color:#4ecdc4">Ir a la app</a></p>';
    } else {
        echo '<a href="install.php" style="color:#4ecdc4;font-weight:bold">Ejecutar el instalador &rarr;</a></p>';
    }
} else {
    echo '<p class="fail">Sube la carpeta <code>private/</code> del deploy al servidor.</p>';
    echo '<p>Debe quedar en alguna de estas rutas:</p><ul>';
    foreach ($privatePaths as $p) {
        echo '<li><code>' . htmlspecialchars($p) . '</code></li>';
    }
    echo '</ul>';
}

echo '<p style="margin-top:2em;color:#ff6b6b;font-weight:bold">Elimina este archivo (diagnostico.php) cuando termines.</p>';
?>
</div>
</body>
</html>
