<?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/feedback.php';

function feedbackJson($success, $message, $data = [], $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    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') {
    feedbackJson(false, '지원하지 않는 요청입니다.', [], 405);
}

requireCsrfToken();

try {
    ensureFeedbackTable();

    $types = feedbackTypeLabels();
    $type = (string)($_POST['feedback_type'] ?? 'bug');
    if (!array_key_exists($type, $types)) $type = 'other';

    $title = feedbackCleanText($_POST['title'] ?? '', 160);
    $body = feedbackCleanText($_POST['body'] ?? '', 3000);
    $pageUrl = feedbackSanitizeUrl($_POST['page_url'] ?? '');
    $pageTitle = feedbackCleanText($_POST['page_title'] ?? '', 180);
    $songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : 0;
    $songId = $songId > 0 ? $songId : null;
    $adminUserId = isLoggedIn() ? (int)($_SESSION['admin_user_id'] ?? 0) : null;
    $ipHash = feedbackClientHash();
    $userAgent = feedbackCleanText($_SERVER['HTTP_USER_AGENT'] ?? '', 255);

    $titleLength = function_exists('mb_strlen') ? mb_strlen($title, 'UTF-8') : strlen($title);
    $bodyLength = function_exists('mb_strlen') ? mb_strlen($body, 'UTF-8') : strlen($body);

    if ($titleLength < 3) {
        feedbackJson(false, '제목을 3자 이상 입력해 주세요.', [], 422);
    }
    if ($bodyLength < 8) {
        feedbackJson(false, '내용을 조금 더 자세히 입력해 주세요.', [], 422);
    }
    if (!feedbackCanSubmit($adminUserId, $ipHash)) {
        feedbackJson(false, '짧은 시간에 너무 많은 신고가 접수되었습니다. 잠시 후 다시 시도해 주세요.', [], 429);
    }

    $pdo = getDBConnection();
    $stmt = $pdo->prepare("
        INSERT INTO app_feedback
            (feedback_type, status, title, body, page_url, page_title, song_id, admin_user_id, ip_hash, user_agent)
        VALUES
            (:feedback_type, 'received', :title, :body, :page_url, :page_title, :song_id, :admin_user_id, :ip_hash, :user_agent)
    ");
    $stmt->execute([
        ':feedback_type' => $type,
        ':title' => $title,
        ':body' => $body,
        ':page_url' => $pageUrl !== '' ? $pageUrl : null,
        ':page_title' => $pageTitle !== '' ? $pageTitle : null,
        ':song_id' => $songId,
        ':admin_user_id' => $adminUserId ?: null,
        ':ip_hash' => $ipHash,
        ':user_agent' => $userAgent !== '' ? $userAgent : null,
    ]);

    $feedbackId = (int)$pdo->lastInsertId();
    if (function_exists('writeAppLog')) {
        writeAppLog('info', 'feedback', 'Feedback submitted', [
            'feedback_id' => $feedbackId,
            'feedback_type' => $type,
            'song_id' => $songId,
            'admin_user_id' => $adminUserId,
        ]);
    }

    feedbackJson(true, '피드백이 접수되었습니다. 확인 후 개선에 반영하겠습니다.', [
        'data' => ['id' => $feedbackId],
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'feedback_error', 'Feedback submit failed', [
            'error' => limitLogText($e->getMessage(), 300),
        ]);
    }
    feedbackJson(false, '피드백 접수 중 문제가 발생했습니다. 잠시 후 다시 시도해 주세요.', [], 500);
}
