<?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));
$requested = $baseDir . $requestUri;

// existe?
if (!file_exists($requested)) {
    http_response_code(404);
    die("404 Not Found");
}

// resolver ruta real (sigue symlinks)
$real = realpath($requested);

// rutas permitidas (ajusta esto a tu caso)
$allowedRoots = [
    realpath('/srv/files/public'),
    realpath('/srv/radio/tracks'),
];

$allowed = false;

// si realpath funciona, validamos contra roots
if ($real !== false) {
    foreach ($allowedRoots as $root) {
        if ($root && strpos($real, $root) === 0) {
            $allowed = true;
            break;
        }
    }
}

// si es symlink pero realpath falló, igual permitir (casos raros)
if (!$allowed && is_link($requested)) {
    $allowed = true;
}

// bloqueo final
if (!$allowed) {
    http_response_code(403);
    die("403 Forbidden");
}

// decidir path final
$path = $real !== false ? $real : $requested;

// 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, ['.', '..']);

$files = array_filter($files, function($file) {
    return $file[0] !== '.';
});

// 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 = array_filter(explode('/', trim($uri, '/')));
    $path = '';

    $rootLabel = 'files';
    $html = '<a href="/">' . $rootLabel . '</a>';

    $lastIndex = count($parts) - 1;
    $i = 0;

    foreach ($parts as $part) {
        $path .= '/' . $part;

        $html .= '/';

        if ($i === $lastIndex) {
            // último → texto plano
            $html .= '<span class="current">' . htmlspecialchars($part) . '</span>';
        } else {
            // anteriores → link
            $html .= '<a href="' . $path . '/">' . htmlspecialchars($part) . '</a>';
        }

        $i++;
    }

    return $html;
}

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">

<h2 class="pwd"><span class="whoami">sumerce@edmateos-headquarters</span> <?php echo breadcrumbs($requestUri); ?></h2>
<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>
