<?php
declare(strict_types=1);

/**
 * functional/audio/api_playlist.php
 * Відповідає за:
 * - JSON треків конкретного плейлиста (в порядку position)
 */

require_once __DIR__ . '/_boot.php';

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet', true);
}

if (!function_exists('audio_json')) {
    function audio_json(array $data, int $code = 200): void
    {
        http_response_code($code);
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
}

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

if ($userId <= 0) {
    audio_json(['ok' => false, 'error' => 'no_user'], 401);
}
if ($id <= 0) {
    audio_json(['ok' => false, 'error' => 'bad_id'], 400);
}

/* playlist exists and belongs to user */
$st = $pdo->prepare("SELECT id, title FROM audio_playlists WHERE id=? AND user_id=? LIMIT 1");
$st->execute([$id, $userId]);
$pl = $st->fetch(PDO::FETCH_ASSOC);

if (!$pl) {
    audio_json(['ok' => false, 'error' => 'not_found'], 404);
}

/* safety limit (can adjust) */
$limit = 2000;

$st = $pdo->prepare("
    SELECT 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 {$limit}
");
$st->execute([$id, $userId]);
$tracks = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

$out = [];
foreach ($tracks as $t) {
    $tid = (int)($t['id'] ?? 0);
    if ($tid <= 0) continue;

    $out[] = [
        'id' => $tid,
        'title' => (string)($t['title'] ?? ''),
        'artist' => (string)($t['artist'] ?? ''),
        'url' => '/functional/audio/stream.php?id=' . rawurlencode((string)$tid),
    ];
}

audio_json([
    'ok' => true,
    'playlist' => [
        'id' => (int)$pl['id'],
        'title' => (string)$pl['title'],
    ],
    'tracks' => $out,
]);