<?php

function feedbackTypeLabels() {
    return [
        'bug' => '오류 신고',
        'usability' => '사용 불편',
        'feature' => '기능 제안',
        'other' => '기타',
    ];
}

function feedbackStatusLabels() {
    return [
        'received' => '접수',
        'reviewing' => '확인 중',
        'completed' => '처리 완료',
        'held' => '보류',
    ];
}

function feedbackTypeLabel($type) {
    $labels = feedbackTypeLabels();
    return $labels[(string)$type] ?? $labels['other'];
}

function feedbackStatusLabel($status) {
    $labels = feedbackStatusLabels();
    return $labels[(string)$status] ?? $labels['received'];
}

function ensureFeedbackTable() {
    static $checked = false;
    if ($checked) return;
    $checked = true;

    $pdo = getDBConnection();
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS app_feedback (
            id INT AUTO_INCREMENT PRIMARY KEY,
            feedback_type VARCHAR(30) NOT NULL DEFAULT 'bug',
            status VARCHAR(30) NOT NULL DEFAULT 'received',
            title VARCHAR(160) NOT NULL,
            body TEXT NOT NULL,
            page_url VARCHAR(600) DEFAULT NULL,
            page_title VARCHAR(180) DEFAULT NULL,
            song_id INT DEFAULT NULL,
            admin_user_id INT DEFAULT NULL,
            ip_hash CHAR(64) DEFAULT NULL,
            user_agent VARCHAR(255) DEFAULT NULL,
            admin_note TEXT DEFAULT NULL,
            handled_by_admin INT DEFAULT NULL,
            handled_at DATETIME DEFAULT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_feedback_status (status),
            KEY idx_feedback_type (feedback_type),
            KEY idx_feedback_created (created_at),
            KEY idx_feedback_song (song_id),
            KEY idx_feedback_admin_user (admin_user_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
}

function feedbackClientHash() {
    $ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
    if ($ip === '') return null;
    return hash('sha256', $ip . '|melonlite-feedback');
}

function feedbackCleanText($value, $limit) {
    $value = trim(maskInternalPathText(ensureUtf8String($value)));
    if ($limit > 0 && function_exists('mb_substr')) {
        return mb_substr($value, 0, $limit, 'UTF-8');
    }
    return $limit > 0 ? substr($value, 0, $limit) : $value;
}

function feedbackSanitizeUrl($value) {
    $value = trim(maskInternalPathText(ensureUtf8String($value)));
    if ($value === '') return '';

    $parts = @parse_url($value);
    if (!is_array($parts)) return '';

    $host = (string)($_SERVER['HTTP_HOST'] ?? '');
    if (!empty($parts['host']) && $host !== '' && strcasecmp($parts['host'], $host) !== 0) {
        return '';
    }

    $path = (string)($parts['path'] ?? '');
    if ($path === '') $path = currentRelativeUrl();

    $query = '';
    if (!empty($parts['query'])) {
        parse_str((string)$parts['query'], $queryParams);
        foreach (array_keys($queryParams) as $key) {
            if (preg_match('/path|file|dir|folder|root/i', (string)$key)) {
                unset($queryParams[$key]);
            }
        }
        $query = http_build_query($queryParams);
    }

    $safe = $path . ($query !== '' ? '?' . $query : '');
    $safe = str_replace('\\', '/', $safe);
    if (strpos($safe, '..') !== false) return '';
    if (function_exists('mb_substr')) return mb_substr($safe, 0, 600, 'UTF-8');
    return substr($safe, 0, 600);
}

function feedbackCanSubmit($adminUserId, $ipHash) {
    ensureFeedbackTable();
    $pdo = getDBConnection();
    $params = [];
    $conditions = [];

    if ($ipHash !== null && $ipHash !== '') {
        $conditions[] = 'ip_hash = :ip_hash';
        $params[':ip_hash'] = $ipHash;
    }
    if ((int)$adminUserId > 0) {
        $conditions[] = 'admin_user_id = :admin_user_id';
        $params[':admin_user_id'] = (int)$adminUserId;
    }
    if (empty($conditions)) return true;

    $sql = "SELECT COUNT(*) FROM app_feedback WHERE created_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND (" . implode(' OR ', $conditions) . ")";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return (int)$stmt->fetchColumn() < 5;
}
