<?php
// --- دریافت مسیر درخواستی (پارامتر dir یا آدرس) ---
if (isset($_GET['dir'])) {
    $request_path = '/' . trim($_GET['dir'], '/');
} else {
    $request_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
}
$request_path = rtrim($request_path, '/');
if ($request_path === '') $request_path = '/';

// --- امنیت: مسیر نباید فایل باشد؛ اگر فایل بود، ریشه نشون بده ---
$doc_root = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
if (is_file($doc_root . $request_path)) {
    $request_path = '/';
}

// --- مسیر واقعی روی سرور ---
$target_dir = realpath($doc_root . $request_path);
if ($target_dir === false || strpos($target_dir, realpath($doc_root)) !== 0 || !is_dir($target_dir)) {
    http_response_code(404);
    die('<h1 style="font-size:2rem;text-align:center;margin-top:50px;">⛔ پوشه پیدا نشد</h1>');
}

// --- اسکن محتویات ---
$exclude = ['.', '..', 'index.php', '.htaccess'];
$items = scandir($target_dir);
$folders = [];
$files = [];

foreach ($items as $item) {
    if (in_array($item, $exclude)) continue;
    $item_path = $target_dir . '/' . $item;
    $item_url = ($request_path === '/' ? '/' . $item : $request_path . '/' . $item);
    if (is_dir($item_path)) {
        $folders[] = ['name' => $item, 'url' => $item_url . '/', 'size' => '-'];
    } else {
        $files[] = ['name' => $item, 'url' => $item_url, 'size' => filesize($item_path)];
    }
}

// مرتب‌سازی: پوشه‌ها اول، فایل‌ها بعد (هر دو بر اساس نام)
usort($folders, function($a, $b) { return strcasecmp($a['name'], $b['name']); });
usort($files, function($a, $b) { return strcasecmp($a['name'], $b['name']); });
$all = array_merge($folders, $files);

// تبدیل سایز
function fmt($bytes) {
    if ($bytes === '-') return '-';
    if ($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024) return round($bytes / 1024, 2) . ' KB';
    return $bytes . ' B';
}
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>فهرست <?= htmlspecialchars($request_path) ?></title>
    <style>
        body {
            font-family: Tahoma, sans-serif;
            font-size: 1.4rem; /* 30% کوچکتر از 2rem */
            background: #f5f5f5;
            color: #333;
            padding: 25px;
            margin: 0;
        }
        h2 {
            font-size: 1.68rem; /* 30% کوچکتر از 2.4rem */
            margin: 0 0 20px 0;
        }
        a {
            text-decoration: none;
            color: #0066cc;
        }
        a:hover {
            color: #004499;
            text-decoration: underline;
        }
        .size {
            font-size: 0.98rem; /* 30% کوچکتر از 1.4rem */
            color: #666;
            margin-right: 20px;
        }
        #searchBox {
            width: 100%;
            padding: 12px;
            font-size: 1.26rem; /* 30% کوچکتر از 1.8rem */
            margin-bottom: 25px;
            box-sizing: border-box;
            border: 2px solid #ccc;
            border-radius: 8px;
        }
        .item {
            margin: 15px 0;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>

<h2>📁 <?= htmlspecialchars($request_path) ?></h2>

<!-- جعبه جستجو -->
<input type="text" id="searchBox" placeholder="🔍 جستجو..." autofocus>

<div id="listContainer">
    <?php foreach ($all as $item): ?>
        <?php
            $icon = ($item['url'][strlen($item['url'])-1] === '/') ? '📁' : '📄';
            $escName = htmlspecialchars($item['name']);
            $escUrl = htmlspecialchars($item['url']);
        ?>
        <div class="item" data-name="<?= $escName ?>">
            <?= $icon ?> <a href="<?= $escUrl ?>"><?= $escName ?></a>
            <span class="size"><?= fmt($item['size']) ?></span>
        </div>
    <?php endforeach; ?>
    <?php if (empty($all)): ?>
        <p>📭 این پوشه خالی است.</p>
    <?php endif; ?>
</div>

<script>
// جستجوی ساده و فوری بدون هیچ کتابخانه‌ای
(function() {
    var searchBox = document.getElementById('searchBox');
    var items = document.querySelectorAll('.item');

    searchBox.addEventListener('input', function() {
        var filter = this.value.trim().toLowerCase();
        items.forEach(function(item) {
            var name = item.getAttribute('data-name').toLowerCase();
            if (name.indexOf(filter) !== -1) {
                item.classList.remove('hidden');
            } else {
                item.classList.add('hidden');
            }
        });
    });
})();
</script>

</body>
</html>