<?php
declare(strict_types=1);

/**
 * /functional/search/index.php
 * Універсальний пошук по сайту:
 * - Люди (нік + ПІБ)
 * - Аудіо (назва/виконавець)
 * - Відео (назва)
 * - Групи (назва/тема/опис)
 *
 * URL:
 * - /functional/search/?q=...
 * - /functional/search/?q=...&t=people|audio|video|groups|all
 */

require_once __DIR__ . '/../../includes/start.php';

$pdo = db();
$me  = current_user();

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

if (!function_exists('search_tr')) {
  function search_tr(string $uk, string $ru, string $en): string {
    $l = function_exists('lang') ? (string)lang() : 'uk';
    return match ($l) {
      'en' => $en,
      'ru' => $ru,
      default => $uk,
    };
  }
}

if (!function_exists('search_badge_closed')) {
  function search_badge_closed(int $isClosed): string {
    if ($isClosed !== 1) return '';
    $l = function_exists('lang') ? (string)lang() : 'uk';
    $txt = match ($l) {
      'en' => 'Closed',
      'ru' => 'Закрытая',
      default => 'Закрита',
    };
    return '<span class="badge text-bg-secondary ms-2">' . h($txt) . '</span>';
  }
}

function search_tokens(string $q): array {
  $q = trim($q);
  if ($q === '') return [];
  $parts = preg_split('/\s+/u', $q) ?: [];
  $parts = array_values(array_filter(array_map('trim', $parts), fn($x) => $x !== ''));
  if (count($parts) > 6) $parts = array_slice($parts, 0, 6);
  return $parts;
}

/**
 * ВАЖЛИВО: використовуємо позиційні плейсхолдери '?'
 * бо при native prepares повторення одного named :p0 в SQL => HY093.
 *
 * Логіка:
 * - AND між токенами
 * - OR між полями
 */
function search_build_where_positional(array $tokens, array $fields, array &$params): string {
  $and = [];
  foreach ($tokens as $tok) {
    $or = [];
    foreach ($fields as $f) {
      $or[] = "$f LIKE ?";
      $params[] = '%' . $tok . '%';
    }
    $and[] = '(' . implode(' OR ', $or) . ')';
  }
  return $and ? implode(' AND ', $and) : '1=1';
}

/* ===== state ===== */
$langNow = function_exists('lang') ? (string)lang() : 'uk';
if (!in_array($langNow, ['uk','ru','en'], true)) $langNow = 'uk';

$title = search_tr('Пошук', 'Поиск', 'Search');

$q = trim((string)($_GET['q'] ?? ''));
$t = (string)($_GET['t'] ?? 'all');
$allowedTabs = ['all','people','audio','video','groups'];
if (!in_array($t, $allowedTabs, true)) $t = 'all';

$tokens = search_tokens($q);
$minLenOk = (mb_strlen($q, 'UTF-8') >= 2);

$limitAll = 5;
$limitOne = 30;

$people = $audio = $video = $groups = [];
$errors = []; // щоб не падало фаталом, а показувало помилку блоком

/* =========================
   SEO (перед header)
   Пошук НЕ індексуємо
========================= */
$meta_desc = search_tr(
  'Пошук по VMEREGI: люди, аудіо, відео та групи.',
  'Поиск по VMEREGI: люди, аудио, видео и группы.',
  'Search VMEREGI: people, audio, video and groups.'
);

/* canonical без q/t, lang додасть seo.php */
$canonical = abs_url('/functional/search/');

/* завжди noindex для пошуку */
$seo_noindex = true;

if ($minLenOk && $tokens) {

  /* ===== people ===== */
  if ($t === 'all' || $t === 'people') {
    try {
      $params = [];
      $where = search_build_where_positional($tokens, ['u.username', 'u.full_name'], $params);
      $sql = "SELECT u.id, u.username, u.full_name, u.avatar_path, u.city, u.country
              FROM users u
              WHERE u.is_active=1 AND ($where)
              ORDER BY u.id DESC
              LIMIT " . (int)($t === 'people' ? $limitOne : $limitAll);
      $st = $pdo->prepare($sql);
      $st->execute($params);
      $people = $st->fetchAll();
    } catch (Throwable $e) {
      $errors[] = 'people: ' . $e->getMessage();
    }
  }

  /* ===== audio ===== */
  if ($t === 'all' || $t === 'audio') {
    try {
      $params = [];
      $where = search_build_where_positional($tokens, ['a.title', 'a.artist', 'u.username', 'u.full_name'], $params);
      $sql = "SELECT a.id, a.title, a.artist, a.duration_sec, a.rel_path, a.created_at,
                     u.username AS owner_username, u.full_name AS owner_full_name
              FROM audio_tracks a
              JOIN users u ON u.id = a.user_id
              WHERE ($where)
              ORDER BY a.id DESC
              LIMIT " . (int)($t === 'audio' ? $limitOne : $limitAll);
      $st = $pdo->prepare($sql);
      $st->execute($params);
      $audio = $st->fetchAll();
    } catch (Throwable $e) {
      $errors[] = 'audio: ' . $e->getMessage();
    }
  }

  /* ===== video ===== */
  if ($t === 'all' || $t === 'video') {
    try {
      $params = [];
      $where = search_build_where_positional($tokens, ['v.title', 'u.username', 'u.full_name'], $params);
      $sql = "SELECT v.id, v.title, v.rel_path, v.size_bytes, v.created_at,
                     u.username AS owner_username, u.full_name AS owner_full_name
              FROM myvideos v
              JOIN users u ON u.id = v.user_id
              WHERE ($where)
              ORDER BY v.id DESC
              LIMIT " . (int)($t === 'video' ? $limitOne : $limitAll);
      $st = $pdo->prepare($sql);
      $st->execute($params);
      $video = $st->fetchAll();
    } catch (Throwable $e) {
      $errors[] = 'video: ' . $e->getMessage();
    }
  }

  /* ===== groups ===== */
  if ($t === 'all' || $t === 'groups') {
    try {
      $params = [];
      $where = search_build_where_positional($tokens, ['g.name', 'g.topic', 'g.about', 'g.slug'], $params);
      $sql = "SELECT g.id, g.name, g.slug, g.topic, g.avatar_path, g.is_closed,
                     (SELECT COUNT(*) FROM group_members gm WHERE gm.group_id = g.id AND gm.status='active') AS members_cnt
              FROM `groups` g
              WHERE ($where)
              ORDER BY g.id DESC
              LIMIT " . (int)($t === 'groups' ? $limitOne : $limitAll);
      $st = $pdo->prepare($sql);
      $st->execute($params);
      $groups = $st->fetchAll();
    } catch (Throwable $e) {
      $errors[] = 'groups: ' . $e->getMessage();
    }
  }
}

require_once __DIR__ . '/../../includes/header.php';

$tabs = [
  'all'    => search_tr('Все', 'Всё', 'All'),
  'people' => search_tr('Люди', 'Люди', 'People'),
  'audio'  => search_tr('Аудіо', 'Аудио', 'Audio'),
  'video'  => search_tr('Відео', 'Видео', 'Video'),
  'groups' => search_tr('Групи', 'Группы', 'Groups'),
];

function search_tab_link(string $tab, string $q, string $langNow): string {
  $q = trim($q);
  $qs = ['t' => $tab, 'lang' => $langNow];
  if ($q !== '') $qs['q'] = $q;
  return '/functional/search/?' . http_build_query($qs);
}

function search_with_lang(string $url, string $langNow): string {
  $url = trim($url);
  if ($url === '') return $url;

  $parts = parse_url($url);
  $path = (string)($parts['path'] ?? $url);
  if ($path === '') $path = '/';

  $query = [];
  if (!empty($parts['query'])) {
    parse_str((string)$parts['query'], $query);
    if (!is_array($query)) $query = [];
  }
  $query['lang'] = $langNow;

  $out = $path . '?' . http_build_query($query);
  if (!empty($parts['fragment'])) $out .= '#' . (string)$parts['fragment'];
  return $out;
}
?>
<div class="row g-3">
  <div class="col-lg-3 d-none d-lg-block">
    <?php
      $p = __DIR__ . '/../../blocks/left.php';
      if (is_file($p)) require $p;
    ?>
  </div>

  <div class="col-lg-6">

    <?php if ($errors): ?>
      <div class="alert alert-warning">
        <div class="fw-semibold mb-1"><?= h(search_tr('Попередження пошуку', 'Предупреждение поиска', 'Search warning')) ?></div>
        <div style="white-space:pre-wrap"><?= h(implode("\n", $errors)) ?></div>
      </div>
    <?php endif; ?>

    <div class="card shadow-sm">
      <div class="card-body">
        <div class="d-flex align-items-center justify-content-between gap-2 flex-wrap">
          <h1 class="h5 m-0"><?= h(search_tr('Пошук', 'Поиск', 'Search')) ?></h1>
          <span class="text-muted small"><?= h(search_tr('Універсальний пошук по сайту', 'Универсальный поиск по сайту', 'Universal site search')) ?></span>
        </div>

        <form class="mt-3" action="/functional/search/" method="get">
          <input type="hidden" name="t" value="<?= h($t) ?>">
          <input type="hidden" name="lang" value="<?= h($langNow) ?>">
          <div class="input-group">
            <input
              type="search"
              class="form-control"
              name="q"
              value="<?= h($q) ?>"
              placeholder="<?= h(search_tr('Введіть нік, ПІБ, назву пісні/відео або групи', 'Введите ник, ФИО, название песни/видео или группы', 'Enter username, full name, song/video or group name')) ?>"
              maxlength="120"
              autocomplete="off"
            >
            <button class="btn btn-primary" type="submit"><?= h(search_tr('Пошук', 'Найти', 'Search')) ?></button>
          </div>
          <div class="form-text">
            <?= h(search_tr('Працює по людям, аудіо, відео і групам.', 'Работает по людям, аудио, видео и группам.', 'Searches people, audio, video and groups.')) ?>
          </div>
        </form>

        <ul class="nav nav-pills mt-3">
          <?php foreach ($tabs as $key => $label): ?>
            <?php $active = ($t === $key) ? 'active' : ''; ?>
            <li class="nav-item">
              <a class="nav-link <?= $active ?>" href="<?= h(search_tab_link($key, $q, $langNow)) ?>"><?= h($label) ?></a>
            </li>
          <?php endforeach; ?>
        </ul>
      </div>
    </div>

    <?php if (!$minLenOk): ?>
      <div class="alert alert-info mt-3">
        <?= h(search_tr('Введіть мінімум 2 символи для пошуку.', 'Введите минимум 2 символа для поиска.', 'Type at least 2 characters to search.')) ?>
      </div>
    <?php elseif (!$tokens): ?>
      <div class="alert alert-info mt-3">
        <?= h(search_tr('Введіть запит у поле пошуку.', 'Введите запрос в поле поиска.', 'Enter a query in the search field.')) ?>
      </div>
    <?php else: ?>

      <?php
        $nothing =
          (($t === 'people' && !$people) ||
           ($t === 'audio'  && !$audio)  ||
           ($t === 'video'  && !$video)  ||
           ($t === 'groups' && !$groups) ||
           ($t === 'all'    && !$people && !$audio && !$video && !$groups));
      ?>
      <?php if ($nothing): ?>
        <div class="alert alert-warning mt-3">
          <?= h(search_tr('Нічого не знайдено.', 'Ничего не найдено.', 'Nothing found.')) ?>
        </div>
      <?php endif; ?>

      <?php if ($t === 'all' || $t === 'people'): ?>
        <div class="card shadow-sm mt-3">
          <div class="card-header d-flex align-items-center justify-content-between">
            <span class="fw-semibold"><?= h(search_tr('Люди', 'Люди', 'People')) ?></span>
            <?php if ($t === 'all'): ?>
              <a class="small text-decoration-none" href="<?= h(search_tab_link('people', $q, $langNow)) ?>"><?= h(search_tr('Показати всі', 'Показать все', 'View all')) ?></a>
            <?php endif; ?>
          </div>
          <div class="card-body">
            <?php if (!$people): ?>
              <div class="text-muted"><?= h(search_tr('Немає збігів', 'Нет совпадений', 'No matches')) ?></div>
            <?php else: ?>
              <div class="list-group">
                <?php foreach ($people as $urow): ?>
                  <?php
                    $uname = (string)($urow['username'] ?? '');
                    $fn    = trim((string)($urow['full_name'] ?? ''));
                    $ava   = (string)($urow['avatar_path'] ?? '');
                    $city  = trim((string)($urow['city'] ?? ''));
                    $cntr  = trim((string)($urow['country'] ?? ''));
                    $place = trim(($city !== '' ? $city : '') . ($cntr !== '' ? ($city !== '' ? ', ' : '') . $cntr : ''));
                    $href  = search_with_lang('/profile/?u=' . rawurlencode($uname), $langNow);
                  ?>
                  <a class="list-group-item list-group-item-action d-flex align-items-center gap-3" href="<?= h($href) ?>">
                    <div style="width:44px;height:44px;border-radius:12px;overflow:hidden;background:#e9ecef;flex:0 0 auto;">
                      <?php if ($ava !== ''): ?>
                        <img src="<?= h($ava) ?>" alt="" style="width:100%;height:100%;object-fit:cover;">
                      <?php endif; ?>
                    </div>
                    <div class="flex-grow-1">
                      <div class="fw-semibold"><?= h($fn !== '' ? $fn : $uname) ?></div>
                      <div class="text-muted small">@<?= h($uname) ?><?= $place !== '' ? ' · ' . h($place) : '' ?></div>
                    </div>
                  </a>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      <?php endif; ?>

      <?php if ($t === 'all' || $t === 'audio'): ?>
        <div class="card shadow-sm mt-3">
          <div class="card-header d-flex align-items-center justify-content-between">
            <span class="fw-semibold"><?= h(search_tr('Аудіо', 'Аудио', 'Audio')) ?></span>
            <?php if ($t === 'all'): ?>
              <a class="small text-decoration-none" href="<?= h(search_tab_link('audio', $q, $langNow)) ?>"><?= h(search_tr('Показати всі', 'Показать все', 'View all')) ?></a>
            <?php endif; ?>
          </div>
          <div class="card-body">
            <?php if (!$audio): ?>
              <div class="text-muted"><?= h(search_tr('Немає збігів', 'Нет совпадений', 'No matches')) ?></div>
            <?php else: ?>
              <div class="list-group">
                <?php foreach ($audio as $arow): ?>
                  <?php
                    $titleA = (string)($arow['title'] ?? '');
                    $artist = trim((string)($arow['artist'] ?? ''));
                    $rel    = (string)($arow['rel_path'] ?? '');
                    $ownU   = (string)($arow['owner_username'] ?? '');
                    $sec    = (int)($arow['duration_sec'] ?? 0);
                    $dur    = ($sec > 0) ? sprintf('%d:%02d', intdiv($sec, 60), $sec % 60) : '';
                    $ownerHref = search_with_lang('/profile/?u=' . rawurlencode($ownU), $langNow);
                  ?>
                  <div class="list-group-item">
                    <div class="d-flex align-items-start justify-content-between gap-2 flex-wrap">
                      <div>
                        <div class="fw-semibold"><?= h($titleA) ?></div>
                        <div class="text-muted small">
                          <?= $artist !== '' ? h($artist) . ' · ' : '' ?>
                          <?= h(search_tr('Власник', 'Владелец', 'Owner')) ?>:
                          <a class="text-decoration-none" href="<?= h($ownerHref) ?>">@<?= h($ownU) ?></a>
                          <?= $dur !== '' ? ' · ' . h($dur) : '' ?>
                        </div>
                      </div>
                      <?php if ($rel !== ''): ?>
                        <a class="btn btn-sm btn-outline-primary" href="<?= h($rel) ?>" target="_blank" rel="noopener">
                          <?= h(search_tr('Відкрити', 'Открыть', 'Open')) ?>
                        </a>
                      <?php endif; ?>
                    </div>

                    <?php if ($rel !== ''): ?>
                      <div class="mt-2">
                        <audio controls preload="none" style="width:100%;">
                          <source src="<?= h($rel) ?>">
                        </audio>
                      </div>
                    <?php endif; ?>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      <?php endif; ?>

      <?php if ($t === 'all' || $t === 'video'): ?>
        <div class="card shadow-sm mt-3">
          <div class="card-header d-flex align-items-center justify-content-between">
            <span class="fw-semibold"><?= h(search_tr('Відео', 'Видео', 'Video')) ?></span>
            <?php if ($t === 'all'): ?>
              <a class="small text-decoration-none" href="<?= h(search_tab_link('video', $q, $langNow)) ?>"><?= h(search_tr('Показати всі', 'Показать все', 'View all')) ?></a>
            <?php endif; ?>
          </div>
          <div class="card-body">
            <?php if (!$video): ?>
              <div class="text-muted"><?= h(search_tr('Немає збігів', 'Нет совпадений', 'No matches')) ?></div>
            <?php else: ?>
              <div class="list-group">
                <?php foreach ($video as $vrow): ?>
                  <?php
                    $idV   = (int)($vrow['id'] ?? 0);
                    $ttlV  = (string)($vrow['title'] ?? '');
                    $relV  = (string)($vrow['rel_path'] ?? '');
                    $ownU  = (string)($vrow['owner_username'] ?? '');
                    $watch = search_with_lang('/functional/video/watch.php?id=' . $idV, $langNow);
                    $ownerHref = search_with_lang('/profile/?u=' . rawurlencode($ownU), $langNow);
                  ?>
                  <div class="list-group-item">
                    <div class="d-flex align-items-start justify-content-between gap-2 flex-wrap">
                      <div>
                        <div class="fw-semibold"><?= h($ttlV) ?></div>
                        <div class="text-muted small">
                          <?= h(search_tr('Власник', 'Владелец', 'Owner')) ?>:
                          <a class="text-decoration-none" href="<?= h($ownerHref) ?>">@<?= h($ownU) ?></a>
                        </div>
                      </div>
                      <div class="d-flex gap-2">
                        <a class="btn btn-sm btn-outline-primary" href="<?= h($watch) ?>">
                          <?= h(search_tr('Дивитись', 'Смотреть', 'Watch')) ?>
                        </a>
                        <?php if ($relV !== ''): ?>
                          <a class="btn btn-sm btn-outline-secondary" href="<?= h($relV) ?>" target="_blank" rel="noopener">
                            <?= h(search_tr('Файл', 'Файл', 'File')) ?>
                          </a>
                        <?php endif; ?>
                      </div>
                    </div>

                    <?php if ($relV !== ''): ?>
                      <div class="mt-2">
                        <video controls preload="none" style="width:100%;max-height:360px;">
                          <source src="<?= h($relV) ?>">
                        </video>
                      </div>
                    <?php endif; ?>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      <?php endif; ?>

      <?php if ($t === 'all' || $t === 'groups'): ?>
        <div class="card shadow-sm mt-3">
          <div class="card-header d-flex align-items-center justify-content-between">
            <span class="fw-semibold"><?= h(search_tr('Групи', 'Группы', 'Groups')) ?></span>
            <?php if ($t === 'all'): ?>
              <a class="small text-decoration-none" href="<?= h(search_tab_link('groups', $q, $langNow)) ?>"><?= h(search_tr('Показати всі', 'Показать все', 'View all')) ?></a>
            <?php endif; ?>
          </div>
          <div class="card-body">
            <?php if (!$groups): ?>
              <div class="text-muted"><?= h(search_tr('Немає збігів', 'Нет совпадений', 'No matches')) ?></div>
            <?php else: ?>
              <div class="list-group">
                <?php foreach ($groups as $grow): ?>
                  <?php
                    $slug  = (string)($grow['slug'] ?? '');
                    $nameG = (string)($grow['name'] ?? '');
                    $topic = trim((string)($grow['topic'] ?? ''));
                    $avaG  = (string)($grow['avatar_path'] ?? '');
                    $isC   = (int)($grow['is_closed'] ?? 0);
                    $cnt   = (int)($grow['members_cnt'] ?? 0);
                    $hrefG = search_with_lang('/functional/group/view.php?g=' . rawurlencode($slug), $langNow);
                  ?>
                  <a class="list-group-item list-group-item-action d-flex align-items-center gap-3" href="<?= h($hrefG) ?>">
                    <div style="width:44px;height:44px;border-radius:12px;overflow:hidden;background:#e9ecef;flex:0 0 auto;">
                      <?php if ($avaG !== ''): ?>
                        <img src="<?= h($avaG) ?>" alt="" style="width:100%;height:100%;object-fit:cover;">
                      <?php endif; ?>
                    </div>
                    <div class="flex-grow-1">
                      <div class="fw-semibold">
                        <?= h($nameG) ?><?= search_badge_closed($isC) ?>
                      </div>
                      <div class="text-muted small">
                        <?= $topic !== '' ? h($topic) . ' · ' : '' ?>
                        <?= h(search_tr('Учасників', 'Участников', 'Members')) ?>: <?= h((string)$cnt) ?>
                      </div>
                    </div>
                  </a>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      <?php endif; ?>

    <?php endif; ?>

  </div>

  <div class="col-lg-3 d-none d-lg-block">
    <?php
      $p1 = __DIR__ . '/../../blocks/profile.php';
      if (is_file($p1)) require $p1;

      $p2 = __DIR__ . '/../../blocks/groups.php';
      if (is_file($p2)) require $p2;
    ?>
  </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>