<?php
declare(strict_types=1);
/** Раздел библиотеки: список документов и страниц. */
require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/kb.php';

$section = kb_section((string)($_GET['s'] ?? ''));
if (!$section) {
    http_response_code(404);
    page_header(t('kb_title'), 'kb');
    echo '<div class="alert error">' . e(t('kb_not_found')) . '</div>';
    echo '<p><a class="btn ghost" href="/kb">' . e(t('kb_back')) . '</a></p>';
    page_footer();
    exit;
}

$docs = kb_documents((int)$section['id']);
page_header(ref_name($section), 'kb');
?>
<nav class="crumbs"><a href="/kb"><?= e(t('nav_kb')) ?></a> / <span><?= e(ref_name($section)) ?></span></nav>

<section class="hero" style="--kb-color: <?= e($section['color']) ?>">
  <h1><?= e(ref_name($section)) ?></h1>
  <?php $intro = (string)($section['intro_' . current_lang()] ?? ''); ?>
  <?php if ($intro !== ''): ?><p class="lead"><?= e($intro) ?></p><?php endif; ?>
</section>

<?php if (!$docs): ?>
  <div class="alert info"><?= e(t('kb_empty')) ?></div>
<?php endif; ?>

<ul class="kb-list">
<?php foreach ($docs as $d):
    $pending = $d['status'] === 'pending';
    $files   = kb_files($d);
    ?>
  <li class="kb-item<?= $pending ? ' pending' : '' ?>">
    <div class="kb-item-main">
      <?php if ($pending): ?>
        <span class="kb-item-title"><?= e(kb_title($d)) ?></span>
        <span class="badge pending"><?= e(t('kb_pending')) ?></span>
      <?php else: ?>
        <a class="kb-item-title" href="<?= e(kb_doc_url($d)) ?>"><?= e(kb_title($d)) ?></a>
      <?php endif; ?>
      <?php if (kb_summary($d) !== ''): ?>
        <p class="kb-item-sum"><?= e(kb_summary($d)) ?></p>
      <?php endif; ?>
    </div>
    <?php if ($files): ?>
      <div class="kb-item-files">
        <?php
        // сначала показываем, потом даём скачать: сразу предлагать файл Word неудобно,
        // человек не видит, тот ли это документ
        $first = array_key_first($files);
        $fmts  = [];
        foreach ($files as $l => $f) {
            $fmts[] = strtoupper($l === 'uk' ? 'UA' : 'EN') . ' '
                    . strtoupper(pathinfo($f['name'], PATHINFO_EXTENSION)) . ', ' . kb_size($f['size']);
        }
        ?>
        <a class="btn file" href="<?= e(kb_doc_url($d)) ?>">
          <?= e(t('kb_preview')) ?>
          <span class="fmeta"><?= e(implode(' · ', $fmts)) ?></span>
        </a>
      </div>
    <?php elseif ($d['doc_type'] === 'page' && !$pending): ?>
      <div class="kb-item-files"><a class="btn ghost" href="<?= e(kb_doc_url($d)) ?>"><?= e(t('kb_open')) ?></a></div>
    <?php endif; ?>
  </li>
<?php endforeach; ?>
</ul>

<p><a class="btn ghost" href="/kb"><?= e(t('kb_back')) ?></a></p>
<?php
page_footer();
