<?php
// Base directory (current directory)
$baseDir = __DIR__;
$baseRealPath = realpath($baseDir);

// Get current folder
$currentFolder = isset($_GET['folder']) ? urldecode($_GET['folder']) : '';
$currentPath = realpath($baseDir . '/' . $currentFolder);

// Security check for browsing
if ($currentPath === false || strpos($currentPath, $baseRealPath) !== 0) {
    die("Access denied.");
}

// ==============================
// DOWNLOAD FILE (STREAM SAFE)
// ==============================
if (isset($_GET['download'])) {

    $downloadPath = urldecode($_GET['download']);
    $file = realpath($baseDir . '/' . $downloadPath);

    // Security validation
    if ($file === false || strpos($file, $baseRealPath) !== 0 || !is_file($file)) {
        die("Invalid file.");
    }

    // Clear output buffers
    if (ob_get_level()) {
        ob_end_clean();
    }

    // Prevent timeout
    set_time_limit(0);

    $filesize = filesize($file);
    $filename = basename($file);

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . $filesize);
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Expires: 0');

    $chunkSize = 1024 * 1024; // 1MB chunks
    $handle = fopen($file, 'rb');

    if ($handle === false) {
        die("Cannot open file.");
    }

    while (!feof($handle)) {
        echo fread($handle, $chunkSize);
        flush();
    }

    fclose($handle);
    exit;
}

$items = scandir($currentPath);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Storage File Manager</title>
<style>
body {
    font-family: Arial, sans-serif;
    background: #f4f6f9;
    margin: 0;
    padding: 40px;
}

.container {
    max-width: 1100px;
    margin: auto;
}

h1 {
    text-align: center;
    color: #333;
}

.file-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 20px;
    margin-top: 30px;
}

.card {
    background: white;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    transition: 0.3s;
}

.card:hover {
    transform: translateY(-5px);
}

.folder {
    color: #007bff;
    font-weight: bold;
}

.file {
    color: #333;
    word-break: break-word;
}

.size {
    font-size: 13px;
    color: #888;
    margin-top: 5px;
}

.button {
    display: inline-block;
    margin-top: 12px;
    padding: 8px 14px;
    border-radius: 6px;
    text-decoration: none;
    font-size: 14px;
}

.download-btn {
    background: #28a745;
    color: white;
}

.download-btn:hover {
    background: #218838;
}

.folder-btn {
    background: #007bff;
    color: white;
}

.folder-btn:hover {
    background: #0056b3;
}

.back {
    margin-bottom: 20px;
    display: inline-block;
    text-decoration: none;
    color: #555;
}
</style>
</head>

<body>
<div class="container">
    <h1>📁 Storage File Manager</h1>

    <?php if ($currentFolder != ''): ?>
        <a class="back" href="?folder=<?php echo urlencode(dirname($currentFolder)); ?>">⬅ Back</a>
    <?php endif; ?>

    <div class="file-grid">
        <?php foreach ($items as $item): ?>
            <?php if ($item == '.' || $item == '..') continue; ?>

            <?php
            $itemPath = $currentPath . '/' . $item;
            $relativePath = ltrim($currentFolder . '/' . $item, '/');
            ?>

            <div class="card">
                <?php if (is_dir($itemPath)): ?>
                    <div class="folder">📂 <?php echo htmlspecialchars($item); ?></div>
                    <a class="button folder-btn" href="?folder=<?php echo urlencode($relativePath); ?>">Open</a>
                <?php else: ?>
                    <div class="file">📄 <?php echo htmlspecialchars($item); ?></div>
                    <div class="size">
                        <?php echo round(filesize($itemPath) / 1024 / 1024, 2); ?> MB
                    </div>
                    <a class="button download-btn" href="?download=<?php echo urlencode($relativePath); ?>">Download</a>
                <?php endif; ?>
            </div>

        <?php endforeach; ?>
    </div>
</div>
</body>
</html>