<?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';
require_once __DIR__ . '/includes/metadata_requests.php';

function metadataRequestJson($success, $message, $data = [], $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    echo json_encode(array_merge([
        'success' => (bool)$success,
        'message' => ensureUtf8String($message),
    ], $data), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    metadataRequestJson(false, '지원하지 않는 요청입니다.', [], 405);
}

requireCsrfToken();

try {
    ensureMetadataRequestsTable();

    $typeLabels = metadataRequestTypeLabels();
    $songId = (int)($_POST['song_id'] ?? 0);
    $requestType = (string)($_POST['request_type'] ?? 'other');
    if (!array_key_exists($requestType, $typeLabels)) {
        $requestType = 'other';
    }

    if ($songId <= 0) {
        metadataRequestJson(false, '곡 정보를 확인할 수 없습니다.', [], 422);
    }

    $pdo = getDBConnection();
    $songStmt = $pdo->prepare("
        SELECT id, title, artist, album, genre, year
        FROM songs
        WHERE id = :id AND COALESCE(is_missing, 0) = 0
        LIMIT 1
    ");
    $songStmt->execute([':id' => $songId]);
    $song = $songStmt->fetch();
    if (!$song) {
        metadataRequestJson(false, '요청할 곡을 찾을 수 없습니다.', [], 404);
    }

    $suggestedValue = metadataRequestCleanText($_POST['suggested_value'] ?? '', 3000);
    $reason = metadataRequestCleanText($_POST['reason'] ?? '', 1200);
    $pageUrl = metadataRequestSanitizeUrl($_POST['page_url'] ?? '');
    $adminUserId = isLoggedIn() ? (int)($_SESSION['admin_user_id'] ?? 0) : null;
    $ipHash = metadataRequestClientHash();
    $userAgent = metadataRequestCleanText($_SERVER['HTTP_USER_AGENT'] ?? '', 255);

    $suggestedLength = function_exists('mb_strlen') ? mb_strlen($suggestedValue, 'UTF-8') : strlen($suggestedValue);
    $reasonLength = function_exists('mb_strlen') ? mb_strlen($reason, 'UTF-8') : strlen($reason);
    if ($suggestedLength < 2 && $reasonLength < 4) {
        metadataRequestJson(false, '수정 제안 내용이나 요청 사유를 조금 더 입력해 주세요.', [], 422);
    }
    if (!metadataRequestCanSubmit($songId, $requestType, $adminUserId, $ipHash)) {
        metadataRequestJson(false, '같은 곡의 같은 유형 요청이 최근에 접수되었습니다. 잠시 후 다시 시도해 주세요.', [], 429);
    }

    $stmt = $pdo->prepare("
        INSERT INTO metadata_correction_requests
            (song_id, request_type, status, current_title, current_artist, current_album, current_genre, current_year,
             suggested_value, reason, requester_admin_id, requester_ip_hash, user_agent, page_url)
        VALUES
            (:song_id, :request_type, 'received', :current_title, :current_artist, :current_album, :current_genre, :current_year,
             :suggested_value, :reason, :requester_admin_id, :requester_ip_hash, :user_agent, :page_url)
    ");
    $stmt->execute([
        ':song_id' => $songId,
        ':request_type' => $requestType,
        ':current_title' => metadataRequestCleanText($song['title'] ?? '', 255),
        ':current_artist' => metadataRequestCleanText($song['artist'] ?? '', 255),
        ':current_album' => metadataRequestCleanText($song['album'] ?? '', 255),
        ':current_genre' => metadataRequestCleanText($song['genre'] ?? '', 120),
        ':current_year' => metadataRequestCleanText($song['year'] ?? '', 20),
        ':suggested_value' => $suggestedValue !== '' ? $suggestedValue : null,
        ':reason' => $reason !== '' ? $reason : null,
        ':requester_admin_id' => $adminUserId ?: null,
        ':requester_ip_hash' => $ipHash,
        ':user_agent' => $userAgent !== '' ? $userAgent : null,
        ':page_url' => $pageUrl !== '' ? $pageUrl : null,
    ]);

    $requestId = (int)$pdo->lastInsertId();
    if (function_exists('writeAppLog')) {
        writeAppLog('info', 'metadata_request', 'Metadata correction request submitted', [
            'request_id' => $requestId,
            'song_id' => $songId,
            'request_type' => $requestType,
            'admin_user_id' => $adminUserId,
        ]);
    }

    metadataRequestJson(true, '음악 정보 수정 요청이 접수되었습니다.', [
        'data' => [
            'id' => $requestId,
            'song_id' => $songId,
            'request_type' => $requestType,
        ],
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'metadata_request_error', 'Metadata request submit failed', [
            'error' => limitLogText($e->getMessage(), 300),
        ]);
    }
    metadataRequestJson(false, '수정 요청 접수 중 문제가 발생했습니다. 잠시 후 다시 시도해 주세요.', [], 500);
}
