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

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

$songId = isset($_GET['song_id']) ? (int)$_GET['song_id'] : 0;

if ($songId <= 0) {
    jsonResponse(['success' => false, 'message' => '유효하지 않은 곡 ID입니다.'], 400);
    exit;
}

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT lyrics_text FROM lyrics WHERE song_id = :song_id");
    $stmt->execute([':song_id' => $songId]);
    $row = $stmt->fetch();

    jsonResponse([
        'success' => true,
        'lyrics' => ($row && !empty($row['lyrics_text'])) ? ensureUtf8String($row['lyrics_text']) : null,
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'lyrics_error', 'Lyrics load failed', ['song_id' => $songId, 'error' => $e->getMessage()]);
    }
    jsonResponse(['success' => false, 'message' => '가사를 불러오지 못했습니다.'], 500);
}
