<?php
// Simple PHP File Manager with Folder Download

$baseDir = __DIR__; // Root directory
$path = realpath($baseDir . '/' . ($_GET['dir'] ?? ''));

// Security: prevent directory traversal
if (strpos($path, $baseDir) !== 0) {
    die("Access denied");
}

// Download a folder as ZIP
if (isset($_GET['download_folder'])) {
    $folder = realpath($path . '/' . $_GET['download_folder']);
    if (strpos($folder, $baseDir) !== 0) die("Access denied");

    $zipname = basename($folder) . ".zip";
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);

    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($files as $file) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($folder) + 1);

        if ($file->isDir()) {
            $zip->addEmptyDir($relativePath);
        } else {
            $zip->addFile($filePath, $relativePath);
        }
    }

    $zip->close();

    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zipname . '"');
    readfile($zipname);
    unlink($zipname);
    exit;
}

// Download a single file
if (isset($_GET['download'])) {
    $file = realpath($path . '/' . $_GET['download']);
    if (strpos($file, $baseDir) !== 0 || !is_file($file)) die("Access denied");

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    readfile($file);
    exit;
}

// List directory contents
$items = scandir($path);
?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP File Manager</title>
    <style>
        body { font-family: Arial; padding: 20px; }
        a { text-decoration: none; }
    </style>
</head>
<body>
<h2>File Manager</h2>
<p>Current directory: <strong><?= htmlspecialchars($path) ?></strong></p>

<ul>
<?php if ($path !== $baseDir): ?>
    <li><a href="?dir=<?= urlencode(dirname($_GET['dir'] ?? '')) ?>">⬅️ Up</a></li>
<?php endif; ?>

<?php foreach ($items as $item): 
    if ($item === "." || $item === "..") continue;
    $full = $path . '/' . $item;
?>
    <li>
        <?php if (is_dir($full)): ?>
            📁 <a href="?dir=<?= urlencode(trim(($_GET['dir'] ?? '') . '/' . $item, '/')) ?>">
                <?= htmlspecialchars($item) ?>
            </a>
            — <a href="?dir=<?= urlencode($_GET['dir'] ?? '') ?>&download_folder=<?= urlencode($item) ?>">Download Folder</a>
        <?php else: ?>
            📄 <?= htmlspecialchars($item) ?>
            — <a href="?dir=<?= urlencode($_GET['dir'] ?? '') ?>&download=<?= urlencode($item) ?>">Download</a>
        <?php endif; ?>
    </li>
<?php endforeach; ?>
</ul>

</body>
</html>
