<?php
// ===== CONFIG =====
$baseDir = realpath(__DIR__);

// wallpapers
$wallpapers = glob(__DIR__ . "/apache-theme/wallpapers/*.{jpg,jpeg,png}", GLOB_BRACE);
$bg = str_replace(__DIR__, '', $wallpapers[array_rand($wallpapers)]);

// ===== ROUTING =====
$requestUri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
$path = realpath($baseDir . $requestUri);

// seguridad básica
if ($path === false || strpos($path, $baseDir) !== 0) {
    http_response_code(403);
    die("403 Forbidden");
}

// si es archivo, servirlo directo
if (is_file($path)) {
    header("Content-Type: " . mime_content_type($path));
    readfile($path);
    exit;
}

// ===== LISTADO =====
$files = scandir($path);
$files = array_diff($files, ['.', '..']);

// ordenar: carpetas primero
usort($files, function($a, $b) use ($path) {
    return (is_dir("$path/$b") - is_dir("$path/$a")) ?: strcasecmp($a, $b);
});

// ===== HELPERS =====
function humanSize($bytes) {
    $units = ['B','KB','MB','GB','TB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units)-1) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, 1) . ' ' . $units[$i];
}

// breadcrumbs
function breadcrumbs($uri) {
    $parts = explode('/', trim($uri, '/'));
    $path = '';
    $crumbs = ['<a href="/">/</a>'];

    foreach ($parts as $part) {
        if ($part === '') continue;
        $path .= '/' . $part;
        $crumbs[] = '<a href="' . $path . '/">' . htmlspecialchars($part) . '</a>';
    }

    return implode(' / ', $crumbs);
}

function fileClass($path, $isDir) {
    if ($isDir) return 'dir';

    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));

    $images = ['jpg','jpeg','png','gif','webp','bmp','svg'];
    $media = ['mp4','mkv','webm','avi','mov','mp3','ogg'];
    $archives = ['zip','rar','7z','tar','gz','bz2','xz'];

    if (in_array($ext, $images)) return 'image';
    if (in_array($ext, $media)) return 'media';
    if (in_array($ext, $archives)) return 'archive';

    return 'file';
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index of <?php echo htmlspecialchars($requestUri); ?></title>
<link rel="stylesheet" href="/apache-theme/style.css">
</head>

<body style="background-image: url('<?php echo $bg; ?>')">
<div class="container">

<h1><span class="whoami">you@edmateos-headquarters</span> <?php echo breadcrumbs($requestUri); ?></h1>
<hr color="fbf1c7">

<table>
<tr class="indexhead">
    <th>Name</th>
    <th>Last modified</th>
    <th>Size</th>
</tr>

<?php if ($requestUri !== '/'): ?>
<tr class="dir">
    <td class="name-cell"><a href="../">..</a></td>
    <td>-</td>
    <td>-</td>
</tr>
<?php endif; ?>

<?php foreach ($files as $file):
    $fullPath = $path . '/' . $file;
    $isDir = is_dir($fullPath);
?>
<tr class="<?php echo fileClass($fullPath, $isDir); ?>">
    <td class="name-cell">
        <a href="<?php echo htmlspecialchars($file) . ($isDir ? '/' : ''); ?>">
            <?php echo htmlspecialchars($file) . ($isDir ? '/' : ''); ?>
        </a>
    </td>
    <td><?php echo date("Y-m-d H:i", filemtime($fullPath)); ?></td>
    <td><?php echo $isDir ? '-' : humanSize(filesize($fullPath)); ?></td>
</tr>
<?php endforeach; ?>

</table>

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