<?php
session_start();
require_once "../config.php";

if (!isset($_SESSION['user_id'])) {
    die("Not logged in.");
}

$root = "../userfiles/" . $_SESSION['user_id'] . "/";
if (!is_dir($root)) mkdir($root, 0777, true);

$path = $_GET['path'] ?? "";
$full = realpath($root . $path);

if (!$full || strpos($full, realpath($root)) !== 0) {
    die("Invalid path.");
}

$items = scandir($full);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Manager</title>
<style>
    body { background:#111; color:white; font-family:Arial; margin:0; padding:10px; }
    a { color:#0ff; text-decoration:none; }
    .item { padding:6px; border-bottom:1px solid #333; }
</style>
</head>
<body>

<h2>📁 File Manager</h2>
<p>Current: <?= htmlspecialchars($path ?: "/") ?></p>

<?php if ($path): ?>
    <div class="item">
        <a href="?path=<?= urlencode(dirname($path)) ?>">⬅️ Up</a>
    </div>
<?php endif; ?>

<?php foreach ($items as $i): ?>
    <?php if ($i === "." || $i === "..") continue; ?>
    <?php $isDir = is_dir($full . "/" . $i); ?>
    <div class="item">
        <?php if ($isDir): ?>
            <a href="?path=<?= urlencode(trim($path . "/" . $i, "/")) ?>">📁 <?= $i ?></a>
        <?php else: ?>
            📄 <?= $i ?>
        <?php endif; ?>
    </div>
<?php endforeach; ?>

</body>
</html>