<?php
declare(strict_types=1);

/**
 * functional/audio/playlist_view.php
 * Відповідає за:
 * - перегляд плейлиста
 * - список треків плейлиста (з пагінацією)
 * - відтворення плейлиста через глобальний плеєр (VMGA) або Audio App (fallback)
 * - прибирання треків з плейлиста
 */

require_once __DIR__ . '/_boot.php';

$userId = (int)($me['id'] ?? 0);
$id = get_int('id', 0);

if ($userId <= 0 || $id <= 0) {
    if (function_exists('redirect')) redirect('/functional/audio/');
    header('Location: /functional/audio/', true, 302);
    exit;
}

/* playlist (only needed fields) */
$st = $pdo->prepare("SELECT id, title, created_at FROM audio_playlists WHERE id=? AND user_id=? LIMIT 1");
$st->execute([$id, $userId]);
$pl = $st->fetch(PDO::FETCH_ASSOC);

if (!$pl) {
    if (function_exists('redirect')) redirect('/functional/audio/');
    header('Location: /functional/audio/', true, 302);
    exit;
}

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

$csrf = csrf_token();

$confirmRemove = match ($langNow) {
    'ru' => 'Убрать трек из плейлиста?',
    'en' => 'Remove track from playlist?',
    default => 'Прибрати трек з плейлиста?',
};

$appTo = '/functional/audio/playlist_view.php?id=' . (int)$pl['id'] . '&lang=' . $langNow;
$appToEnc = urlencode($appTo);

/* pagination */
$perPage = 200;
$page = get_int('page', 1);
if ($page < 1) $page = 1;
if ($page > 10000) $page = 10000;
$offset = ($page - 1) * $perPage;
if ($offset < 0) $offset = 0;
if ($offset > 2000000) $offset = 2000000;

/* total tracks in playlist */
$st = $pdo->prepare("SELECT COUNT(*) FROM audio_playlist_tracks WHERE playlist_id=?");
$st->execute([(int)$pl['id']]);
$total = (int)$st->fetchColumn();
$pagesTotal = (int)max(1, (int)ceil($total / $perPage));

/* tracks (only required fields) */
$st = $pdo->prepare("
  SELECT pt.position, t.id, t.title, t.artist
  FROM audio_playlist_tracks pt
  JOIN audio_tracks t ON t.id=pt.track_id
  WHERE pt.playlist_id=? AND t.user_id=?
  ORDER BY pt.position ASC, pt.added_at ASC
  LIMIT {$perPage} OFFSET {$offset}
");
$st->execute([(int)$pl['id'], $userId]);
$tracks = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

/* SEO */
$title = audio_t('playlists') . ' — ' . (string)$pl['title'];
$meta_desc = $title;
$canonical = function_exists('abs_url')
    ? abs_url('/functional/audio/playlist_view.php?id=' . (int)$pl['id'])
    : ('/functional/audio/playlist_view.php?id=' . (int)$pl['id']);
$seo_noindex = true;

require __DIR__ . '/../../includes/header.php';
?>

<!-- audio.css: PJAX-safe -->
<script>
(function(){
  var href = "/css/audio.css?v=1";
  try {
    if (!document.querySelector('link[rel="stylesheet"][href="' + href + '"]')) {
      var l = document.createElement('link');
      l.rel = "stylesheet";
      l.href = href;
      document.head.appendChild(l);
    }
  } catch (e) {}
})();
</script>
<noscript><link rel="stylesheet" href="/css/audio.css?v=1"></noscript>

<div class="audio-wrap my-3">
  <div class="d-flex align-items-center justify-content-between gap-2 flex-wrap mb-3">
    <div>
      <h1 class="h4 mb-1"><?= h((string)$pl['title']) ?></h1>
      <div class="audio-muted">
        <?= (int)$total ?> <?= h(audio_t('tracks')) ?>
        <?php if ($pagesTotal > 1): ?>
          <span class="text-muted small"> • page <?= (int)$page ?>/<?= (int)$pagesTotal ?></span>
        <?php endif; ?>
      </div>
    </div>

    <div class="d-flex gap-2 flex-wrap">
      <a class="audio-btn" href="/functional/audio/?lang=<?= h($langNow) ?>"><?= h(audio_t('back')) ?></a>

      <button class="audio-btn audio-btn-primary" type="button" onclick="VM_PL.playPlaylist(<?= (int)$pl['id'] ?>);">
        ▶ <?= h(audio_t('play_playlist')) ?>
      </button>

      <a class="audio-btn"
         href="/functional/audio/app.php?lang=<?= h($langNow) ?>&to=<?= h($appToEnc) ?>#play=playlist&id=<?= (int)$pl['id'] ?>"
         target="_blank" rel="noopener noreferrer">
        ↗ Audio App
      </a>
    </div>
  </div>

  <div class="audio-card">
    <?php if (!$tracks): ?>
      <div class="audio-muted">—</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="audio-table">
          <thead>
            <tr>
              <th style="width:80px;">#</th>
              <th><?= h(audio_t('title')) ?></th>
              <th style="width:220px;"><?= h(audio_t('artist')) ?></th>
              <th style="width:160px;"><?= h(audio_t('actions')) ?></th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($tracks as $t): ?>
            <tr>
              <td><?= (int)($t['position'] ?? 0) ?></td>
              <td><?= h((string)($t['title'] ?? '')) ?></td>
              <td><?= h((string)($t['artist'] ?? '')) ?></td>
              <td>
                <form method="post"
                      action="/functional/audio/playlist_remove_track.php"
                      onsubmit="return confirm(<?= json_encode($confirmRemove, JSON_UNESCAPED_UNICODE) ?>);">
                  <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                  <input type="hidden" name="playlist_id" value="<?= (int)$pl['id'] ?>">
                  <input type="hidden" name="track_id" value="<?= (int)($t['id'] ?? 0) ?>">
                  <input type="hidden" name="back" value="<?= h('/functional/audio/playlist_view.php?id=' . (int)$pl['id'] . '&lang=' . $langNow . '&page=' . (int)$page) ?>">
                  <button class="audio-btn" type="submit">🗑 <?= h(audio_t('remove')) ?></button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <?php if ($pagesTotal > 1): ?>
        <div class="mt-3 d-flex flex-wrap gap-2 align-items-center">
          <?php
            $base = '/functional/audio/playlist_view.php?id=' . (int)$pl['id'] . '&lang=' . $langNow;
            $prev = $page > 1 ? ($page - 1) : 1;
            $next = $page < $pagesTotal ? ($page + 1) : $pagesTotal;
          ?>
          <a class="btn btn-sm btn-outline-secondary"
             href="<?= h($base . '&page=' . $prev) ?>"
             <?= $page <= 1 ? 'aria-disabled="true" tabindex="-1"' : '' ?>>← Prev</a>

          <span class="text-muted small">Page <?= (int)$page ?> / <?= (int)$pagesTotal ?></span>

          <a class="btn btn-sm btn-outline-secondary"
             href="<?= h($base . '&page=' . $next) ?>"
             <?= $page >= $pagesTotal ? 'aria-disabled="true" tabindex="-1"' : '' ?>>Next →</a>
        </div>
      <?php endif; ?>

    <?php endif; ?>
  </div>
</div>

<script>
window.VM_PL = {
  playPlaylist(id) {
    if (window.VMGA && typeof window.VMGA.playPlaylist === 'function') {
      window.VMGA.playPlaylist(id).catch(()=>{});
      return;
    }
    window.open('/functional/audio/app.php?lang=<?= h($langNow) ?>&to=<?= h($appToEnc) ?>#play=playlist&id=' + encodeURIComponent(id), '_blank', 'noopener');
  }
};
</script>

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