<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/layout.php';
require_once dirname(__DIR__) . '/includes/patch_notes.php';

requirePermission('patch_note_manage');
ensurePatchNotesTable();

$pdo = getDBConnection();
$message = trim((string)($_GET['message'] ?? ''));
$status = trim((string)($_GET['status'] ?? 'success'));
$editId = max(0, (int)($_GET['edit'] ?? 0));
$types = patchNoteTypeLabels();

function patchNoteRedirect($status, $message, $extra = '') {
    header('Location: patch_notes.php?status=' . urlencode($status) . '&message=' . urlencode($message) . $extra);
    exit;
}

function patchNoteSafeError(Throwable $e) {
    $message = function_exists('maskInternalPathText') ? maskInternalPathText($e->getMessage()) : $e->getMessage();
    if (preg_match('/SQLSTATE|PDOException|Stack trace|Fatal error|Warning:|Notice:|[A-Z]:[\\\\\/]/i', $message)) {
        return '패치노트 저장 중 오류가 발생했습니다. 오류 로그를 확인해 주세요.';
    }
    return $message !== '' ? $message : '처리 중 오류가 발생했습니다.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'save') {
            $id = max(0, (int)($_POST['id'] ?? 0));
            $type = (string)($_POST['note_type'] ?? 'stability');
            if (!isset($types[$type])) $type = 'stability';

            $releaseVersion = patchNoteCleanText($_POST['release_version'] ?? '', 80);
            $title = patchNoteCleanText($_POST['title'] ?? '', 180);
            $body = patchNoteCleanText($_POST['body'] ?? '', 8000);
            $isActive = !empty($_POST['is_active']) ? 1 : 0;
            $publishedAt = patchNoteDateValue($_POST['published_at'] ?? '');

            if ($title === '') throw new RuntimeException('업데이트 제목을 입력하세요.');
            if ($body === '') throw new RuntimeException('업데이트 내용을 입력하세요.');

            if ($id > 0) {
                $stmt = $pdo->prepare("
                    UPDATE app_patch_notes
                    SET release_version = :release_version,
                        note_type = :note_type,
                        title = :title,
                        body = :body,
                        is_active = :is_active,
                        published_at = :published_at,
                        updated_at = NOW()
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':release_version' => $releaseVersion !== '' ? $releaseVersion : null,
                    ':note_type' => $type,
                    ':title' => $title,
                    ':body' => $body,
                    ':is_active' => $isActive,
                    ':published_at' => $publishedAt,
                    ':id' => $id,
                ]);
                $savedId = $id;
                $doneMessage = '패치노트를 수정했습니다.';
                writeAuditLog('patch_note_updated', 'Patch note updated #' . $id, 'success', 'info', 'patch_note', $id);
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO app_patch_notes
                        (release_version, note_type, title, body, is_active, published_at, created_by_admin)
                    VALUES
                        (:release_version, :note_type, :title, :body, :is_active, :published_at, :created_by_admin)
                ");
                $stmt->execute([
                    ':release_version' => $releaseVersion !== '' ? $releaseVersion : null,
                    ':note_type' => $type,
                    ':title' => $title,
                    ':body' => $body,
                    ':is_active' => $isActive,
                    ':published_at' => $publishedAt,
                    ':created_by_admin' => $_SESSION['admin_user_id'] ?? null,
                ]);
                $savedId = (int)$pdo->lastInsertId();
                $doneMessage = '패치노트를 등록했습니다.';
                writeAuditLog('patch_note_created', 'Patch note created #' . $savedId, 'success', 'info', 'patch_note', $savedId);
            }
            if (function_exists('writeAppLog')) {
                writeAppLog('info', 'patch_note', $doneMessage, ['patch_note_id' => $savedId, 'type' => $type]);
            }
            patchNoteRedirect('success', $doneMessage, '&edit=' . rawurlencode((string)$savedId));
        }

        if ($action === 'hide' || $action === 'show') {
            $id = max(0, (int)($_POST['id'] ?? 0));
            if ($id <= 0) throw new RuntimeException('패치노트 ID를 확인하세요.');
            $active = $action === 'show' ? 1 : 0;
            $stmt = $pdo->prepare("UPDATE app_patch_notes SET is_active = :is_active, updated_at = NOW() WHERE id = :id");
            $stmt->execute([':is_active' => $active, ':id' => $id]);
            $doneMessage = $active ? '패치노트를 다시 표시합니다.' : '패치노트를 숨김 처리했습니다.';
            writeAuditLog($active ? 'patch_note_shown' : 'patch_note_hidden', 'Patch note #' . $id, 'success', 'info', 'patch_note', $id);
            if (function_exists('writeAppLog')) writeAppLog('info', 'patch_note', $doneMessage, ['patch_note_id' => $id]);
            patchNoteRedirect('success', $doneMessage);
        }

        throw new RuntimeException('알 수 없는 작업입니다.');
    } catch (Throwable $e) {
        if (function_exists('writeAppLog')) {
            writeAppLog('error', 'patch_note_error', 'Patch note save failed', [
                'action' => $action,
                'error' => limitLogText($e->getMessage(), 300),
            ]);
        }
        patchNoteRedirect('error', patchNoteSafeError($e), $editId > 0 ? '&edit=' . rawurlencode((string)$editId) : '');
    }
}

$editNote = null;
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM app_patch_notes WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $editId]);
    $editNote = $stmt->fetch() ?: null;
}

$stmt = $pdo->prepare("
    SELECT id, release_version, note_type, title, body, is_active, published_at, created_at, updated_at
    FROM app_patch_notes
    ORDER BY is_active DESC, COALESCE(published_at, created_at) DESC, updated_at DESC, id DESC
    LIMIT 80
");
$stmt->execute();
$patchNotes = $stmt->fetchAll();

renderHeader('패치노트 관리', 'patch_notes');
?>
<div class="admin-dashboard patch-notes-admin-page">
    <div class="page-title-section">
        <h1 class="page-main-title">패치노트 관리</h1>
        <p class="page-subtitle">사용자에게 표시할 최근 업데이트 내역, 버그 수정, 안정화 내용을 관리합니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="alert-box <?php echo $status === 'error' ? 'alert-danger' : 'alert-info'; ?>">
            <div class="alert-icon"><i class="fas fa-circle-info"></i></div>
            <div class="alert-content"><p><?php echo h($message); ?></p></div>
        </div>
    <?php endif; ?>

    <section class="settings-card patch-note-editor-card">
        <div class="section-heading-row">
            <h2 class="section-title"><?php echo $editNote ? '패치노트 수정' : '패치노트 등록'; ?></h2>
            <div class="inline-actions">
                <a class="btn btn-secondary btn-sm" href="../updates.php"><i class="fa-solid fa-eye"></i> 사용자 화면 보기</a>
                <?php if ($editNote): ?><a class="btn btn-secondary btn-sm" href="patch_notes.php">새 패치노트 작성</a><?php endif; ?>
            </div>
        </div>
        <form method="POST" class="settings-form patch-note-form">
            <?php echo csrfInput(); ?>
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" value="<?php echo h($editNote['id'] ?? 0); ?>">
            <div class="form-row">
                <div class="form-group">
                    <label for="note_type">유형</label>
                    <select id="note_type" name="note_type">
                        <?php foreach ($types as $type => $label): ?>
                            <option value="<?php echo h($type); ?>" <?php echo (($editNote['note_type'] ?? 'stability') === $type) ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="release_version">버전 / 차수</label>
                    <input type="text" id="release_version" name="release_version" value="<?php echo h($editNote['release_version'] ?? ''); ?>" maxlength="80" placeholder="예: 상용서비스화 9차">
                </div>
                <div class="form-group">
                    <label for="published_at">표시일</label>
                    <input type="datetime-local" id="published_at" name="published_at" value="<?php echo h(patchNoteInputDate($editNote['published_at'] ?? '')); ?>">
                </div>
            </div>
            <div class="form-group">
                <label for="title">제목</label>
                <input type="text" id="title" name="title" value="<?php echo h($editNote['title'] ?? ''); ?>" maxlength="180" required placeholder="예: 패치노트 기능 추가">
            </div>
            <div class="form-group">
                <label for="body">내용</label>
                <textarea id="body" name="body" rows="7" required placeholder="업데이트 내용을 입력하세요. HTML은 실행되지 않습니다."><?php echo h($editNote['body'] ?? ''); ?></textarea>
            </div>
            <div class="section-heading-row patch-note-form-footer">
                <label class="check-row"><input type="checkbox" name="is_active" value="1" <?php echo !isset($editNote['is_active']) || !empty($editNote['is_active']) ? 'checked' : ''; ?>> 사용자 화면에 표시</label>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> 저장</button>
            </div>
        </form>
    </section>

    <section class="home-section patch-note-list-card">
        <div class="section-heading-row">
            <h2 class="section-title">패치노트 목록</h2>
            <span class="settings-muted"><?php echo number_format(count($patchNotes)); ?>개</span>
        </div>
        <?php if (empty($patchNotes)): ?>
            <div class="patch-admin-empty-state">
                <div class="patch-admin-empty-icon" aria-hidden="true"><i class="fa-regular fa-note-sticky"></i></div>
                <strong>등록된 패치노트가 없습니다.</strong>
                <p>위 등록 폼에서 첫 업데이트 내역을 저장하면 사용자 화면의 최근 업데이트 페이지에 표시됩니다.</p>
            </div>
        <?php else: ?>
            <div class="patch-admin-list">
                <?php foreach ($patchNotes as $note): ?>
                    <article class="patch-admin-card patch-type-<?php echo h(patchNoteTypeClass($note['note_type'] ?? 'stability')); ?> <?php echo empty($note['is_active']) ? 'is-hidden' : ''; ?>">
                        <div class="patch-admin-main">
                            <div class="patch-note-meta">
                                <span class="patch-type-badge"><?php echo h(patchNoteTypeLabel($note['note_type'] ?? 'stability')); ?></span>
                                <?php if (!empty($note['release_version'])): ?><span class="patch-version"><?php echo h($note['release_version']); ?></span><?php endif; ?>
                                <?php if (empty($note['is_active'])): ?><span class="metadata-badge">숨김</span><?php endif; ?>
                                <time><?php echo h($note['published_at'] ?: $note['created_at']); ?></time>
                            </div>
                            <h3><?php echo h($note['title']); ?></h3>
                            <?php if (trim((string)($note['body'] ?? '')) !== ''): ?><p><?php echo nl2br(h($note['body'])); ?></p><?php endif; ?>
                            <small class="settings-muted">수정 <?php echo h($note['updated_at']); ?></small>
                        </div>
                        <div class="patch-admin-actions">
                            <a class="btn btn-secondary btn-sm" href="patch_notes.php?edit=<?php echo h($note['id']); ?>"><i class="fa-solid fa-pen"></i> 수정</a>
                            <form method="POST" class="inline-action-form" onsubmit="return confirm('패치노트 표시 상태를 변경할까요?');">
                                <?php echo csrfInput(); ?>
                                <input type="hidden" name="id" value="<?php echo h($note['id']); ?>">
                                <button class="btn <?php echo empty($note['is_active']) ? 'btn-primary' : 'btn-danger'; ?> btn-sm" name="action" value="<?php echo empty($note['is_active']) ? 'show' : 'hide'; ?>" type="submit">
                                    <i class="fa-solid <?php echo empty($note['is_active']) ? 'fa-eye' : 'fa-eye-slash'; ?>"></i> <?php echo empty($note['is_active']) ? '다시 표시' : '숨김'; ?>
                                </button>
                            </form>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
