<?php
declare(strict_types=1);

/**
 * functional/audio/playlist_add_track.php
 * Відповідає за:
 * - додавання треку в плейлист (позиція = max+1)
 * - safe redirect back
 * - захист від дублювання
 * - транзакційно (щоб позиція не зламалась при паралельних запитах)
 */

require_once __DIR__ . '/_boot.php';

$back = function_exists('post_str') ? post_str('back', '') : (string)($_POST['back'] ?? '');
if (!function_exists('safe_local_path')) {
    function safe_local_path(string $path, string $fallback = '/'): string
    {
        $path = trim(str_replace(["\0", "\r", "\n"], '', $path));
        if ($path === '') return $fallback;

        $p = parse_url($path);
        $pathOnly = (string)($p['path'] ?? '');
        $q = isset($p['query']) && $p['query'] !== '' ? ('?' . $p['query']) : '';
        $out = $pathOnly . $q;

        if ($out === '' || $out[0] !== '/') $out = '/' . ltrim($out, '/');
        if (str_contains($out, "\0")) return $fallback;

        return $out;
    }
}
$back = safe_local_path($back, '/functional/audio/');

if (!is_post()) {
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 302);
    exit;
}

if (!csrf_check(post_str('csrf'))) {
    // можна поставити flash, якщо є
    if (function_exists('flash_set')) flash_set('err', 'CSRF');
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 302);
    exit;
}

$userId = (int)($me['id'] ?? 0);
$playlistId = post_int('playlist_id', 0);
$trackId = post_int('track_id', 0);

if ($userId <= 0 || $playlistId <= 0 || $trackId <= 0) {
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 303);
    exit;
}

/* validate ownership playlist */
$st = $pdo->prepare("SELECT 1 FROM audio_playlists WHERE id=? AND user_id=? LIMIT 1");
$st->execute([$playlistId, $userId]);
if (!$st->fetchColumn()) {
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 303);
    exit;
}

/* validate ownership track */
$st = $pdo->prepare("SELECT 1 FROM audio_tracks WHERE id=? AND user_id=? LIMIT 1");
$st->execute([$trackId, $userId]);
if (!$st->fetchColumn()) {
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 303);
    exit;
}

/* if already in playlist -> just back */
$st = $pdo->prepare("SELECT 1 FROM audio_playlist_tracks WHERE playlist_id=? AND track_id=? LIMIT 1");
$st->execute([$playlistId, $trackId]);
if ($st->fetchColumn()) {
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 303);
    exit;
}

try {
    $pdo->beginTransaction();

    // lock rows for this playlist to safely compute next position
    $st = $pdo->prepare("SELECT COALESCE(MAX(position),0) FROM audio_playlist_tracks WHERE playlist_id=? FOR UPDATE");
    $st->execute([$playlistId]);
    $pos = (int)$st->fetchColumn() + 1;

    $st = $pdo->prepare("
      INSERT INTO audio_playlist_tracks (playlist_id, track_id, position, added_at)
      VALUES (?, ?, ?, ?)
    ");
    $st->execute([$playlistId, $trackId, $pos, date('Y-m-d H:i:s')]);

    $pdo->commit();
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    // за бажанням: flash error
    if (function_exists('flash_set')) flash_set('err', 'DB error');
}

if (function_exists('redirect')) redirect($back);
header('Location: ' . $back, true, 303);
exit;