<?php
// index.php — ملف واحد لعرض شجرة الملفات مع دعم العربية (UTF-8)
// ملاحظات:
// - ضع الملف في المجلد الجذر الذي تريد عرضه.
// - يدعم عرض/تحميل الملفات مع حماية من الخروج خارج المجلد.
// - يعرض الأسماء العربية كما هي، ويشفر الروابط بشكل آمن.

// إعدادات الترميز ودعم العربية
header('Content-Type: text/html; charset=UTF-8');
@ini_set('default_charset', 'UTF-8');
@mb_internal_encoding('UTF-8');

// المسار الجذري الذي يُسمح بالوصول ضمنه فقط
const BASE_DIR = __DIR__;
$BASE_REAL = realpath(BASE_DIR);

// دوال مساعدة
function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function enc_path_for_url(string $rel): string {
    // ترميز كل جزء من المسار بشكل مستقل
    $parts = $rel === '' ? [] : preg_split('#/#', $rel, -1, PREG_SPLIT_NO_EMPTY);
    $parts = array_map('rawurlencode', $parts);
    return implode('/', $parts);
}
function secure_realpath(string $rel): string {
    $candidate = realpath(BASE_DIR . DIRECTORY_SEPARATOR . $rel);
    global $BASE_REAL;
    if ($candidate === false || strpos($candidate, $BASE_REAL) !== 0) {
        http_response_code(400);
        exit('Invalid path');
    }
    return $candidate;
}
function is_hidden(string $name): bool {
    // إخفاء العناصر التي تبدأ بنقطة (اختياري)
    return $name !== '.' && $name !== '..' && str_starts_with($name, '.');
}

// إجراءات العرض/التحميل للملفات
if (isset($_GET['view'])) {
    $rel = ltrim((string)$_GET['view'], '/');
    $abs = secure_realpath($rel);
    if (!is_file($abs)) { http_response_code(404); exit('File not found'); }
    $mime = function_exists('mime_content_type') ? mime_content_type($abs) : 'application/octet-stream';
    header('Content-Type: ' . $mime);
    header('Content-Disposition: inline; filename*=UTF-8\'' . rawurlencode(basename($abs)));
    header('X-Content-Type-Options: nosniff');
    readfile($abs);
    exit;
}
if (isset($_GET['download'])) {
    $rel = ltrim((string)$_GET['download'], '/');
    $abs = secure_realpath($rel);
    if (!is_file($abs)) { http_response_code(404); exit('File not found'); }
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename*=UTF-8\'' . rawurlencode(basename($abs)));
    header('X-Content-Type-Options: nosniff');
    readfile($abs);
    exit;
}

// توليد شجرة المجلدات
function list_dir_recursive(string $base, string $rel = ''): array {
    $abs = $rel ? $base . DIRECTORY_SEPARATOR . $rel : $base;
    $items = @scandir($abs, SCANDIR_SORT_NONE) ?: [];

    $dirs = [];
    $files = [];
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        if (is_hidden($item)) continue; // يمكن التعطيل بإزالة هذا السطر
        $pathRel = $rel === '' ? $item : $rel . '/' . $item;
        $pathAbs = $abs . DIRECTORY_SEPARATOR . $item;
        if (is_dir($pathAbs)) { $dirs[] = $pathRel; } else { $files[] = $pathRel; }
    }
    // ترتيب طبيعي (غير حساس لحالة الأحرف)
    natcasesort($dirs);
    natcasesort($files);

    return [array_values($dirs), array_values($files)];
}

function render_tree(string $rel = ''): void {
    [$dirs, $files] = list_dir_recursive(BASE_DIR, $rel);
    echo "<ul>\n";
    // المجلدات أولاً
    foreach ($dirs as $d) {
        $name = basename($d);
        $id = 'dir_' . md5($d);
        echo '<li class="dir">';
        echo '<span class="toggle" data-target="' . h($id) . '">📁 ' . h($name) . "</span> ";
        echo '<a class="open-link" href="?p=' . enc_path_for_url($d) . '">[فتح]</a>';
        echo '<div id="' . h($id) . '" class="children">';
        render_tree($d);
        echo "</div>";
        echo "</li>\n";
    }
    // الملفات
    foreach ($files as $f) {
        $name = basename($f);
        $view = '?view=' . enc_path_for_url($f);
        $down = '?download=' . enc_path_for_url($f);
        echo '<li class="file">📄 ' . h($name) . ' <a href="' . $view . '">[عرض]</a> <a href="' . $down . '">[تحميل]</a></li>' . "\n";
    }
    echo "</ul>\n";
}

// إذا تم تحديد p: اعرض محتويات هذا المجلد في لوحة منفصلة
$currentRel = '';
if (isset($_GET['p'])) {
    $currentRel = ltrim((string)$_GET['p'], '/');
    secure_realpath($currentRel); // تحقق فقط
}

// حساب معلومات عامة
function dir_size_and_count(string $dir): array {
    $totalSize = 0; $count = 0; $dirs = 0;
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($it as $item) {
        if ($item->isDir()) { $dirs++; continue; }
        $count++;
        $totalSize += $item->getSize();
    }
    return [$totalSize, $count, $dirs];
}
[$totalBytes, $filesCount, $dirsCount] = dir_size_and_count(BASE_DIR);
function human_bytes(int $b): string {
    $u = ['B','KB','MB','GB','TB']; $i = 0;
    while ($b >= 1024 && $i < count($u)-1) { $b/=1024; $i++; }
    return number_format($b, $b < 10 && $i>0 ? 2 : 0) . ' ' . $u[$i];
}

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>مركز حماية لحقوق الانسان — شجرة الملفات</title>
<style>
    :root { --bg:#0b1320; --card:#111a2c; --muted:#8794ad; --accent:#00c2a8; --txt:#e6edf3; }
    *{box-sizing:border-box}
    body{margin:0;font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cairo,Noto Sans Arabic,Arial,sans-serif;background:var(--bg);color:var(--txt)}
    header{padding:18px 22px;border-bottom:1px solid #1f2a44;background:linear-gradient(180deg,#0f1b31,#0b1320)}
    h1{margin:0;font-size:22px;letter-spacing:.3px}
    .sub{color:var(--muted);font-size:13px;margin-top:6px}
    .wrap {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 14px;
  padding: 14px;
}

/* 🟢 تجاوب للجوال والأجهزة الصغيرة */
@media (max-width: 800px) {
  .wrap {
    grid-template-columns: 1fr;
    padding: 10px;
  }
  .panel {
    min-height: auto;
  }
  header h1 {
    font-size: 18px;
  }
  header .sub {
    font-size: 12px;
  }
  form {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  form input {
    width: 100% !important;
  }
  form button {
    width: 100%;
  }
}

    .panel{background:var(--card);border:1px solid #1f2a44;border-radius:14px;overflow:auto;min-height:70vh}
    .panel h2{margin:0;padding:14px 16px;border-bottom:1px solid #1f2a44;font-size:15px;color:#bcd3ff}
    .tree{padding:10px 16px}
    ul{list-style:none;margin:0;padding-inline-start:16px}
    li{margin:4px 0;line-height:1.7}
    .dir>.toggle{cursor:pointer;user-select:none}
    .children{margin:6px 0 6px 0;border-inline-start:2px dashed #233355;padding-inline-start:10px;display:none}
    .dir.open>.children{display:block}
    a{color:var(--accent);text-decoration:none}
    a:hover{text-decoration:underline}
    .stats{display:flex;gap:14px;flex-wrap:wrap;padding:10px 16px;color:#c7d3ea}
    .pill{background:#0d223e;border:1px solid #1f2a44;border-radius:999px;padding:6px 10px;font-size:12px}
    .crumbs{padding:10px 16px;border-bottom:1px solid #1f2a44;color:#c7d3ea}
    .crumbs a{color:#a6ffe6}
    .file{color:#dfe7ff}
    .open-link{font-size:12px;margin-inline-start:6px;color:#9ee7ff}
    .footer{padding:10px 16px;border-top:1px solid #1f2a44;color:#90a0bf;font-size:12px}
    .notice{background:#0d223e;padding:10px 12px;margin:10px 16px;border:1px solid #1f2a44;border-radius:10px;color:#a9c1ff}
</style>
</head>
<body>
<header>
  <h1>مركز حماية لحقوق الانسان</h1>
  <div class="sub">عارض شجرة الملفات — يدعم العربية بالكامل ويتيح عرض/تحميل الملفات بأمان</div>
</header>
<form method="get" style="padding:10px 16px;background:#0d223e;border-bottom:1px solid #1f2a44;">
  🔍 <input type="text" name="q" value="<?=h($_GET['q'] ?? '')?>" placeholder="ابحث عن ملف أو مجلد..." 
     style="padding:6px 10px;border-radius:6px;border:1px solid #1f2a44;background:#111a2c;color:#fff;width:60%;">
  <button type="submit" style="padding:6px 10px;border-radius:6px;border:1px solid #1f2a44;background:#00c2a8;color:#000;font-weight:bold;">بحث</button>
</form>
<?php if (isset($_GET['q']) && $_GET['q'] !== ''): ?>

<!-- 🟢 عند وجود بحث: عرض النتائج بعرض الصفحة -->
<div class="wrap" style="display:block;padding:14px;">
  <section class="panel" style="width:100%;">
    <h2>نتائج البحث</h2>
    <?php
      $query = mb_strtolower(trim($_GET['q']));

      // دالة البحث
      function search_names(string $base, string $rel = '', string $q = ''): array {
          $abs = $rel ? $base . DIRECTORY_SEPARATOR . $rel : $base;
          $items = @scandir($abs, SCANDIR_SORT_NONE) ?: [];
          $results = [];
          foreach ($items as $item) {
              if ($item === '.' || $item === '..' || is_hidden($item)) continue;
              $pathRel = $rel === '' ? $item : $rel . '/' . $item;
              $pathAbs = $abs . DIRECTORY_SEPARATOR . $item;
              if (mb_stripos($item, $q) !== false) {
                  $results[] = $pathRel;
              }
              if (is_dir($pathAbs)) {
                  $results = array_merge($results, search_names($base, $pathRel, $q));
              }
          }
          return $results;
      }

      $results = search_names(BASE_DIR, '', $query);
      echo '<div class="notice">نتائج البحث عن "<strong>' . h($query) . '</strong>": ' . count($results) . ' نتيجة.</div>';

      if (count($results) === 0) {
          echo '<p style="padding:10px 16px;color:#ff9999;">لا توجد نتائج مطابقة.</p>';
      } else {
          echo '<div class="tree"><ul>';
          foreach ($results as $r) {
              $name = basename($r);
              $view = '?view=' . enc_path_for_url($r);
              $down = '?download=' . enc_path_for_url($r);
              $isDir = is_dir(BASE_DIR . DIRECTORY_SEPARATOR . $r);
              if ($isDir) {
                  echo '<li class="dir">📁 <a href="?p=' . enc_path_for_url($r) . '">' . h($name) . '</a></li>';
              } else {
                  echo '<li class="file">📄 ' . h($name) . ' <a href="' . $view . '">[عرض]</a> <a href="' . $down . '">[تحميل]</a></li>';
              }
          }
          echo '</ul></div>';
      }

      echo '<div style="padding:10px 16px;"><a href="?" style="color:#00c2a8;">⬅️ الرجوع لعرض المجلدات</a></div>';
    ?>
  </section>
</div>

<?php else: ?>

<!-- 🔵 الوضع العادي بدون بحث -->
<div class="wrap">
  <section class="panel">
    <h2>شجرة المجلدات (من الجذر)</h2>
    <div class="tree" id="treeRoot">
      <?php render_tree(''); ?>
    </div>
    <div class="footer">الجذر: <code><?=h($BASE_REAL)?></code></div>
  </section>
  <section class="panel">
    <h2>المجلد الحالي</h2>
    <div class="crumbs">
      <?php
        $crumbs = $currentRel === '' ? [] : preg_split('#/#', $currentRel, -1, PREG_SPLIT_NO_EMPTY);
        $pathAcc = [];
        echo '<a href="?">الجذر</a>';
        foreach ($crumbs as $c) { $pathAcc[] = $c; echo ' / <a href="?p=' . enc_path_for_url(implode('/', $pathAcc)) . '">' . h($c) . '</a>'; }
      ?>
    </div>
    <div class="stats">
      <div class="pill">الحجم الكلي: <?=h(human_bytes($totalBytes))?></div>
      <div class="pill">عدد الملفات: <?=h((string)$filesCount)?></div>
      <div class="pill">عدد المجلدات: <?=h((string)$dirsCount)?></div>
    </div>
    <div class="notice">اضغط على مجلد في الشجرة لفتحه هنا، أو استعمل أزرار [عرض] و[تحميل] بجانب الملفات.</div>
    <div class="tree">
      <?php
        [$dirsNow, $filesNow] = list_dir_recursive(BASE_DIR, $currentRel);
        echo "<ul>\n";
        foreach ($dirsNow as $d) {
            $name = basename($d);
            echo '<li class="dir">📁 <a href="?p=' . enc_path_for_url($d) . '">' . h($name) . '</a></li>' . "\n";
        }
        foreach ($filesNow as $f) {
            $name = basename($f);
            $view = '?view=' . enc_path_for_url($f);
            $down = '?download=' . enc_path_for_url($f);
            echo '<li class="file">📄 ' . h($name) . ' <a href="' . $view . '">[عرض]</a> <a href="' . $down . '">[تحميل]</a></li>' . "\n";
        }
        echo "</ul>\n";
      ?>
    </div>
  </section>
</div>

<?php endif; ?>

<script>
// طيّ/فتح المجلدات في الشجرة
addEventListener('click', function(e){
  var t = e.target.closest('.toggle');
  if(!t) return;
  var li = t.parentElement;
  li.classList.toggle('open');
});
// فتح أول مستوى افتراضياً
(function(){
  var firstLevels = document.querySelectorAll('#treeRoot > ul > li.dir');
  firstLevels.forEach(function(li){ li.classList.add('open'); });
})();
</script>
</body>
</html>
