<?php
/**
 * Delete 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 lyricsDeleteFail(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') {
    lyricsDeleteFail('허용되지 않는 요청 방식입니다.', 405, $isAjax);
}

requireCsrfToken();

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

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

try {
    $pdo = getDBConnection();

    $stmt = $pdo->prepare("DELETE FROM lyrics WHERE song_id = :song_id");
    $stmt->execute([':song_id' => $songId]);

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

    if ($isAjax) {
        $data = [
            'id' => $songId,
            'song_id' => $songId,
            'lyrics' => '',
            'has_lyrics' => false,
            'updated_at' => '',
            'lyrics_url' => 'api/get_lyrics.php?song_id=' . $songId,
            'song_url' => 'song.php?id=' . $songId,
        ];
        jsonResponse([
            'success' => true,
            'message' => '가사가 삭제되었습니다.',
            'data' => $data,
            'song_id' => $songId,
            'lyrics' => '',
            'has_lyrics' => false,
            'updated_at' => '',
            'redirect' => $data['song_url'],
        ]);
        exit;
    }

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