<?php
/**
 * Save lyrics for a song.
 * AJAX requests receive JSON; normal POST falls back to song detail redirect.
 */

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

$isAjax = (
    (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
    || (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)
);

function lyricsSaveFail(string $message, int $statusCode, bool $isAjax): void {
    if ($isAjax) {
        jsonResponse(['success' => false, 'message' => $message], $statusCode);
        exit;
    }
    http_response_code($statusCode);
    die(h($message));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    lyricsSaveFail('허용되지 않는 요청 방식입니다.', 405, $isAjax);
}

requireCsrfToken();

$songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : 0;
$lyricsText = isset($_POST['lyrics_text']) ? trim(ensureUtf8String($_POST['lyrics_text'])) : '';

if ($songId <= 0) {
    lyricsSaveFail('올바르지 않은 곡 ID입니다.', 400, $isAjax);
}

try {
    $pdo = getDBConnection();

    $songCheck = $pdo->prepare("SELECT id FROM songs WHERE id = :id AND COALESCE(is_missing, 0) = 0 LIMIT 1");
    $songCheck->execute([':id' => $songId]);
    if (!$songCheck->fetchColumn()) {
        lyricsSaveFail('곡을 찾을 수 없습니다.', 404, $isAjax);
    }

    $sql = "
        INSERT INTO lyrics (song_id, lyrics_text, source)
        VALUES (:song_id, :lyrics_text, 'manual')
        ON DUPLICATE KEY UPDATE
            lyrics_text = :lyrics_text_update,
            source = 'manual',
            updated_at = CURRENT_TIMESTAMP
    ";
    $stmt = $pdo->prepare($sql);
    $lyricsValue = $lyricsText !== '' ? $lyricsText : null;
    $stmt->execute([
        ':song_id' => $songId,
        ':lyrics_text' => $lyricsValue,
        ':lyrics_text_update' => $lyricsValue,
    ]);

    if (function_exists('writeAppLog')) {
        writeAppLog('info', 'lyrics_updated', 'Lyrics saved', ['song_id' => $songId]);
    }

    $lyricsStmt = $pdo->prepare("
        SELECT
            s.id,
            s.title,
            s.artist,
            s.album,
            l.lyrics_text,
            l.updated_at AS lyrics_updated_at
        FROM songs s
        LEFT JOIN lyrics l ON l.song_id = s.id
        WHERE s.id = :song_id
        LIMIT 1
    ");
    $lyricsStmt->execute([':song_id' => $songId]);
    $lyricsRow = $lyricsStmt->fetch() ?: ['id' => $songId, 'lyrics_text' => $lyricsText];
    $savedLyrics = ensureUtf8String($lyricsRow['lyrics_text'] ?? '');
    $hasLyrics = trim($savedLyrics) !== '';

    $data = [
        'id' => (int)($lyricsRow['id'] ?? $songId),
        'song_id' => (int)($lyricsRow['id'] ?? $songId),
        'title' => ensureUtf8String($lyricsRow['title'] ?? ''),
        'artist' => artistName($lyricsRow['artist'] ?? ''),
        'album' => albumName($lyricsRow['album'] ?? ''),
        'lyrics' => $savedLyrics,
        'has_lyrics' => $hasLyrics,
        'updated_at' => ensureUtf8String($lyricsRow['lyrics_updated_at'] ?? ''),
        'lyrics_url' => 'api/get_lyrics.php?song_id=' . $songId,
        'song_url' => 'song.php?id=' . $songId,
    ];

    if ($isAjax) {
        jsonResponse([
            'success' => true,
            'message' => '가사가 저장되었습니다.',
            'data' => $data,
            'song_id' => $data['song_id'],
            'lyrics' => $data['lyrics'],
            'has_lyrics' => $data['has_lyrics'],
            'updated_at' => $data['updated_at'],
            'redirect' => $data['song_url'],
        ]);
        exit;
    }

    header('Location: song.php?id=' . $songId);
    exit;
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'lyrics_save_error', 'Lyrics save failed', ['song_id' => $songId, 'error' => $e->getMessage()]);
    }
    lyricsSaveFail('가사를 저장하지 못했습니다.', 500, $isAjax);
}
