<?php
declare(strict_types=1);

/**
 * functional/audio/playlist_create.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;
}

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

$title = post_str('title', '');
$title = trim($title);
$title = preg_replace('/[\x00-\x1F\x7F]/u', ' ', $title) ?? $title; // control chars
$title = preg_replace('/\s+/u', ' ', $title) ?? $title;            // collapse spaces
$title = trim($title);

if ($title === '') $title = 'Playlist';
$title = mb_substr($title, 0, 255);

try {
    $st = $pdo->prepare("
        INSERT INTO audio_playlists (user_id, title, created_at, updated_at)
        VALUES (?, ?, ?, NULL)
    ");
    $st->execute([$userId, $title, date('Y-m-d H:i:s')]);

    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;