<?php
declare(strict_types=1);

/**
 * functional/audio/api_tracks.php
 * Відповідає за:
 * - JSON: tracks + playlists для Audio App
 */

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);
if ($userId <= 0) {
    audio_json(['ok' => false, 'error' => 'no_user'], 401);
}

/**
 * Підтримка пагінації:
 * - ?limit=5000&offset=0
 * Ліміти спеціально обмежені, щоб не “вивалити” БД.
 */
$limit  = get_int('limit', 5000);
$offset = get_int('offset', 0);

if ($limit <= 0) $limit = 5000;
if ($limit > 5000) $limit = 5000;

if ($offset < 0) $offset = 0;
if ($offset > 200000) $offset = 200000; // safety cap

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

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

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

/* ---------- Playlists + tracks count (fast: JOIN+GROUP BY) ---------- */
$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) ?: [];

$playlistsOut = [];
foreach ($playlists as $p) {
    $playlistsOut[] = [
        'id' => (int)($p['id'] ?? 0),
        'title' => (string)($p['title'] ?? ''),
        'tracks_cnt' => (int)($p['tracks_cnt'] ?? 0),
    ];
}

audio_json([
    'ok' => true,
    'tracks' => $tracksOut,
    'playlists' => $playlistsOut,
    'paging' => [
        'limit' => $limit,
        'offset' => $offset,
        'returned' => count($tracksOut),
    ],
]);