<?php
// pages/team_notice.php — 팀 공지사항 (독립 게시판, notice.php 참고)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isLoggedIn()) { header('Location: '.BASE_URL.''); exit; }
$db = (new Database())->getConnection();

$db->exec("CREATE TABLE IF NOT EXISTS team_notice (
    tnotice_id INT AUTO_INCREMENT PRIMARY KEY, team VARCHAR(50) NOT NULL,
    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, INDEX idx_team(team)
)");
// 기존 테이블에 누락된 컬럼 추가
try { $db->exec("ALTER TABLE team_notice ADD COLUMN is_pinned TINYINT(1) DEFAULT 0 AFTER content"); } catch(Exception $e) {}
try { $db->exec("ALTER TABLE team_notice ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER created_at"); } catch(Exception $e) {}

$myRole = $_SESSION['user_role'] ?? '';
$myUserId = $_SESSION['user_id'] ?? 0;
$myStaffId = currentUser()['staff_id'] ?? 0;
$myTeamQ = $db->prepare("SELECT team FROM staff WHERE staff_id=?"); $myTeamQ->execute([$myStaffId]); $myTeam = $myTeamQ->fetchColumn();

$isTL = ($myRole === 'team_leader');
$isCeoSys = in_array($myRole, ['ceo','sysadmin']);
$isMgr = ($myRole === 'manager');
$canViewAll = $isCeoSys || $isMgr;
$canWrite = $isTL || $isCeoSys || $isMgr;

$viewTeam = $_GET['team'] ?? $myTeam;
if ($isTL && !$isCeoSys && !$isMgr) $viewTeam = $myTeam;
// 시스템관리자/대표는 팀이 없으므로 첫 번째 팀으로 기본 설정
if (!$viewTeam && $canViewAll) {
    $firstTeam = $db->query("SELECT team_name FROM team_master WHERE is_active=1 ORDER BY team_name LIMIT 1")->fetchColumn();
    $viewTeam = $firstTeam ?: '';
}

require_once __DIR__ . '/../includes/header.php';
$user = currentUser();

$mode = $_GET['mode'] ?? 'list';
$noticeId = (int)($_GET['id'] ?? 0);
$message = '';
$authorJoin = "LEFT JOIN user_account ua ON tn.author_id=ua.user_id LEFT JOIN staff s ON ua.staff_id=s.staff_id";
$allTeams = $db->query("SELECT team_name AS team FROM team_master WHERE is_active=1 AND team_name NOT IN ('경영진','경영지원','시스템관리자','오너','시스템','관리자') AND team_name IS NOT NULL AND TRIM(team_name)!='' ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);

// ── POST 처리 ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canWrite) {
    $action = $_POST['action'] ?? '';
    if ($action === 'create' && trim($_POST['title'] ?? '')) {
        $targetTeam = $canViewAll ? ($_POST['team'] ?? $viewTeam) : $viewTeam;
        $db->prepare("INSERT INTO team_notice (team,title,content,is_pinned,author_id) VALUES(?,?,?,?,?)")
           ->execute([$targetTeam, trim($_POST['title']), trim($_POST['content'] ?? ''), (int)($_POST['is_pinned'] ?? 0), $myUserId]);
        $message = '팀 공지가 등록되었습니다.'; $mode = 'list';
    }
    if ($action === 'update' && $noticeId && trim($_POST['title'] ?? '')) {
        $db->prepare("UPDATE team_notice SET title=?, content=?, is_pinned=?, updated_at=NOW() WHERE tnotice_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 team_notice WHERE tnotice_id IN ($ph)")->execute(array_map('intval',$ids));
            $message = count($ids).'건이 삭제되었습니다.'; } $mode = 'list';
    }
    if ($action === 'delete_one' && $noticeId) {
        $db->prepare("DELETE FROM team_notice WHERE tnotice_id=?")->execute([$noticeId]);
        $message = '삭제되었습니다.'; $mode = 'list'; $noticeId = 0;
    }
    if ($action === 'copy_selected') {
        $ids = $_POST['del_ids'] ?? [];
        if ($ids) { $ph = implode(',', array_fill(0,count($ids),'?'));
            $originals = $db->prepare("SELECT team,title,content,is_pinned FROM team_notice WHERE tnotice_id IN ($ph)");
            $originals->execute(array_map('intval',$ids)); $cnt=0;
            foreach ($originals->fetchAll() as $o) {
                $db->prepare("INSERT INTO team_notice (team,title,content,is_pinned,author_id) VALUES(?,?,?,?,?)")
                   ->execute([$o['team'],$o['title'].' (복사)',$o['content'],$o['is_pinned'],$myUserId]); $cnt++; }
            $message = $cnt.'건이 복사되었습니다.'; } $mode = 'list';
    }
}
?>

<div class="page-header">
    <h2>📢 팀 공지사항</h2>
    <div class="breadcrumb"><?= htmlspecialchars($viewTeam) ?> 팀</div>
</div>

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

<!-- 팀 필터 -->
<?php if ($canViewAll): ?>
<div class="card" style="margin-bottom:1rem;padding:0.75rem 1rem;">
    <form method="GET" style="display:flex;gap:0.75rem;align-items:center;">
        <span style="font-size:var(--fs-sm);color:var(--text-secondary);">팀 선택:</span>
        <select name="team" onchange="this.form.submit()" class="dash-filter" style="width:12rem;">
            <?php foreach ($allTeams as $t): ?>
            <option value="<?= htmlspecialchars($t) ?>" <?= $t===$viewTeam?'selected':'' ?>><?= htmlspecialchars($t) ?></option>
            <?php endforeach; ?>
        </select>
    </form>
</div>
<?php endif; ?>

<?php if ($mode === 'list'): ?>
<?php
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10; $offset = ($page-1)*$perPage;
$cntStmt = $db->prepare("SELECT COUNT(*) FROM team_notice WHERE team=?"); $cntStmt->execute([$viewTeam]); $totalCnt = (int)$cntStmt->fetchColumn();
$totalPages = max(1, ceil($totalCnt / $perPage));
$stmt = $db->prepare("SELECT tn.*, s.name AS author_name FROM team_notice tn $authorJoin WHERE tn.team=? ORDER BY tn.is_pinned DESC, tn.created_at DESC LIMIT $perPage OFFSET $offset");
$stmt->execute([$viewTeam]); $notices = $stmt->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&team=<?= urlencode($viewTeam) ?>" 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" onclick="document.querySelectorAll('.chk-tn').forEach(c=>c.checked=this.checked)"></th><?php endif; ?>
            <th style="width:3rem;">No</th><th>제목</th>
            <th style="width:7rem;">작성자</th><th style="width:9.5rem;">작성일</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['tnotice_id'] ?>&team=<?= urlencode($viewTeam) ?>'">
            <?php if ($canWrite): ?><td style="" onclick="event.stopPropagation()"><input type="checkbox" name="del_ids[]" value="<?= $n['tnotice_id'] ?>" class="chk-tn"></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><?= htmlspecialchars($n['title']) ?></strong></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($n['author_name']??'') ?></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= date('Y-m-d H:i', strtotime($n['created_at'])) ?></td>
        </tr>
        <?php endforeach; else: ?>
        <tr><td colspan="<?= $canWrite?5:4 ?>" 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="?team=<?= urlencode($viewTeam) ?>&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="?team=<?= urlencode($viewTeam) ?>&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="?team=<?= urlencode($viewTeam) ?>&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 tn.*, s.name AS author_name FROM team_notice tn $authorJoin WHERE tn.tnotice_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['team']) ?></span>
            <span>작성자: <?= htmlspecialchars($n['author_name']??'-') ?></span>
            <span>작성일: <?= date('Y-m-d H:i', strtotime($n['created_at'])) ?></span>
        </div>
    </div>
    <div style="padding:1.25rem;min-height:8rem;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&team=<?= urlencode($n['team']) ?>" class="btn btn-outline">← 목록</a>
    <div style="display:flex;gap:0.5rem;">
        <?php if ($canWrite): ?>
        <a href="?mode=edit&id=<?= $n['tnotice_id'] ?>&team=<?= urlencode($n['team']) ?>" 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>
<?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">
        <?php if ($canViewAll): ?>
        <div class="form-group"><label>팀</label>
            <select name="team" style="width:12rem;">
                <?php foreach ($allTeams as $t): ?><option value="<?= htmlspecialchars($t) ?>" <?= $t===$viewTeam?'selected':'' ?>><?= htmlspecialchars($t) ?></option><?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        <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&team=<?= urlencode($viewTeam) ?>" 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 team_notice WHERE tnotice_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'"><?= 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['tnotice_id'] ?>&team=<?= urlencode($n['team']) ?>" 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'; ?>
