<?php
declare(strict_types=1);

/**
 * functional/audio/track_update.php
 * Відповідає за:
 * - редагування назви/виконавця треку
 * - safe redirect back
 * - нормалізація title/artist
 */

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;
}

/* input: allow partial update */
$title  = function_exists('post_str') ? post_str('title', '') : (string)($_POST['title'] ?? '');
$artist = function_exists('post_str') ? post_str('artist', '') : trim((string)($_POST['artist'] ?? ''));

$title = trim($title);
$artist = trim($artist);

$title  = preg_replace('/[\x00-\x1F\x7F]/u', ' ', $title) ?? $title;
$artist = preg_replace('/[\x00-\x1F\x7F]/u', ' ', $artist) ?? $artist;

$title  = preg_replace('/\s+/u', ' ', $title) ?? $title;
$artist = preg_replace('/\s+/u', ' ', $artist) ?? $artist;

$title  = trim($title);
$artist = trim($artist);

if ($title === '') $title = 'Track';

$title  = mb_substr($title, 0, 255);
$artist = mb_substr($artist, 0, 255);

$artistDb = ($artist !== '') ? $artist : null;

/* ensure track exists & belongs to user */
$st = $pdo->prepare("SELECT 1 FROM audio_tracks WHERE id=? AND user_id=? LIMIT 1");
$st->execute([$id, $userId]);
if (!$st->fetchColumn()) {
    if (function_exists('flash_set')) flash_set('err', 'Not found');
    if (function_exists('redirect')) redirect($back);
    header('Location: ' . $back, true, 303);
    exit;
}

try {
    $st = $pdo->prepare("UPDATE audio_tracks SET title=?, artist=?, updated_at=? WHERE id=? AND user_id=?");
    $st->execute([$title, $artistDb, date('Y-m-d H:i:s'), $id, $userId]);
    if (function_exists('flash_set')) flash_set('ok', 'OK');
} catch (Throwable $e) {
    if (function_exists('flash_set')) flash_set('err', 'DB error');
}

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