<?php
// pages/notice.php — 공지사항 게시판
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';

$db = (new Database())->getConnection();

// 테이블 보장
$db->exec("CREATE TABLE IF NOT EXISTS notice (notice_id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200) NOT NULL, content TEXT, is_pinned TINYINT(1) DEFAULT 0, author_id INT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");

// 권한: menu_role_permission 연동 또는 기본 관리자 권한
$canWrite = false;
try {
    // menu_role_permission 자동 등록
    $db->exec("INSERT IGNORE INTO menu_role_permission (menu_key, role_key, view_scope, can_create, can_edit, can_delete) VALUES
        ('notice','staff','all',0,0,0),
        ('notice','team_leader','all',0,0,0),
        ('notice','manager','all',1,1,1),
        ('notice','ceo','all',1,1,1),
        ('notice','sysadmin','all',1,1,1)");
    $mrp = $db->prepare("SELECT can_create FROM menu_role_permission WHERE menu_key='notice' AND role_key=?");
    $mrp->execute([$user['role']]); $mrpRow = $mrp->fetch();
    if ($mrpRow) { $canWrite = (bool)$mrpRow['can_create']; }
    else { $canWrite = in_array($user['role'], ['manager','ceo','sysadmin']); }
} catch(Exception $e) { $canWrite = in_array($user['role'], ['manager','ceo','sysadmin']); }

$message = '';
$mode = $_GET['mode'] ?? 'list';
$noticeId = (int)($_GET['id'] ?? 0);

// ── POST 처리 ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canWrite) {
    $action = $_POST['action'] ?? '';

    if ($action === 'create' && trim($_POST['title'] ?? '')) {
        $db->prepare("INSERT INTO notice (title, content, is_pinned, author_id) VALUES(?,?,?,?)")
           ->execute([trim($_POST['title']), trim($_POST['content'] ?? ''), (int)($_POST['is_pinned'] ?? 0), $user['user_id']]);
        $newId = $db->lastInsertId();
        // 알림
        $db->exec("CREATE TABLE IF NOT EXISTS notifications (noti_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, message VARCHAR(300), link VARCHAR(200) DEFAULT '', is_read TINYINT(1) DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, INDEX idx_user_read(user_id, is_read))");
        $allUsers = $db->query("SELECT user_id FROM user_account WHERE is_active=1 AND user_id!=".(int)$user['user_id'])->fetchAll(PDO::FETCH_COLUMN);
        $notiMsg = '📌 새 공지: ' . mb_substr(trim($_POST['title']),0,30) . ' (' . $user['name'] . ')';
        $notiStmt = $db->prepare("INSERT INTO notifications (user_id,message,link) VALUES(?,?,?)");
        foreach ($allUsers as $uid) { $notiStmt->execute([$uid, $notiMsg, BASE_URL.'pages/notice.php?mode=view&id='.$newId]); }
        $message = '공지가 등록되었습니다.';
        $mode = 'view'; $noticeId = (int)$newId;
    }

    if ($action === 'update' && $noticeId && trim($_POST['title'] ?? '')) {
        $db->prepare("UPDATE notice SET title=?, content=?, is_pinned=?, updated_at=NOW() WHERE notice_id=?")
           ->execute([trim($_POST['title']), trim($_POST['content'] ?? ''), (int)($_POST['is_pinned'] ?? 0), $noticeId]);
        $message = '공지가 수정되었습니다.';
        $mode = 'view';
    }

    if ($action === 'delete_selected') {
        $ids = $_POST['del_ids'] ?? [];
        if ($ids) {
            $ph = implode(',', array_fill(0, count($ids), '?'));
            $db->prepare("DELETE FROM notice WHERE notice_id IN ($ph)")->execute(array_map('intval', $ids));
            $message = count($ids) . '건이 삭제되었습니다.';
        }
        $mode = 'list';
    }

    if ($action === 'delete_one' && $noticeId) {
        $db->prepare("DELETE FROM notice WHERE notice_id=?")->execute([$noticeId]);
        $message = '공지가 삭제되었습니다.';
        $mode = 'list'; $noticeId = 0;
    }
}

// 게시물 복사 (모든 사용자, canWrite 권한 필요)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'copy_selected' && $canWrite) {
    $ids = $_POST['del_ids'] ?? [];
    if ($ids) {
        $ph = implode(',', array_fill(0, count($ids), '?'));
        $originals = $db->prepare("SELECT title, content, is_pinned FROM notice WHERE notice_id IN ($ph)");
        $originals->execute(array_map('intval', $ids));
        $copyCount = 0;
        foreach ($originals->fetchAll() as $orig) {
            $db->prepare("INSERT INTO notice (title, content, is_pinned, author_id) VALUES(?,?,?,?)")
               ->execute([$orig['title'] . ' (복사)', $orig['content'], $orig['is_pinned'], $user['user_id']]);
            $copyCount++;
        }
        $message = $copyCount . '건이 복사되었습니다.';
    }
    $mode = 'list';
}

// ── 작성자 이름 서브쿼리 ──
$authorJoin = "LEFT JOIN user_account ua ON n.author_id=ua.user_id LEFT JOIN staff s ON ua.staff_id=s.staff_id";
?>

<div class="page-header">
    <h2>📌 공지사항</h2>
</div>

<?php if ($message): ?><div class="alert alert-success" style="margin-bottom:1rem;">✓ <?= htmlspecialchars($message) ?></div><?php endif; ?>

<?php if ($mode === 'list'): ?>
<!-- ═══ 리스트 ═══ -->
<?php
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;
$totalCnt = (int)$db->query("SELECT COUNT(*) FROM notice")->fetchColumn();
$totalPages = max(1, ceil($totalCnt / $perPage));

$notices = $db->query("SELECT n.*, s.name AS author_name FROM notice n $authorJoin ORDER BY n.is_pinned DESC, n.created_at DESC LIMIT $perPage OFFSET $offset")->fetchAll();
?>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.75rem;">
    <div style="display:flex;gap:0.5rem;">
        <?php if ($canWrite): ?>
        <button type="submit" form="listForm" name="action" value="delete_selected" class="btn btn-outline" style="font-size:var(--fs-xs);color:var(--accent);" onclick="return confirm('선택된 공지를 삭제하시겠습니까?')">🗑️ 선택 삭제</button>
        <button type="submit" form="listForm" name="action" value="copy_selected" class="btn btn-outline" style="font-size:var(--fs-xs);">📋 선택 복사</button>
        <?php endif; ?>
    </div>
    <?php if ($canWrite): ?>
    <a href="?mode=write" class="btn btn-primary" style="font-size:var(--fs-sm);">✏️ 새 공지 작성</a>
    <?php endif; ?>
</div>

<form method="POST" id="listForm">
<div class="card">
    <div class="table-wrap">
    <table class="data-table">
        <thead>
            <tr>
                <?php if ($canWrite): ?><th style="width:2.5rem;"><input type="checkbox" id="chkAll" onclick="document.querySelectorAll('.chk-notice').forEach(c=>c.checked=this.checked)"></th><?php endif; ?>
                <th style="width:3rem;">No</th>
                <th>제목</th>
                <th style="width:7rem;white-space:nowrap;">작성자</th>
                <th style="width:9.5rem;white-space:nowrap;">작성일</th>
            </tr>
        </thead>
        <tbody>
        <?php if ($notices): foreach ($notices as $ni => $n): ?>
        <tr style="cursor:pointer;" onclick="if(!event.target.closest('input'))location='?mode=view&id=<?= $n['notice_id'] ?>'">
            <?php if ($canWrite): ?><td style="" onclick="event.stopPropagation()"><input type="checkbox" name="del_ids[]" value="<?= $n['notice_id'] ?>" class="chk-notice"></td><?php endif; ?>
            <td style="color:var(--text-tertiary);font-size:var(--fs-xs);">
                <?php if ($n['is_pinned']): ?><span style="color:var(--accent);">📌</span>
                <?php else: ?><?= $offset + $ni + 1 ?>
                <?php endif; ?>
            </td>
            <td style="max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                <strong style="color:var(--text-primary);"><?= htmlspecialchars($n['title']) ?></strong>
            </td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);white-space:nowrap;"><?= htmlspecialchars($n['author_name'] ?? '') ?></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);white-space:nowrap;"><?= date('Y-m-d H:i', strtotime($n['created_at'])) ?></td>
        </tr>
        <?php endforeach; else: ?>
        <tr><td colspan="<?= $canWrite ? 6 : 5 ?>" style="padding:2rem;color:var(--text-tertiary);">공지사항이 없습니다.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>
</form>

<!-- 페이지네이션 -->
<?php if ($totalPages > 1): ?>
<div style="display:flex;justify-content:center;gap:0.25rem;margin-top:1rem;">
    <?php if ($page > 1): ?><a href="?page=<?= $page-1 ?>" class="btn btn-outline" style="font-size:var(--fs-xs);padding:0.25rem 0.5rem;">‹</a><?php endif; ?>
    <?php for ($p = max(1,$page-3); $p <= min($totalPages,$page+3); $p++): ?>
    <a href="?page=<?= $p ?>" class="btn <?= $p===$page?'btn-primary':'btn-outline' ?>" style="font-size:var(--fs-xs);padding:0.25rem 0.5rem;"><?= $p ?></a>
    <?php endfor; ?>
    <?php if ($page < $totalPages): ?><a href="?page=<?= $page+1 ?>" class="btn btn-outline" style="font-size:var(--fs-xs);padding:0.25rem 0.5rem;">›</a><?php endif; ?>
</div>
<?php endif; ?>

<?php elseif ($mode === 'view' && $noticeId): ?>
<!-- ═══ 보기 ═══ -->
<?php
$n = $db->prepare("SELECT n.*, s.name AS author_name FROM notice n $authorJoin WHERE n.notice_id=?");
$n->execute([$noticeId]); $n = $n->fetch();
if (!$n) { echo '<div class="alert alert-warning">존재하지 않는 공지입니다.</div>'; } else {
?>
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header" style="flex-direction:column;align-items:flex-start;gap:0.5rem;">
        <h3 style="margin:0;"><?php if($n['is_pinned']): ?><span style="color:var(--accent);">📌</span> <?php endif; ?><?= htmlspecialchars($n['title']) ?></h3>
        <div style="display:flex;gap:1rem;font-size:var(--fs-xs);color:var(--text-tertiary);">
            <span>작성자: <?= htmlspecialchars($n['author_name'] ?? '-') ?></span>
            <span>작성일: <?= date('Y-m-d H:i', strtotime($n['created_at'])) ?></span>
            <?php if ($n['updated_at'] !== $n['created_at']): ?><span>수정일: <?= date('Y-m-d H:i', strtotime($n['updated_at'])) ?></span><?php endif; ?>
        </div>
    </div>
    <div style="padding:1.25rem;min-height:10rem;font-size:var(--fs-sm);color:var(--text-primary);line-height:1.8;">
        <?= nl2br(htmlspecialchars($n['content'] ?? '')) ?>
    </div>
</div>

<div style="display:flex;justify-content:space-between;">
    <a href="?mode=list" class="btn btn-outline">← 목록</a>
    <div style="display:flex;gap:0.5rem;">
        <button onclick="copyNotice()" class="btn btn-outline" style="font-size:var(--fs-sm);" id="copyBtn">📋 복사</button>
        <?php if ($canWrite): ?>
        <a href="?mode=edit&id=<?= $n['notice_id'] ?>" class="btn btn-primary" style="font-size:var(--fs-sm);">✏️ 수정</a>
        <form method="POST" style="display:inline;" onsubmit="return confirm('삭제하시겠습니까?')">
            <input type="hidden" name="action" value="delete_one">
            <button type="submit" class="btn btn-outline" style="font-size:var(--fs-sm);color:var(--accent);">🗑️ 삭제</button>
        </form>
        <?php endif; ?>
    </div>
</div>
<script>
function copyNotice(){
    const title = <?= json_encode($n['title']) ?>;
    const content = <?= json_encode($n['content'] ?? '') ?>;
    const text = '[공지사항] ' + title + '\n\n' + content;
    navigator.clipboard.writeText(text).then(()=>{
        const btn = document.getElementById('copyBtn');
        btn.textContent = '✅ 복사됨';
        setTimeout(()=>{ btn.textContent = '📋 복사'; }, 2000);
    }).catch(()=>{
        const ta = document.createElement('textarea');
        ta.value = text; document.body.appendChild(ta);
        ta.select(); document.execCommand('copy');
        document.body.removeChild(ta);
        const btn = document.getElementById('copyBtn');
        btn.textContent = '✅ 복사됨';
        setTimeout(()=>{ btn.textContent = '📋 복사'; }, 2000);
    });
}
</script>
<?php } ?>

<?php elseif ($mode === 'write' && $canWrite): ?>
<!-- ═══ 작성 ═══ -->
<div class="card">
    <div class="card-header"><h3>✏️ 새 공지 작성</h3></div>
    <form method="POST" style="padding:1.25rem;">
        <input type="hidden" name="action" value="create">
        <div class="form-group">
            <label>제목 *</label>
            <input type="text" name="title" required placeholder="공지 제목" style="width:100%;">
        </div>
        <div class="form-group">
            <label>내용</label>
            <textarea name="content" rows="1" placeholder="공지 내용을 입력하세요." style="width:100%;overflow:hidden;resize:none;" oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px';"></textarea>
        </div>
        <div class="form-group">
            <label><input type="checkbox" name="is_pinned" value="1"> 📌 상단 고정</label>
        </div>
        <div style="display:flex;justify-content:flex-end;gap:0.5rem;">
            <a href="?mode=list" class="btn btn-outline">취소</a>
            <button type="submit" class="btn btn-primary">등록</button>
        </div>
    </form>
</div>

<?php elseif ($mode === 'edit' && $noticeId && $canWrite): ?>
<!-- ═══ 수정 ═══ -->
<?php
$n = $db->prepare("SELECT * FROM notice WHERE notice_id=?");
$n->execute([$noticeId]); $n = $n->fetch();
if (!$n) { echo '<div class="alert alert-warning">존재하지 않는 공지입니다.</div>'; } else {
?>
<div class="card">
    <div class="card-header"><h3>✏️ 공지 수정</h3></div>
    <form method="POST" style="padding:1.25rem;">
        <input type="hidden" name="action" value="update">
        <div class="form-group">
            <label>제목 *</label>
            <input type="text" name="title" required value="<?= htmlspecialchars($n['title']) ?>" style="width:100%;">
        </div>
        <div class="form-group">
            <label>내용</label>
            <textarea name="content" rows="1" style="width:100%;overflow:hidden;resize:none;" oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px'" onload="this.style.height=this.scrollHeight+'px'"><?= htmlspecialchars($n['content'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label><input type="checkbox" name="is_pinned" value="1" <?= $n['is_pinned']?'checked':'' ?>> 📌 상단 고정</label>
        </div>
        <div style="display:flex;justify-content:flex-end;gap:0.5rem;">
            <a href="?mode=view&id=<?= $n['notice_id'] ?>" class="btn btn-outline">취소</a>
            <button type="submit" class="btn btn-primary">수정 저장</button>
        </div>
    </form>
</div>
<?php } ?>
<?php endif; ?>

<script>document.querySelectorAll('textarea[oninput]').forEach(t=>{t.style.height='auto';t.style.height=t.scrollHeight+'px';});</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
