<?php
declare(strict_types=1);

/**
 * functional/audio/playlist_delete.php
 * Відповідає за:
 * - видалення плейлиста користувача
 * - 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'))) {
    if (function_exists('flash_set')) flash_set('err', 'CSRF');
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 302);
    exit;
}

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

if ($userId <= 0) {
    if (function_exists('redirect')) redirect('/login.php');
    header('Location: /login.php', true, 302);
    exit;
}

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

/* ensure playlist belongs to user */
$st = $pdo->prepare("SELECT id FROM audio_playlists WHERE id=? AND user_id=? LIMIT 1");
$st->execute([$id, $userId]);
$pid = (int)$st->fetchColumn();

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

try {
    $pdo->beginTransaction();

    // delete relations first (works even without FK)
    $st = $pdo->prepare("DELETE FROM audio_playlist_tracks WHERE playlist_id=?");
    $st->execute([$pid]);

    $st = $pdo->prepare("DELETE FROM audio_playlists WHERE id=? AND user_id=?");
    $st->execute([$pid, $userId]);

    $pdo->commit();

    if (function_exists('flash_set')) flash_set('ok', 'OK');
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    if (function_exists('flash_set')) flash_set('err', 'DB error');
}

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