<?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/announcements.php';
requirePermission('announcement_manage');

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

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

function announcementDateValue($value) {
    $value = trim((string)$value);
    if ($value === '') return null;
    $timestamp = strtotime($value);
    return $timestamp ? date('Y-m-d H:i:s', $timestamp) : null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'save') {
            $id = max(0, (int)($_POST['id'] ?? 0));
            $type = (string)($_POST['notice_type'] ?? 'notice');
            if (!isset($types[$type])) $type = 'notice';
            $title = trim((string)($_POST['title'] ?? ''));
            $body = trim((string)($_POST['body'] ?? ''));
            $isImportant = !empty($_POST['is_important']) ? 1 : 0;
            $isActive = !empty($_POST['is_active']) ? 1 : 0;
            $startsAt = announcementDateValue($_POST['starts_at'] ?? '');
            $endsAt = announcementDateValue($_POST['ends_at'] ?? '');

            if ($title === '') throw new RuntimeException('공지 제목을 입력하세요.');
            if ($endsAt !== null && $startsAt !== null && strtotime($endsAt) < strtotime($startsAt)) {
                throw new RuntimeException('종료일은 시작일보다 빠를 수 없습니다.');
            }

            if ($id > 0) {
                $stmt = $pdo->prepare("
                    UPDATE app_announcements
                    SET notice_type = :notice_type,
                        title = :title,
                        body = :body,
                        is_important = :is_important,
                        is_active = :is_active,
                        starts_at = :starts_at,
                        ends_at = :ends_at,
                        updated_at = NOW()
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':notice_type' => $type,
                    ':title' => $title,
                    ':body' => $body,
                    ':is_important' => $isImportant,
                    ':is_active' => $isActive,
                    ':starts_at' => $startsAt,
                    ':ends_at' => $endsAt,
                    ':id' => $id,
                ]);
                $savedId = $id;
                $doneMessage = '공지를 수정했습니다.';
                if (function_exists('logAdminAction')) logAdminAction('announcement_updated', 'Announcement updated #' . $id);
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO app_announcements
                        (notice_type, title, body, is_important, is_active, starts_at, ends_at, created_by_admin)
                    VALUES
                        (:notice_type, :title, :body, :is_important, :is_active, :starts_at, :ends_at, :created_by_admin)
                ");
                $stmt->execute([
                    ':notice_type' => $type,
                    ':title' => $title,
                    ':body' => $body,
                    ':is_important' => $isImportant,
                    ':is_active' => $isActive,
                    ':starts_at' => $startsAt,
                    ':ends_at' => $endsAt,
                    ':created_by_admin' => $_SESSION['admin_user_id'] ?? null,
                ]);
                $savedId = (int)$pdo->lastInsertId();
                $doneMessage = '공지를 등록했습니다.';
                if (function_exists('logAdminAction')) logAdminAction('announcement_created', 'Announcement created #' . $savedId);
            }
            if (function_exists('writeAppLog')) {
                writeAppLog('info', 'announcement', $doneMessage, ['announcement_id' => $savedId, 'type' => $type]);
            }
            announcementRedirect('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_announcements SET is_active = :is_active, updated_at = NOW() WHERE id = :id");
            $stmt->execute([':is_active' => $active, ':id' => $id]);
            $doneMessage = $active ? '공지를 다시 표시합니다.' : '공지를 숨김 처리했습니다.';
            if (function_exists('logAdminAction')) logAdminAction($active ? 'announcement_shown' : 'announcement_hidden', 'Announcement #' . $id);
            if (function_exists('writeAppLog')) writeAppLog('info', 'announcement', $doneMessage, ['announcement_id' => $id]);
            announcementRedirect('success', $doneMessage);
        }

        throw new RuntimeException('알 수 없는 작업입니다.');
    } catch (Throwable $e) {
        if (function_exists('writeAppLog')) {
            writeAppLog('error', 'announcement_error', 'Announcement save failed', ['action' => $action, 'error' => $e->getMessage()]);
        }
        $safe = function_exists('maskInternalPathText') ? maskInternalPathText($e->getMessage()) : $e->getMessage();
        if (preg_match('/SQLSTATE|PDOException|Stack trace|Fatal error|Warning:|Notice:|[A-Z]:[\\\\\/]/i', $safe)) {
            $safe = '공지 저장 중 오류가 발생했습니다. 오류 로그를 확인해 주세요.';
        }
        announcementRedirect('error', $safe, $editId > 0 ? '&edit=' . rawurlencode((string)$editId) : '');
    }
}

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

$stmt = $pdo->prepare("
    SELECT id, notice_type, title, body, is_important, is_active, starts_at, ends_at, created_at, updated_at
    FROM app_announcements
    ORDER BY is_active DESC, is_important DESC, updated_at DESC, id DESC
    LIMIT 80
");
$stmt->execute();
$announcements = $stmt->fetchAll();

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

renderHeader('공지 관리', 'announcements');
?>
<div class="admin-dashboard announcements-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 announcement-editor-card">
        <div class="section-heading-row">
            <h2 class="section-title"><?php echo $editNotice ? '공지 수정' : '공지 등록'; ?></h2>
            <?php if ($editNotice): ?><a class="btn btn-secondary btn-sm" href="announcements.php">새 공지 작성</a><?php endif; ?>
        </div>
        <form method="POST" class="settings-form announcement-form">
            <?php echo csrfInput(); ?>
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" value="<?php echo h($editNotice['id'] ?? 0); ?>">
            <div class="form-row">
                <div class="form-group">
                    <label for="notice_type">공지 유형</label>
                    <select id="notice_type" name="notice_type">
                        <?php foreach ($types as $type => $label): ?>
                            <option value="<?php echo h($type); ?>" <?php echo (($editNotice['notice_type'] ?? 'notice') === $type) ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="title">제목</label>
                    <input type="text" id="title" name="title" value="<?php echo h($editNotice['title'] ?? ''); ?>" maxlength="255" required>
                </div>
            </div>
            <div class="form-group">
                <label for="body">내용</label>
                <textarea id="body" name="body" rows="5" placeholder="공지 내용을 입력하세요. HTML은 실행되지 않습니다."><?php echo h($editNotice['body'] ?? ''); ?></textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="starts_at">시작일</label>
                    <input type="datetime-local" id="starts_at" name="starts_at" value="<?php echo h(announcementInputDate($editNotice['starts_at'] ?? '')); ?>">
                </div>
                <div class="form-group">
                    <label for="ends_at">종료일</label>
                    <input type="datetime-local" id="ends_at" name="ends_at" value="<?php echo h(announcementInputDate($editNotice['ends_at'] ?? '')); ?>">
                </div>
            </div>
            <div class="bulk-option-row announcement-option-row">
                <label class="check-row"><input type="checkbox" name="is_important" value="1" <?php echo !empty($editNotice['is_important']) ? 'checked' : ''; ?>> 중요 공지로 우선 표시</label>
                <label class="check-row"><input type="checkbox" name="is_active" value="1" <?php echo !isset($editNotice['is_active']) || !empty($editNotice['is_active']) ? 'checked' : ''; ?>> 활성화</label>
            </div>
            <div class="section-heading-row announcement-form-footer">
                <p class="settings-muted">활성 공지 중 중요 공지가 우선 표시되고, 그 외에는 최신 수정 공지가 표시됩니다.</p>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> 저장</button>
            </div>
        </form>
    </section>

    <section class="home-section">
        <div class="section-heading-row">
            <h2 class="section-title">공지 목록</h2>
            <span class="settings-muted"><?php echo number_format(count($announcements)); ?>개</span>
        </div>
        <?php if (empty($announcements)): ?>
            <p class="empty-text">등록된 공지가 없습니다.</p>
        <?php else: ?>
            <div class="announcement-admin-list">
                <?php foreach ($announcements as $notice): ?>
                    <article class="announcement-admin-card announcement-<?php echo h(announcementTypeClass($notice['notice_type'] ?? 'notice')); ?> <?php echo empty($notice['is_active']) ? 'is-hidden' : ''; ?>">
                        <div class="announcement-admin-icon" aria-hidden="true">
                            <i class="fa-solid <?php echo ($notice['notice_type'] ?? 'notice') === 'maintenance' ? 'fa-screwdriver-wrench' : (($notice['notice_type'] ?? 'notice') === 'update' ? 'fa-rotate' : (($notice['notice_type'] ?? 'notice') === 'important' ? 'fa-circle-exclamation' : 'fa-bullhorn')); ?>"></i>
                        </div>
                        <div class="announcement-admin-main">
                            <div class="announcement-title-row">
                                <span class="announcement-type"><?php echo h(announcementTypeLabel($notice['notice_type'] ?? 'notice')); ?></span>
                                <strong><?php echo h($notice['title']); ?></strong>
                                <?php if (!empty($notice['is_important'])): ?><span class="announcement-important">중요</span><?php endif; ?>
                                <?php if (empty($notice['is_active'])): ?><span class="metadata-badge">숨김</span><?php endif; ?>
                            </div>
                            <?php if (trim((string)($notice['body'] ?? '')) !== ''): ?><p><?php echo nl2br(h($notice['body'])); ?></p><?php endif; ?>
                            <div class="announcement-admin-meta">
                                <span><i class="fa-regular fa-calendar"></i> <?php echo h($notice['starts_at'] ?: '즉시'); ?> ~ <?php echo h($notice['ends_at'] ?: '제한 없음'); ?></span>
                                <span><i class="fa-regular fa-clock"></i> 수정 <?php echo h($notice['updated_at']); ?></span>
                            </div>
                        </div>
                        <div class="announcement-admin-actions">
                            <a class="btn btn-secondary btn-sm" href="announcements.php?edit=<?php echo h($notice['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($notice['id']); ?>">
                                <button class="btn <?php echo empty($notice['is_active']) ? 'btn-primary' : 'btn-danger'; ?> btn-sm" name="action" value="<?php echo empty($notice['is_active']) ? 'show' : 'hide'; ?>" type="submit">
                                    <i class="fa-solid <?php echo empty($notice['is_active']) ? 'fa-eye' : 'fa-eye-slash'; ?>"></i> <?php echo empty($notice['is_active']) ? '다시 표시' : '숨김'; ?>
                                </button>
                            </form>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
