<?php
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set('Asia/Tehran');

// مسیر فعلی
$currentPath = realpath(__DIR__);
$target = isset($_GET['path']) ? $_GET['path'] : '';
$fullPath = realpath($currentPath . '/' . $target);

// جلوگیری از خروج از مسیر اصلی
if ($fullPath === false || strpos($fullPath, $currentPath) !== 0) {
    die("دسترسی غیرمجاز");
}

$items = scandir($fullPath);

// Human-readable file size
function fileSizeNice($bytes) {
    $sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.2f %s", $bytes / pow(1024, $factor), $sizes[$factor]);
}

// تشخیص انواع فایل
function isVideo($file) {
    return in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), 
    ['mp4','webm','mkv','mov','m4v']);
}

function isAudio($file) {
    return in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), 
    ['mp3','wav','ogg','m4a']);
}

?>
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<title>مرکز فایل</title>
<style>
body { font-family:tahoma; background:#f7f7f7; padding:20px; direction:rtl; }
.container { max-width:900px; margin:auto; background:white; padding:25px; border-radius:12px; }
.item { background:#eee; padding:15px; margin:12px 0; border-radius:8px; }
a { color:#0044cc; text-decoration:none; }
</style>
</head>
<body>

<div class="container">

<h2>📁 مدیریت فایل‌ها</h2>

<?php
// دکمه بازگشت
if ($target !== '') {
    $back = dirname($target);
    if ($back == '.') $back = '';
    echo "<div class='item'><a href='?path=$back'>⬅ بازگشت</a></div>";
}

// ----------------------
// نمایش فولدرها
// ----------------------
foreach ($items as $i) {
    if ($i == "." || $i == "..") continue;

    $p = $fullPath . '/' . $i;

    if (is_dir($p)) {
        $newPath = ($target !== '' ? $target.'/' : '') . $i;
        echo "<div class='item'>📂 <a href='?path=" . urlencode($newPath) . "'>$i</a></div>";
    }
}

// ----------------------
// نمایش فایل‌ها
// ----------------------
foreach ($items as $i) {
    if ($i == "." || $i == "..") continue;

    $p = $fullPath . '/' . $i;

    if (is_file($p)) {

        // مسیر واقعی
        $fileUrl = ($target !== '' ? $target.'/' : '') . $i;

        // encode صحیح
        $fileUrlEncoded = implode('/', array_map('rawurlencode', explode('/', $fileUrl)));

        $size = fileSizeNice(filesize($p));

        echo "<div class='item'>";
        echo "📄 $i <br>";
        echo "<small>حجم: $size</small><br><br>";

        if (isVideo($i) || isAudio($i)) {
            echo "<a href='player.php?file=" . urlencode($fileUrlEncoded) . "'>▶ پخش آنلاین</a><br>";
        }

        echo "<a href='download.php?file=" . urlencode($fileUrl) . "'>⬇ دانلود</a>";

        echo "</div>";
    }
}
?>

</div>
</body>
</html>
