<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('max_execution_time', 20);

function formatBytes($bytes, $decimals = 2): string {
  if ($bytes === false) return 'N/A';
  $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  $i = 0;

  $bytes = (float)$bytes;
  while ($bytes >= 1024 && $i < count($units) - 1) {
    $bytes /= 1024;
    $i++;
  }
  return number_format($bytes, $decimals, '.', ',') . ' ' . $units[$i];
}

$reqPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$scriptDir = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'])), '/');
if ($scriptDir !== '' && $scriptDir !== '.') {
  if ($scriptDir !== '/' && str_starts_with($reqPath, $scriptDir)) {
    $reqPath = substr($reqPath, strlen($scriptDir));
  }
}

$reqPath = '/' . ltrim($reqPath, '/');

$targetPath = ($reqPath === '/' || $reqPath === '')
  ? __DIR__
  : __DIR__ . $reqPath;

$targetPath = rtrim(str_replace('\\','/',$targetPath), '/');

$realTarget = realpath($targetPath);
$realRoot   = realpath(__DIR__);

if ($realTarget === false || $realRoot === false || !str_starts_with($realTarget, $realRoot)) {
  http_response_code(403);
  echo "Access denied.";
  exit;
}

$title = "Files Directory: " . htmlspecialchars($reqPath, ENT_QUOTES, 'UTF-8');

$ignore = array('.', '..', 'index.php', '.htaccess', '.DS_Store');

$items = [];
foreach (scandir($realTarget) as $name) {
  if (in_array($name, $ignore, true)) continue;
  $items[] = $name;
}
?>
<!doctype html>
<html lang="fa" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></title>
  <style>
    body { font-family: Arial, sans-serif; background:#f0f2f5; padding:40px; color:#333; direction:ltr; text-align:left; }
    .container { max-width: 900px; margin:auto; background:#fff; padding:24px; border-radius:14px; box-shadow:0 4px 15px rgba(0,0,0,0.08); }
    h1 { margin: 0 0 14px; color:#0f62fe; border-bottom:2px solid #0f62fe; padding-bottom:10px; }
    ul { list-style:none; padding:0; margin:0; }
    li { border-bottom:1px solid #eee; }
    a { display:flex; align-items:center; gap:10px; padding:12px 2px; text-decoration:none; color:#111; font-weight:600; }
    a:hover { color:#0f62fe; }
    .icon { width:28px; text-align:center; font-size:20px; }
    .size { margin-inline-start:auto; font-weight:700; color:#0f62fe; }
  </style>
</head>
<body>
<div class="container">
  <h1><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></h1>

  <ul>
    <?php foreach ($items as $name): ?>
      <?php
        $full = $realTarget . DIRECTORY_SEPARATOR . $name;
        $isDir = is_dir($full);
        $icon = $isDir ? '📁' : '📄';

        $sizeText = '';
        if (!$isDir) {
          $sizeText = formatBytes(filesize($full));
        }

        $base = rtrim($_SERVER['REQUEST_URI'], '/');
        $href = $base . '/' . rawurlencode($name);
        if ($isDir) $href .= '/';
      ?>
      <li>
        <a href="<?= htmlspecialchars($href, ENT_QUOTES, 'UTF-8') ?>">
          <span class="icon"><?= $icon ?></span>
          <span><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></span>
          <?php if ($sizeText !== ''): ?>
            <span class="size"><?= htmlspecialchars($sizeText, ENT_QUOTES, 'UTF-8') ?></span>
          <?php endif; ?>
        </a>
      </li>
    <?php endforeach; ?>
  </ul>
</div>
</body>
</html>
