<?php
declare(strict_types=1);

/**
 * functional/audio/track_delete.php
 * Відповідає за:
 * - видалення треку користувача
 * - видалення файла з диска (best-effort)
 * - прибирання з плейлистів
 * - 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);
if ($id <= 0) {
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 303);
    exit;
}

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

/* fetch track rel_path */
$st = $pdo->prepare("SELECT rel_path FROM audio_tracks WHERE id=? AND user_id=? LIMIT 1");
$st->execute([$id, $userId]);
$row = $st->fetch(PDO::FETCH_ASSOC);

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

$rel = (string)($row['rel_path'] ?? '');
$rel = '/' . ltrim($rel, '/');

$absReal = null;

/* compute safe absolute file path (only inside user's /upload/<username>/music/) */
$expectedPrefix = '/' . trim(audio_user_music_dir_rel($me), '/');
if ($rel !== '' && str_starts_with($rel, $expectedPrefix . '/')) {
    $abs = audio_rel_to_abs($rel);
    $absReal = realpath($abs);
}

/* ensure file is inside /upload root */
$audioRoot = realpath(audio_storage_root_abs());
$audioRoot = $audioRoot ? (rtrim(str_replace('\\', '/', $audioRoot), '/') . '/') : null;

if ($absReal && $audioRoot) {
    $absNorm = str_replace('\\', '/', $absReal);
    if (strpos($absNorm, $audioRoot) !== 0) {
        $absReal = null; // do not delete outside upload
    }
} else {
    $absReal = null;
}

/* delete DB rows first (transaction), then file best-effort */
try {
    $pdo->beginTransaction();

    // remove from playlists (works even without FK CASCADE)
    $st = $pdo->prepare("DELETE FROM audio_playlist_tracks WHERE track_id=?");
    $st->execute([$id]);

    $st = $pdo->prepare("DELETE FROM audio_tracks WHERE id=? AND user_id=?");
    $st->execute([$id, $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;
}

/* best-effort delete file after commit */
if ($absReal && is_file($absReal)) {
    @unlink($absReal);
}

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