<?php
// Движок листинга. Сканирует папки рядом с собой = разделы сайта.
// description.yaml (необязателен) накладывает названия и описания.

$ROOT = __DIR__;
$EMPTY_DESC = 'Добавьте описание, пожалуйста.';

// ---- читаем description.yaml -------------------------------------------
$meta = [];
$yamlFile = $ROOT . '/description.yaml';
if (is_readable($yamlFile)) {
    if (function_exists('yaml_parse_file')) {
        $parsed = @yaml_parse_file($yamlFile);
        if (is_array($parsed)) $meta = $parsed;
    }
}
$sectionsMeta = $meta['sections'] ?? [];
$title    = $meta['title']    ?? 'Файлы';
$subtitle = $meta['subtitle'] ?? '';
$badge    = $meta['badge']    ?? '';

// ---- хелперы ------------------------------------------------------------
function e($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// экранирует текст и превращает markdown-ссылки [текст](url) в <a>
function md($s) {
    $s = e(trim((string)$s));
    return preg_replace(
        '~\[([^\]]+)\]\((https?://[^\s)]+|/[^\s)]*)\)~u',
        '<a class="inline-link" href="$2" target="_blank" rel="noopener">$1</a>',
        $s
    );
}

function humanSize($bytes) {
    if ($bytes <= 0) return '';
    $u = ['Б','КБ','МБ','ГБ'];
    $i = (int)floor(log($bytes, 1024));
    $i = min($i, count($u) - 1);
    return round($bytes / pow(1024, $i), $i ? 1 : 0) . ' ' . $u[$i];
}

// ---- сканируем папки ----------------------------------------------------
$folders = [];
foreach (scandir($ROOT) ?: [] as $entry) {
    if ($entry === '.' || $entry === '..') continue;
    if (is_dir($ROOT . '/' . $entry)) $folders[] = $entry;
}

// порядок: как в yaml, остальные — по алфавиту в конец
$ordered = [];
foreach (array_keys($sectionsMeta) as $k) {
    if (in_array($k, $folders, true)) $ordered[] = $k;
}
$rest = array_diff($folders, $ordered);
sort($rest, SORT_NATURAL | SORT_FLAG_CASE);
$folders = array_merge($ordered, $rest);

$ICON_DL = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
$ICON_EXT = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';
$ICON_LINK = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>';
?><!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($title) ?></title>
<style>
  :root{--ink:#12261f;--paper:#f6f4ee;--line:#d9d3c4;--seal:#1f5c46;
    --seal-soft:#eaf1ed;--muted:#5f6b62;--file:#8a5a2b}
  *{box-sizing:border-box}
  html,body{margin:0}
  body{background:var(--paper);color:var(--ink);
    font-family:"Segoe UI",-apple-system,Roboto,Arial,sans-serif;
    line-height:1.5;-webkit-font-smoothing:antialiased}
  .wrap{max-width:820px;margin:0 auto;padding:56px 24px 80px}
  header{border-bottom:2px solid var(--ink);padding-bottom:22px;margin-bottom:20px}
  .badge{display:inline-flex;align-items:center;gap:8px;font-size:12px;
    letter-spacing:.14em;text-transform:uppercase;color:var(--seal);
    font-weight:600;margin-bottom:14px}
  h1{font-family:Georgia,"Times New Roman",serif;font-weight:600;font-size:34px;
    line-height:1.15;margin:0 0 8px;letter-spacing:-.01em}
  .subtitle{color:var(--muted);font-size:15px;max-width:60ch;margin:0}
  .section{margin-top:28px;padding:22px 24px;border-radius:12px}
  .section-head{display:flex;align-items:baseline;gap:12px;margin-bottom:4px}
  .section-num{font-family:Georgia,serif;font-size:13px;color:var(--seal);
    font-weight:700;min-width:26px}
  .section-name{font-family:Georgia,serif;font-size:21px;font-weight:600;margin:0}
  .section-desc{color:var(--muted);font-size:14.5px;margin:6px 0 18px 38px;max-width:64ch}
  .files{list-style:none;margin:0 0 0 38px;padding:0;border-top:1px solid var(--line)}
  .file{display:flex;align-items:center;gap:16px;padding:15px 4px;
    border-bottom:1px solid var(--line);text-decoration:none;color:inherit;
    transition:padding-left .15s,background .15s}
  .file:hover{background:var(--seal-soft);padding-left:12px}
  .file:focus-visible{outline:2px solid var(--seal);outline-offset:-2px}
  .ext{flex:none;width:46px;height:46px;border-radius:7px;background:#fff;
    border:1px solid var(--line);display:flex;align-items:center;justify-content:center;
    font-size:10px;font-weight:700;letter-spacing:.05em;color:var(--file);text-transform:uppercase}
  .ext svg{width:20px;height:20px;color:var(--seal)}
  .file-body{flex:1;min-width:0}
  .file-name{display:block;font-weight:600;font-size:15.5px}
  .file-desc{display:block;color:var(--muted);font-size:13.5px;margin-top:3px;max-width:56ch}
  .file-desc.empty{color:#b0a892;font-style:italic}
  .file-size{display:block;color:#a49b86;font-size:12px;margin-top:2px}
  .inline-link{color:var(--seal);text-decoration:underline;text-underline-offset:2px}
  .inline-link:hover{color:#123c2d}
  .dl{flex:none;display:flex;align-items:center;color:var(--seal)}
  .dl svg{width:16px;height:16px}
  .empty-sec{color:#b0a892;font-style:italic;font-size:13.5px;padding:14px 4px;margin-left:38px}
  footer{margin-top:56px;padding-top:20px;border-top:1px solid var(--line);
    color:#a49b86;font-size:12.5px;display:flex;justify-content:space-between;gap:8px}
  @media (max-width:560px){
    .wrap{padding:36px 18px 60px}
    h1{font-size:27px}
    .section{padding:18px 16px}
    .section-desc,.files,.empty-sec{margin-left:0}
  }
  @media (prefers-reduced-motion:reduce){*{transition:none!important}}
</style>
</head>
<body>
<div class="wrap">
  <header>
    <?php if ($badge): ?><div class="badge"><?= e($badge) ?></div><?php endif; ?>
    <h1><?= e($title) ?></h1>
    <?php if ($subtitle): ?><p class="subtitle"><?= e($subtitle) ?></p><?php endif; ?>
  </header>

<?php
$i = 0;
foreach ($folders as $folder):
    $i++;
    $sm    = $sectionsMeta[$folder] ?? [];
    $fMeta = $sm['files'] ?? [];
    $bg    = !empty($sm['bg']) ? ' style="background:' . e($sm['bg']) . '"' : '';

    // файлы на диске
    $files = [];
    foreach (scandir($ROOT . '/' . $folder) ?: [] as $f) {
        if ($f === '.' || $f === '..') continue;
        if (is_file($ROOT . '/' . $folder . '/' . $f)) $files[] = $f;
    }
    sort($files, SORT_NATURAL | SORT_FLAG_CASE);

    // ссылки из yaml (записи с url — файла на диске нет)
    $links = [];
    foreach ($fMeta as $key => $m) {
        if (is_array($m) && !empty($m['url'])) $links[$key] = $m;
    }
?>
  <section class="section"<?= $bg ?>>
    <div class="section-head">
      <span class="section-num"><?= str_pad($i, 2, '0', STR_PAD_LEFT) ?></span>
      <h2 class="section-name"><?= e($sm['name'] ?? $folder) ?></h2>
    </div>
    <?php if (!empty($sm['desc'])): ?>
      <p class="section-desc"><?= md($sm['desc']) ?></p>
    <?php endif; ?>

    <?php if ($files || $links): ?>
    <ul class="files">

      <?php foreach ($files as $fname):
        $m    = $fMeta[$fname] ?? [];
        $ext  = strtolower(pathinfo($fname, PATHINFO_EXTENSION));
        $name = $m['name'] ?? $fname;
        $size = humanSize(@filesize($ROOT . '/' . $folder . '/' . $fname));
        $href = rawurlencode($folder) . '/' . rawurlencode($fname);
      ?>
        <a class="file" href="<?= $href ?>" download>
          <span class="ext"><?= e($ext) ?></span>
          <span class="file-body">
            <span class="file-name"><?= e($name) ?></span>
            <?php if (!empty($m['desc'])): ?>
              <span class="file-desc"><?= md($m['desc']) ?></span>
            <?php else: ?>
              <span class="file-desc empty"><?= e($EMPTY_DESC) ?></span>
            <?php endif; ?>
            <?php if ($size): ?><span class="file-size"><?= e($size) ?></span><?php endif; ?>
          </span>
          <span class="dl"><?= $ICON_DL ?></span>
        </a>
      <?php endforeach; ?>

      <?php foreach ($links as $key => $m): ?>
        <a class="file" href="<?= e($m['url']) ?>" target="_blank" rel="noopener">
          <span class="ext"><?= $ICON_LINK ?></span>
          <span class="file-body">
            <span class="file-name"><?= e($m['name'] ?? $key) ?></span>
            <?php if (!empty($m['desc'])): ?>
              <span class="file-desc"><?= md($m['desc']) ?></span>
            <?php endif; ?>
          </span>
          <span class="dl"><?= $ICON_EXT ?></span>
        </a>
      <?php endforeach; ?>

    </ul>
    <?php else: ?>
      <div class="empty-sec">Раздел пуст.</div>
    <?php endif; ?>
  </section>
<?php endforeach; ?>

<?php if ($i === 0): ?>
  <p class="empty-sec">Разделы не найдены — создайте папки рядом с index.php.</p>
<?php endif; ?>

  <footer>
    <span>sgbm.biz</span>
    <span><?= date('Y') ?></span>
  </footer>
</div>
</body>
</html>
