<?php
declare(strict_types=1);

/**
 * /blocks/groups.php
 * Правий боковий блок "Групи":
 * - показує список груп користувача (де він учасник)
 * - кнопка "Створити групу"
 */

if (!function_exists('h')) {
  function h(?string $s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

$u = current_user();
$lang = (string)($_SESSION['lang'] ?? ($u['lang'] ?? 'uk'));
if (!in_array($lang, ['uk','ru','en'], true)) $lang = 'uk';
$T = function(string $uk, string $ru, string $en) use ($lang): string {
  if ($lang === 'ru') return $ru;
  if ($lang === 'en') return $en;
  return $uk;
};

?>
<div class="card card-app mb-3">
  <div class="card-body">
    <div class="d-flex align-items-center justify-content-between mb-2">
      <div class="fw-semibold"><?= h($T('Групи','Группы','Groups')) ?></div>
      <a class="btn btn-sm btn-outline-primary" href="/functional/group/create.php">
        <?= h($T('Створити','Создать','Create')) ?>
      </a>
    </div>

    <?php if (!$u): ?>
      <div class="text-muted small">
        <?= h($T('Увійди, щоб бачити групи.','Войди, чтобы видеть группы.','Log in to see your groups.')) ?>
      </div>
    <?php else: ?>
      <?php
        $pdo = db();
        $rows = [];
        try {
          $st = $pdo->prepare("
            SELECT g.id, g.slug, g.name, g.avatar_path, g.topic
            FROM group_members gm
            JOIN `groups` g ON g.id = gm.group_id
            WHERE gm.user_id = ? AND gm.status = 'active'
            ORDER BY g.id DESC
            LIMIT 10
          ");
          $st->execute([(int)$u['id']]);
          $rows = $st->fetchAll() ?: [];
        } catch (Throwable $e) {
          $rows = [];
        }
      ?>

      <?php if (!$rows): ?>
        <div class="text-muted small">
          <?= h($T('Поки що немає груп.','Пока нет групп.','No groups yet.')) ?>
        </div>
      <?php else: ?>
        <div class="vstack gap-2">
          <?php foreach ($rows as $g): ?>
            <?php
              $slug = (string)($g['slug'] ?? '');
              $name = (string)($g['name'] ?? '');
              $topic = (string)($g['topic'] ?? '');
              $ava = trim((string)($g['avatar_path'] ?? ''));
              $ini = $name !== '' ? mb_substr($name, 0, 1, 'UTF-8') : 'G';
              $href = $slug !== '' ? ('/functional/group/view.php?g=' . rawurlencode($slug)) : ('/functional/group/view.php?id=' . (int)$g['id']);
            ?>
            <a class="d-flex align-items-center gap-2 text-decoration-none" href="<?= h($href) ?>">
              <div style="width:36px;height:36px;border-radius:10px;overflow:hidden;flex:0 0 auto;background:#e9ecef;display:flex;align-items:center;justify-content:center;font-weight:700;color:#495057;">
                <?php if ($ava !== ''): ?>
                  <img src="<?= h($ava) ?>" alt="" style="width:100%;height:100%;object-fit:cover;display:block;">
                <?php else: ?>
                  <?= h($ini) ?>
                <?php endif; ?>
              </div>
              <div class="flex-grow-1">
                <div class="fw-semibold" style="line-height:1.1;"><?= h($name) ?></div>
                <?php if ($topic !== ''): ?>
                  <div class="text-muted small" style="line-height:1.1;"><?= h($topic) ?></div>
                <?php endif; ?>
              </div>
            </a>
          <?php endforeach; ?>
        </div>

        <div class="mt-3">
          <a class="btn btn-sm btn-outline-secondary w-100" href="/functional/group/">
            <?= h($T('Усі групи','Все группы','All groups')) ?>
          </a>
        </div>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</div>
