<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

requirePermission('metadata_edit');

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

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

requireCsrfToken();

$album = albumDescriptionKey($_POST['album'] ?? '');
$artist = albumDescriptionKey($_POST['artist'] ?? '');
$description = trim(ensureUtf8String($_POST['description'] ?? ''));

if ($album === '') {
    albumDescriptionSaveFail('앨범명이 올바르지 않습니다.', 400, $isAjax);
}

if (function_exists('mb_strlen') && mb_strlen($description, 'UTF-8') > 12000) {
    $description = mb_substr($description, 0, 12000, 'UTF-8');
} elseif (strlen($description) > 48000) {
    $description = substr($description, 0, 48000);
}

try {
    $adminId = isset($_SESSION['admin_user_id']) ? (int)$_SESSION['admin_user_id'] : null;
    $result = saveAlbumDescription($album, $artist, $description, $adminId);

    if (function_exists('writeAppLog')) {
        writeAppLog('info', 'album_description_updated', 'Album description updated', [
            'album' => $album,
            'artist' => $artist,
            'has_custom' => $result['saved'],
        ]);
    }

    if ($isAjax) {
        jsonResponse([
            'success' => true,
            'message' => $result['saved'] ? '앨범 소개를 저장했습니다.' : '앨범 소개를 자동 생성 상태로 되돌렸습니다.',
            'data' => [
                'album' => $album,
                'artist' => $artist,
                'description' => $result['description'],
                'has_custom' => $result['saved'],
                'updated_at' => $result['updated_at'],
            ],
        ]);
        exit;
    }

    $defaultReturn = 'album.php?' . http_build_query(['album' => $album, 'artist' => $artist]);
    $returnUrl = safeReturnUrl($_POST['return_url'] ?? '', $defaultReturn);
    header('Location: ' . $returnUrl);
    exit;
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'album_description_save_error', 'Album description save failed', [
            'album' => $album,
            'artist' => $artist,
            'error' => $e->getMessage(),
        ]);
    }
    albumDescriptionSaveFail('앨범 소개를 저장하지 못했습니다.', 500, $isAjax);
}
