<?php
header('Content-Type: application/json; charset=utf-8');

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';

try {
    $pdo = getDBConnection();
    $stmt = $pdo->query("
        SELECT p.id, p.name, p.description, COUNT(ps.id) AS song_count
        FROM playlists p
        LEFT JOIN playlist_songs ps ON p.id = ps.playlist_id
        GROUP BY p.id
        ORDER BY p.name ASC
    ");
    $playlists = $stmt->fetchAll();

    foreach ($playlists as &$playlist) {
        $playlist['name'] = ensureUtf8String($playlist['name'] ?? '');
        $playlist['description'] = ensureUtf8String($playlist['description'] ?? '');
    }
    unset($playlist);

    jsonResponse([
        'success' => true,
        'playlists' => $playlists,
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'playlist_error', 'Playlist list load failed', ['error' => $e->getMessage()]);
    }
    jsonResponse(['success' => false, 'message' => '플레이리스트 목록을 불러오지 못했습니다.'], 500);
}
