<?php

function patchNoteTypeLabels() {
    return [
        'feature' => '기능 추가',
        'bugfix' => '버그 수정',
        'stability' => '안정화',
        'design' => '디자인 개선',
        'security' => '보안 개선',
    ];
}

function patchNoteTypeLabel($type) {
    $labels = patchNoteTypeLabels();
    return $labels[(string)$type] ?? $labels['stability'];
}

function patchNoteTypeClass($type) {
    $type = (string)$type;
    return array_key_exists($type, patchNoteTypeLabels()) ? $type : 'stability';
}

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

    $pdo = getDBConnection();
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS app_patch_notes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            release_version VARCHAR(80) DEFAULT NULL,
            note_type VARCHAR(30) NOT NULL DEFAULT 'stability',
            title VARCHAR(180) NOT NULL,
            body TEXT NOT NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            published_at DATETIME DEFAULT NULL,
            created_by_admin INT DEFAULT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_patch_active_published (is_active, published_at),
            KEY idx_patch_type (note_type),
            KEY idx_patch_updated (updated_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
}

function patchNoteCleanText($value, $limit = 0) {
    $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 patchNoteDateValue($value) {
    $value = trim((string)$value);
    if ($value === '') return null;
    $timestamp = strtotime($value);
    return $timestamp ? date('Y-m-d H:i:s', $timestamp) : null;
}

function patchNoteInputDate($value) {
    if (!$value) return '';
    $time = strtotime((string)$value);
    return $time ? date('Y-m-d\TH:i', $time) : '';
}

function fetchVisiblePatchNotes($limit = 10) {
    ensurePatchNotesTable();
    $limit = max(1, min(30, (int)$limit));
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("
        SELECT id, release_version, note_type, title, body, published_at, created_at, updated_at
        FROM app_patch_notes
        WHERE is_active = 1
          AND (published_at IS NULL OR published_at <= NOW())
        ORDER BY COALESCE(published_at, created_at) DESC, id DESC
        LIMIT $limit
    ");
    $stmt->execute();
    return $stmt->fetchAll();
}
