<?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';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/functions_notes.php';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'POST 요청만 허용됩니다.'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (!verifyCsrfToken()) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => '보안 토큰이 올바르지 않습니다.'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $songId = (int)($_POST['song_id'] ?? 0);
    $action = (string)($_POST['action'] ?? 'save');
    if ($songId <= 0) throw new RuntimeException('곡 정보를 확인할 수 없습니다.');

    if ($action === 'delete') {
        deleteSongNote($songId);
        $note = null;
    } else {
        saveSongNote($songId, $_POST['note_text'] ?? '');
        $note = getSongNote($songId);
    }
    echo json_encode([
        'success' => true,
        'message' => $action === 'delete' ? '메모를 삭제했습니다.' : '메모를 저장했습니다.',
        'note' => $note ? (string)$note['note_text'] : '',
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'note_error', 'Note save failed', ['song_id' => $_POST['song_id'] ?? null, 'error' => $e->getMessage()]);
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '메모 처리 중 오류가 발생했습니다.'], JSON_UNESCAPED_UNICODE);
}
