<?php
/**
 * Simple PHP File Browser
 * Muestra un listado tipo "Index Of" seguro y limpio.
 */

// CONFIGURACIÓN
// -------------------------------------------------------
// Directorio base: donde está este script.
$base_dir = __DIR__; 

// Obtener el directorio actual de la URL, o usar el base por defecto
$current_dir = isset($_GET['dir']) ? $_GET['dir'] : '';

// SEGURIDAD: PREVENCIÓN DE DIRECTORY TRAVERSAL
// -------------------------------------------------------
// Construimos la ruta real
$path = realpath($base_dir . '/' . $current_dir);

// Verificamos que la ruta resultante siga estando dentro del directorio base
// y que el directorio exista.
if ($path === false || strpos($path, $base_dir) !== 0 || !is_dir($path)) {
    die("Error: Ruta inválida o acceso denegado.");
}

// Calcular la ruta relativa para mostrar en la interfaz
$relative_path = substr($path, strlen($base_dir));
$relative_path = $relative_path ? $relative_path : '/';

// FUNCIONES AUXILIARES
// -------------------------------------------------------
function formatSize($bytes) {
    if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576)    return number_format($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024)       return number_format($bytes / 1024, 2) . ' KB';
    return $bytes . ' bytes';
}

// OBTENER ARCHIVOS Y CARPETAS
// -------------------------------------------------------
$items = scandir($path);
$folders = [];
$files = [];

foreach ($items as $item) {
    if ($item == '.' || $item == 'index.php') continue; // Ocultar este script y el punto
    if ($item == '..' && $relative_path == '/') continue; // Ocultar '..' en la raíz

    $full_path = $path . '/' . $item;
    $item_data = [
        'name' => $item,
        'path' => ltrim($relative_path . '/' . $item, '/'),
        'date' => date("Y-m-d H:i:s", filemtime($full_path))
    ];

    if (is_dir($full_path)) {
        $folders[] = $item_data;
    } else {
        $item_data['size'] = formatSize(filesize($full_path));
        $files[] = $item_data;
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Índice de <?php echo htmlspecialchars($relative_path); ?></title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
        .container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); border-radius: 8px; }
        h1 { font-size: 20px; margin-bottom: 20px; border-bottom: 1px solid #eee; padding-bottom: 10px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { text-align: left; padding: 12px; border-bottom: 1px solid #eee; }
        th { background-color: #fafafa; font-weight: 600; }
        tr:hover { background-color: #f9f9f9; }
        a { text-decoration: none; color: #007bff; }
        a:hover { text-decoration: underline; }
        .icon { margin-right: 8px; width: 20px; display: inline-block; text-align: center; }
        .meta { color: #888; font-size: 0.9em; }
    </style>
</head>
<body>

<div class="container">
    <h1>Índice de: <?php echo htmlspecialchars($relative_path); ?></h1>

    <table>
        <thead>
            <tr>
                <th>Nombre</th>
                <th>Tamaño</th>
                <th>Última Modificación</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($relative_path != '/'): ?>
            <tr>
                <td>
                    <span class="icon">⬆️</span>
                    <a href="?dir=<?php echo urlencode(dirname($relative_path)); ?>">Directorio Superior</a>
                </td>
                <td>-</td>
                <td>-</td>
            </tr>
            <?php endif; ?>

            <?php foreach ($folders as $folder): ?>
            <tr>
                <td>
                    <span class="icon">📁</span>
                    <a href="?dir=<?php echo urlencode($folder['path']); ?>">
                        <?php echo htmlspecialchars($folder['name']); ?>
                    </a>
                </td>
                <td class="meta">-</td>
                <td class="meta"><?php echo $folder['date']; ?></td>
            </tr>
            <?php endforeach; ?>

            <?php foreach ($files as $file): ?>
            <tr>
                <td>
                    <span class="icon">📄</span>
                    <a href="<?php echo htmlspecialchars($file['path']); ?>" target="_blank">
                        <?php echo htmlspecialchars($file['name']); ?>
                    </a>
                </td>
                <td class="meta"><?php echo $file['size']; ?></td>
                <td class="meta"><?php echo $file['date']; ?></td>
            </tr>
            <?php endforeach; ?>

            <?php if (empty($folders) && empty($files)): ?>
            <tr>
                <td colspan="3" style="text-align:center; color: #999;">Carpeta vacía</td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

</body>
</html>