<?php
declare(strict_types=1);

/**
 * /functional/audio/index.php
 * "Моя музика":
 * - список треків (з пагінацією)
 * - завантаження (до 25MB/файл)
 * - квота 5GB на користувача (полоса прогресу)
 * - плейлисти (створення/видалення) + додавання треків у плейлист
 * - редагування title/artist
 * - видалення треку
 * - layout як у /functional/files/index.php: feed-layout + sidebar-sticky + blocks/profile.php + blocks/groups.php
 *
 * SEO:
 * - приватний розділ (тільки власник) => noindex,nofollow
 */

require_once __DIR__ . '/_boot.php';

/* _boot.php вже дав $pdo/$me та перевірив логін */
if (!isset($pdo) || !($pdo instanceof PDO)) $pdo = db();
if (!isset($me) || !is_array($me)) $me = current_user();

$u = $me; // для сайдбарів, якщо вони очікують $u

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

$userId = (int)($me['id'] ?? 0);
if ($userId <= 0) {
    if (function_exists('redirect')) redirect('/login.php');
    header('Location: /login.php');
    exit;
}

$csrf = csrf_token();

$quotaMax  = audio_quota_bytes();                 // 5GB
$usedBytes = audio_used_bytes($pdo, $userId);
$usedPct   = $quotaMax > 0 ? min(100, (int)round($usedBytes * 100 / $quotaMax)) : 0;

$maxOne = audio_max_file_bytes();                 // 25MB

/* ===== pagination for tracks ===== */
$perPage = 200;
$page = function_exists('get_int') ? get_int('page', 1) : (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
if ($page > 10000) $page = 10000; // safety cap

$offset = ($page - 1) * $perPage;
if ($offset < 0) $offset = 0;
if ($offset > 2000000) $offset = 2000000; // safety cap

/* ===== totals ===== */
$st = $pdo->prepare("SELECT COUNT(*) FROM audio_tracks WHERE user_id=?");
$st->execute([$userId]);
$tracksTotal = (int)$st->fetchColumn();

$pagesTotal = (int)max(1, (int)ceil($tracksTotal / $perPage));

/* ===== data: tracks (paged) ===== */
$st = $pdo->prepare("
  SELECT id, title, artist
  FROM audio_tracks
  WHERE user_id=?
  ORDER BY created_at DESC
  LIMIT {$perPage} OFFSET {$offset}
");
$st->execute([$userId]);
$tracks = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

/* ===== data: playlists (fast count via join) ===== */
$st = $pdo->prepare("
  SELECT p.id, p.title, COUNT(pt.track_id) AS tracks_cnt
  FROM audio_playlists p
  LEFT JOIN audio_playlist_tracks pt ON pt.playlist_id = p.id
  WHERE p.user_id=?
  GROUP BY p.id
  ORDER BY p.created_at DESC
");
$st->execute([$userId]);
$playlists = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

/* ===== confirm texts once ===== */
$confirmDelPlaylist = match ($langNow) {
  'ru' => 'Удалить плейлист?',
  'en' => 'Delete playlist?',
  default => 'Видалити плейлист?',
};

$confirmDelTrack = match ($langNow) {
  'ru' => 'Удалить трек?',
  'en' => 'Delete track?',
  default => 'Видалити трек?',
};

/* ===== app iframe default page ===== */
$appTo = '/functional/audio/?lang=' . $langNow;
$appToEnc = urlencode($appTo);

/* =========================
   SEO (перед header)
========================= */
$title = audio_t('audio') . ' — ' . audio_t('my_music');
$meta_desc = $title;

/* canonical без параметрів (lang додасть seo.php) */
$canonical = function_exists('abs_url') ? abs_url('/functional/audio/') : '/functional/audio/';

/* приватна зона */
$seo_noindex = true;

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

<!-- audio.css: гарантовано вставляємо в <head> навіть при PJAX -->
<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="feed-layout">
  <aside>
    <div class="sidebar-sticky">
      <?php require __DIR__ . '/../../blocks/profile.php'; ?>
    </div>
  </aside>

  <section>
    <div class="container my-4">

      <!-- TOP CARD: Title + quota progress -->
      <div class="card mb-3">
        <div class="card-body">

          <div class="d-flex align-items-start justify-content-between flex-wrap gap-3">
            <div>
              <h1 class="h4 mb-1"><?= h($title) ?></h1>
              <div class="small text-muted">
                <?= h(audio_t('limit_per_file')) ?>: <b><?= h(audio_fmt_bytes($maxOne)) ?></b>
              </div>
              <div class="mt-2 d-flex gap-2 flex-wrap">
                <button class="btn btn-sm btn-outline-secondary" type="button" onclick="VM_Audio.playAllFromLibrary();">
                  ▶ <?= h(audio_t('play_all')) ?>
                </button>
                <a class="btn btn-sm btn-outline-secondary"
                   href="/functional/audio/app.php?lang=<?= h($langNow) ?>&to=<?= h($appToEnc) ?>"
                   target="_blank" rel="noopener noreferrer">
                  ↗ <?= h(audio_t('audio_app')) ?>
                </a>
              </div>
            </div>

            <div style="min-width:280px">
              <div class="small text-muted mb-1">
                <?= h(audio_t('used')) ?>: <b><?= h(audio_fmt_bytes($usedBytes)) ?></b>
                / <b><?= h(audio_fmt_bytes($quotaMax)) ?></b>
              </div>
              <div class="progress" style="height:10px;">
                <div class="progress-bar" role="progressbar"
                     style="width: <?= (int)$usedPct ?>%;"
                     aria-valuenow="<?= (int)$usedPct ?>" aria-valuemin="0" aria-valuemax="100"></div>
              </div>
            </div>
          </div>

        </div>
      </div>

      <!-- TOP AREA: Upload + Create playlist + Playlists list -->
      <div class="row g-3 mb-3">

        <!-- Upload -->
        <div class="col-12 col-lg-4">
          <div class="card h-100">
            <div class="card-body">
              <div class="fw-semibold mb-2"><?= h(audio_t('upload_tracks')) ?></div>

              <form action="/functional/audio/upload.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf" value="<?= h($csrf) ?>">

                <input class="form-control form-control-sm" type="file" name="files[]" accept="audio/*" multiple required>
                <div class="form-text">
                  <?= h(audio_t('limit_per_file')) ?>: <?= h(audio_fmt_bytes($maxOne)) ?>
                </div>

                <button class="btn btn-sm btn-primary mt-2" type="submit"><?= h(audio_t('upload')) ?></button>
              </form>
            </div>
          </div>
        </div>

        <!-- Create playlist + delete playlist -->
        <div class="col-12 col-lg-4">
          <div class="card h-100">
            <div class="card-body">
              <div class="fw-semibold mb-2"><?= h(audio_t('create_playlist')) ?></div>

              <form action="/functional/audio/playlist_create.php" method="post">
                <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                <input class="form-control form-control-sm" type="text" name="title" maxlength="255"
                       placeholder="<?= h(audio_t('playlist_title')) ?>" required>
                <button class="btn btn-sm btn-outline-secondary mt-2" type="submit"><?= h(audio_t('create')) ?></button>
              </form>

              <?php if ($playlists): ?>
                <hr>
                <div class="fw-semibold mb-2"><?= h(audio_t('delete')) ?> (<?= h(audio_t('playlists')) ?>)</div>

                <form method="post" action="/functional/audio/playlist_delete.php"
                      onsubmit="return confirm(<?= json_encode($confirmDelPlaylist, JSON_UNESCAPED_UNICODE) ?>);">
                  <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                  <select class="form-select form-select-sm" name="id" required>
                    <option value=""><?= h(audio_t('choose_playlist')) ?></option>
                    <?php foreach ($playlists as $pl): ?>
                      <option value="<?= (int)$pl['id'] ?>"><?= h((string)$pl['title']) ?></option>
                    <?php endforeach; ?>
                  </select>
                  <button class="btn btn-sm btn-outline-danger mt-2" type="submit"><?= h(audio_t('delete')) ?></button>
                </form>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- Playlists list -->
        <div class="col-12 col-lg-4">
          <div class="card h-100">
            <div class="card-body">
              <div class="fw-semibold mb-2"><?= h(audio_t('playlists')) ?></div>

              <?php if (!$playlists): ?>
                <div class="text-muted">—</div>
              <?php else: ?>
                <div class="list-group">
                  <?php foreach ($playlists as $pl): ?>
                    <a class="list-group-item list-group-item-action d-flex align-items-center justify-content-between"
                       href="/functional/audio/playlist_view.php?id=<?= (int)$pl['id'] ?>&lang=<?= h($langNow) ?>">
                      <span>🎵 <?= h((string)$pl['title']) ?></span>
                      <span class="text-muted small"><?= (int)$pl['tracks_cnt'] ?></span>
                    </a>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>

            </div>
          </div>
        </div>

      </div>

      <!-- TRACKS: full width -->
      <div class="card">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-2">
            <div class="fw-semibold">
              <?= h(audio_t('tracks')) ?> (<?= (int)$tracksTotal ?>)
              <?php if ($pagesTotal > 1): ?>
                <span class="text-muted small"> • page <?= (int)$page ?>/<?= (int)$pagesTotal ?></span>
              <?php endif; ?>
            </div>
            <?php if ($tracksTotal > 0): ?>
              <button class="btn btn-sm btn-outline-secondary" type="button" onclick="VM_Audio.playAllFromLibrary();">
                ▶ <?= h(audio_t('play_all')) ?>
              </button>
            <?php endif; ?>
          </div>

          <?php if (!$tracks): ?>
            <div class="text-muted">—</div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm mb-0 audio-table">
                <thead>
                  <tr>
                    <th style="width:90px;">▶</th>
                    <th><?= h(audio_t('title')) ?></th>
                    <th style="width:220px;"><?= h(audio_t('artist')) ?></th>
                    <th style="width:340px;"><?= h(audio_t('actions')) ?></th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($tracks as $t): ?>
                    <?php
                      $tid = (int)($t['id'] ?? 0);
                      if ($tid <= 0) continue;

                      $ttl = (string)($t['title'] ?? '');
                      $art = (string)($t['artist'] ?? '');

                      $streamUrl = '/functional/audio/stream.php?id=' . $tid; // приватно, lang не критичний
                      $trackJson = json_encode([
                        'id' => $tid,
                        'title' => $ttl,
                        'artist' => $art,
                        'url' => $streamUrl,
                      ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                    ?>
                    <tr data-track='<?= h((string)$trackJson) ?>'>

                      <td>
                        <button class="btn btn-sm btn-outline-secondary" type="button" onclick="VM_Audio.playFromRow(this);">▶</button>
                      </td>

                      <td style="min-width:260px">
                        <form class="d-flex gap-2 align-items-center" method="post" action="/functional/audio/track_update.php">
                          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                          <input type="hidden" name="id" value="<?= $tid ?>">
                          <input class="form-control form-control-sm" name="title" value="<?= h($ttl) ?>" maxlength="255">
                          <button class="btn btn-sm btn-outline-secondary" type="submit"><?= h(audio_t('save')) ?></button>
                        </form>
                      </td>

                      <td>
                        <form class="d-flex gap-2 align-items-center" method="post" action="/functional/audio/track_update.php">
                          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                          <input type="hidden" name="id" value="<?= $tid ?>">
                          <input type="hidden" name="title" value="<?= h($ttl) ?>">
                          <input class="form-control form-control-sm" name="artist" value="<?= h($art) ?>" maxlength="255">
                          <button class="btn btn-sm btn-outline-secondary" type="submit"><?= h(audio_t('save')) ?></button>
                        </form>
                      </td>

                      <td>
                        <div class="d-flex flex-wrap gap-2">

                          <form class="d-flex gap-2" method="post" action="/functional/audio/playlist_add_track.php">
                            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                            <input type="hidden" name="track_id" value="<?= $tid ?>">
                            <select class="form-select form-select-sm" name="playlist_id" required>
                              <option value=""><?= h(audio_t('choose_playlist')) ?></option>
                              <?php foreach ($playlists as $pl): ?>
                                <option value="<?= (int)$pl['id'] ?>"><?= h((string)$pl['title']) ?></option>
                              <?php endforeach; ?>
                            </select>
                            <button class="btn btn-sm btn-outline-secondary" type="submit"><?= h(audio_t('add_to_playlist')) ?></button>
                          </form>

                          <form method="post" action="/functional/audio/track_delete.php"
                                onsubmit="return confirm(<?= json_encode($confirmDelTrack, JSON_UNESCAPED_UNICODE) ?>);">
                            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                            <input type="hidden" name="id" value="<?= $tid ?>">
                            <button class="btn btn-sm btn-outline-danger" type="submit">🗑 <?= h(audio_t('delete')) ?></button>
                          </form>

                        </div>
                      </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/?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>

    </div>
  </section>

  <aside>
    <div class="sidebar-sticky">
      <?php require __DIR__ . '/../../blocks/groups.php'; ?>
    </div>
  </aside>
</div>

<script>
window.VM_Audio = {
  _safeParse(jsonStr) {
    try { return JSON.parse(jsonStr); } catch (e) { return null; }
  },

  playFromRow(btn) {
    const tr = btn && btn.closest ? btn.closest('tr[data-track]') : null;
    if (!tr) return;

    const current = this._safeParse(tr.getAttribute('data-track') || '');
    if (!current || !current.id) return;

    // Глобальний плеєр (VMGA) — якщо підключений
    if (window.VMGA && typeof window.VMGA.playTrackById === 'function') {
      window.VMGA.playTrackById(current.id).catch(()=>{});
      return;
    }

    // fallback: Audio App
    window.open('/functional/audio/app.php?lang=<?= h($langNow) ?>&to=<?= h($appToEnc) ?>#play=track&id=' + encodeURIComponent(current.id), '_blank', 'noopener');
  },

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

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