<?php
// pages/team_status.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, 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'] ?? '';
$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');
// 관리자가 팀장 직위 보유시 팀장 권한으로 처리 (자기 팀만, 필터 불가)
$mgrIsTL = false;
if ($isMgr) {
    $mgrRole = $db->prepare("SELECT role FROM staff WHERE staff_id=?"); $mgrRole->execute([$myStaffId]);
    $mgrIsTL = ($mgrRole->fetchColumn() === '팀장');
}
$canViewAll = $isCeoSys || ($isMgr && !$mgrIsTL); // 대표/시스템관리자, 관리자(팀장아닌) = 모든 팀 + 필터
$canView = $isTL || $isCeoSys || $isMgr;


$viewTeam = $_GET['team'] ?? $myTeam;
if ($isTL || $mgrIsTL) $viewTeam = $myTeam; // 팀장, 관리자(팀장겸직)는 자기 팀만

// 팀장/대표/시스템관리자: 공지 작성 가능
$canWrite = $isTL || $isCeoSys;

// POST: 팀 공지 작성
if ($_SERVER['REQUEST_METHOD']==='POST' && $canWrite) {
    if (($_POST['action']??'')==='add_team_notice' && trim($_POST['title']??'')) {
        $targetTeam = $canViewAll ? ($_POST['team']??$viewTeam) : $viewTeam;
        $db->prepare("INSERT INTO team_notice (team,title,content,author_id) VALUES(?,?,?,?)")
           ->execute([$targetTeam, trim($_POST['title']), trim($_POST['content']??''), $_SESSION['user_id']]);
        header("Location: ".BASE_URL."pages/team_status.php?team=" . urlencode($targetTeam)); exit;
    }
}
if (isset($_GET['del_tnotice']) && $canWrite) {
    $db->prepare("DELETE FROM team_notice WHERE tnotice_id=?")->execute([(int)$_GET['del_tnotice']]);
    header("Location: ".BASE_URL."pages/team_status.php?team=" . urlencode($viewTeam)); exit;
}

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

$allTeams = $db->query("SELECT team_name AS team FROM team_master WHERE is_active=1 AND team_name NOT IN ('경영진','경영지원','오너','시스템') ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
$grades = $db->query("SELECT grade_name, sort_order FROM grade_master WHERE is_active=1 ORDER BY sort_order")->fetchAll();

// 팀원
$teamMembers = $db->prepare("SELECT s.*, ua.user_role, ua.login_id, ua.last_login, ua.user_id AS ua_user_id
    FROM staff s LEFT JOIN user_account ua ON s.staff_id=ua.staff_id
    WHERE s.team=? AND s.is_active=1 ORDER BY FIELD(s.role,'팀장','관리자','직원'), s.grade DESC, s.name");
$teamMembers->execute([$viewTeam]); $members = $teamMembers->fetchAll();

$teamLeader = null;
foreach ($members as $m) { if ($m['role']==='팀장' || $m['user_role']==='team_leader') { $teamLeader = $m; break; } }

// 팀 공지 전체
$noticeSql = "SELECT tn.*, s.name AS author_name FROM team_notice tn LEFT JOIN user_account u ON tn.author_id=u.user_id LEFT JOIN staff s ON u.staff_id=s.staff_id WHERE tn.team=? ORDER BY tn.created_at DESC";
$noticeStmt = $db->prepare($noticeSql); $noticeStmt->execute([$viewTeam]); $allNotices = $noticeStmt->fetchAll();

// 직급별 통계
$gradeStats = [];
foreach ($grades as $g) $gradeStats[$g['grade_name']] = 0;
foreach ($members as $m) { $g = $m['grade']??'-'; if(isset($gradeStats[$g])) $gradeStats[$g]++; else $gradeStats[$g]=1; }

// 팀 매출기여도 (현재 팀 vs 전체)
$curMonth = date('Y-m');
$totalRevAll = (int)$db->query("SELECT COALESCE(SUM(revenue),0) FROM sales WHERE sale_month='{$curMonth}'")->fetchColumn();
$teamRevStmt = $db->prepare("SELECT COALESCE(SUM(sa.revenue),0) FROM sales sa JOIN staff st ON sa.staff_id=st.staff_id WHERE st.team=? AND sa.sale_month=?");
$teamRevStmt->execute([$viewTeam, $curMonth]);
$teamRev = (int)$teamRevStmt->fetchColumn();
$teamContribPct = $totalRevAll > 0 ? round($teamRev / $totalRevAll * 100, 1) : 0;

// 팀별 매출 기여도 (전체 팀 비교용)
$teamRevAll = $db->query("SELECT st.team, COALESCE(SUM(sa.revenue),0) AS rev FROM sales sa JOIN staff st ON sa.staff_id=st.staff_id WHERE sa.sale_month='{$curMonth}' AND st.team NOT IN ('오너','시스템') GROUP BY st.team ORDER BY rev DESC")->fetchAll();
$teamRevLabels = json_encode(array_column($teamRevAll, 'team'));
$teamRevValues = json_encode(array_map(fn($t) => $totalRevAll > 0 ? round((int)$t['rev'] / $totalRevAll * 100, 1) : 0, $teamRevAll));

// 더보기 페이징 (20개씩)
$memberLimit = (int)($_GET['ml'] ?? 20);
$noticeLimit = (int)($_GET['nl'] ?? 20);
$membersShow = array_slice($members, 0, $memberLimit);
$noticesShow = array_slice($allNotices, 0, $noticeLimit);
$hasMoreMembers = count($members) > $memberLimit;
$hasMoreNotices = count($allNotices) > $noticeLimit;
?>

<div class="page-header">
    <h2>🏢 팀 현황</h2>
    <div class="breadcrumb"><?= htmlspecialchars($viewTeam) ?> · 팀장 전용</div>
</div>

<?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; ?>

<!-- 팀 요약 + 매출기여도 + 직급 체계 -->
<div style="display:grid;grid-template-columns:3fr 2fr 2fr;gap:1rem;margin-bottom:1.25rem;">
    <!-- 요약 카드 -->
    <div class="card" style="padding:1rem;">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(6rem,1fr));gap:0.75rem;">
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">팀 인원</div>
                <div style="font-size:var(--fs-2xl);font-weight:800;color:var(--accent-text);"><?= count($members) ?></div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">명</div>
            </div>
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">팀장</div>
                <div style="font-size:var(--fs-lg);font-weight:700;"><?= $teamLeader ? htmlspecialchars($teamLeader['name']) : '미지정' ?></div>
            </div>
            <?php foreach ($gradeStats as $gName => $gCnt): if ($gCnt > 0): ?>
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($gName) ?></div>
                <div style="font-size:var(--fs-xl);font-weight:800;"><?= $gCnt ?></div>
            </div>
            <?php endif; endforeach; ?>
        </div>
    </div>

    <!-- 팀 매출기여도 원형 차트 -->
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--accent-text);font-weight:700;margin-bottom:0.5rem;">📊 팀 매출기여도 <span style="color:var(--text-tertiary);font-weight:400;">(<?= $curMonth ?>)</span></div>
        <div style="position:relative;width:100%;max-width:10rem;margin:0 auto;">
            <canvas id="teamContribChart"></canvas>
            <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);">
                <div style="font-size:var(--fs-xl);font-weight:800;color:var(--accent-text);"><?= $teamContribPct ?>%</div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">기여도</div>
            </div>
        </div>
        <div style="margin-top:0.5rem;font-size:var(--fs-xs);color:var(--text-tertiary);">
            팀 매출 <?= number_format($teamRev/10000) ?>만 / 전체 <?= number_format($totalRevAll/10000) ?>만
        </div>
    </div>

    <!-- 직급 체계 (grade_master 연동) -->
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--accent-text);font-weight:700;margin-bottom:0.5rem;">📋 직급 체계</div>
        <div style="display:flex;flex-direction:column;gap:0.35rem;">
        <?php foreach ($grades as $i => $g):
            $cnt = $gradeStats[$g['grade_name']] ?? 0;
            $isLast = ($i === count($grades) - 1);
        ?>
        <div style="display:flex;align-items:center;gap:0.5rem;">
            <div style="width:1.5rem;">
                <?php if (!$isLast): ?><span style="color:var(--text-tertiary);font-size:var(--fs-xs);">↑</span><?php endif; ?>
            </div>
            <span class="badge <?= $cnt > 0 ? 'badge-info' : 'badge-gray' ?>" style="min-width:4rem;"><?= htmlspecialchars($g['grade_name']) ?></span>
            <span style="font-size:var(--fs-xs);color:<?= $cnt > 0 ? 'var(--text-primary)' : 'var(--text-tertiary)' ?>;"><?= $cnt ?>명</span>
            <div style="flex:1;height:4px;background:var(--border);border-radius:2px;overflow:hidden;">
                <div style="height:100%;width:<?= count($members) > 0 ? round($cnt/count($members)*100) : 0 ?>%;background:var(--accent);border-radius:2px;"></div>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- 팀원 프로필 사진 -->
<div class="card" style="margin-bottom:1.25rem;padding:1rem 1.25rem;position:relative;z-index:50;overflow:visible;">
    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.75rem;">👥 <?= htmlspecialchars($viewTeam) ?> 팀원 (<?= count($membersShow) ?>명)</div>
    <div style="display:flex;gap:1.5rem;align-items:center;flex-wrap:wrap;min-height:5.5rem;overflow:visible;">
    <?php foreach ($membersShow as $m):
        $mUid = (int)($m['ua_user_id'] ?? 0);
        $mProfileDir = __DIR__ . '/../assets/theme/' . $mUid . '/';
        $mProfileFiles = $mUid ? glob($mProfileDir . 'profile.*') : [];
        $mProfileUrl = $mProfileFiles ? BASE_URL.'assets/theme/' . $mUid . '/' . basename($mProfileFiles[0]) : BASE_URL.'assets/empty.png';
        $isLeader = ($m['role']==='팀장' || ($m['user_role']??'')==='team_leader');
    ?>
    <div style="position:relative;flex-shrink:0;">
        <img src="<?= $mProfileUrl ?>?t=<?= filemtime($mProfileFiles[0] ?? __FILE__) ?>"
             alt="<?= htmlspecialchars($m['name']) ?>"
             style="width:4.5rem;height:4.5rem;border-radius:50%;object-fit:cover;border:3px solid <?= $isLeader ? 'var(--accent)' : 'var(--border)' ?>;cursor:pointer;transition:transform .2s,box-shadow .2s;"
             onmouseenter="this.style.transform='scale(1.12)';this.style.boxShadow='0 6px 20px rgba(0,0,0,0.4)';this.nextElementSibling.style.opacity='1';this.nextElementSibling.style.transform='translateX(-50%) translateY(0)';"
             onmouseleave="this.style.transform='scale(1)';this.style.boxShadow='none';this.nextElementSibling.style.opacity='0';this.nextElementSibling.style.transform='translateX(-50%) translateY(4px)';">
        <div style="position:absolute;bottom:calc(100% + 10px);left:50%;transform:translateX(-50%) translateY(4px);background:rgba(20,20,24,0.95);color:#fff;padding:0.4rem 0.75rem;border-radius:8px;white-space:nowrap;font-size:var(--fs-xs);opacity:0;transition:all .2s;pointer-events:none;z-index:9999;box-shadow:0 6px 20px rgba(0,0,0,0.5);backdrop-filter:blur(8px);">
            <div style="font-weight:700;font-size:0.85rem;"><?= htmlspecialchars($m['name']) ?><?= $isLeader ? ' 👑' : '' ?></div>
            <div style="color:rgba(255,255,255,0.6);font-size:0.72rem;margin-top:2px;"><?= htmlspecialchars($m['grade']) ?></div>
            <div style="position:absolute;top:100%;left:50%;transform:translateX(-50%);width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-top:6px solid rgba(20,20,24,0.95);"></div>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;">

<!-- 팀 구성 현황 -->
<div class="card">
    <div class="card-header"><h3>👥 팀 구성 현황</h3></div>

    <div style="overflow-x:auto;">
    <table class="data-table">
        <thead><tr><th>이름</th><th>직급</th><th>역할</th><th>이메일</th><th>입사일</th><th>최종 로그인</th></tr></thead>
        <tbody>
        <?php foreach ($membersShow as $m): ?>
        <tr style="<?= ($m['role']==='팀장'||$m['user_role']==='team_leader')?'background:rgba(var(--accent-rgb),0.06);':'' ?>">
            <td>
                <strong><?= crownName($m['name'], $m['user_role']??$m['role']??'') ?></strong>
                <?php if ($m['role']==='팀장'||$m['user_role']==='team_leader'): ?><span class="badge badge-warning" style="margin-left:0.25rem;">팀장</span><?php endif; ?>
            </td>
            <td><span class="badge badge-info"><?= $m['grade'] ?></span></td>
            <td><?= $m['role'] ?></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($m['email']) ?></td>
            <td style="font-size:var(--fs-xs);"><?= $m['hire_date'] ?></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $m['last_login']?date('m/d H:i',strtotime($m['last_login'])):'-' ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php if ($hasMoreMembers): ?>
    <div style="padding:0.75rem;">
        <a href="?<?= http_build_query(array_merge($_GET, ['ml' => $memberLimit + 20])) ?>" class="btn btn-outline" style="font-size:var(--fs-xs);padding:0.35rem 1.5rem;">더보기 (<?= count($members) - $memberLimit ?>명 더)</a>
    </div>
    <?php endif; ?>
</div>

<!-- 팀 공지사항 -->
<div class="card">
    <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
        <h3>📢 팀 공지사항</h3>
        <?php if ($canWrite): ?><button onclick="document.getElementById('teamNoticeForm').style.display=document.getElementById('teamNoticeForm').style.display==='none'?'block':'none'" class="btn btn-outline" style="font-size:var(--fs-xs);">+ 작성</button><?php endif; ?>
    </div>

    <?php if ($canWrite): ?>
    <div id="teamNoticeForm" style="display:none;padding:1rem;border-bottom:1px solid var(--border);">
        <form method="POST">
            <input type="hidden" name="action" value="add_team_notice">
            <?php if ($canViewAll): ?><input type="hidden" name="team" value="<?= htmlspecialchars($viewTeam) ?>"><?php endif; ?>
            <div class="form-group"><label>제목</label><input type="text" name="title" required placeholder="팀 공지 제목"></div>
            <div class="form-group"><label>내용</label><textarea name="content" rows="3" placeholder="공지 내용"></textarea></div>
            <button type="submit" class="btn btn-primary" style="font-size:var(--fs-sm);">등록</button>
        </form>
    </div>
    <?php endif; ?>

    <?php if ($noticesShow): ?>
    <?php foreach ($noticesShow as $tn): ?>
    <div style="padding:0.75rem 1rem;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:flex-start;gap:0.5rem;">
        <div style="flex:1;">
            <div style="font-size:var(--fs-sm);font-weight:600;color:var(--text-primary);"><?= htmlspecialchars($tn['title']) ?></div>
            <?php if ($tn['content']): ?><div style="font-size:var(--fs-xs);color:var(--text-secondary);margin-top:0.25rem;white-space:pre-line;"><?= nl2br(htmlspecialchars($tn['content'])) ?></div><?php endif; ?>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:0.25rem;"><?= htmlspecialchars($tn['author_name']??'') ?> · <?= date('m/d H:i',strtotime($tn['created_at'])) ?></div>
        </div>
        <?php if ($canWrite): ?><a href="?del_tnotice=<?= $tn['tnotice_id'] ?>&team=<?= urlencode($viewTeam) ?>" onclick="return confirm('삭제하시겠습니까?')" style="color:var(--text-tertiary);font-size:var(--fs-xs);flex-shrink:0;">삭제</a><?php endif; ?>
    </div>
    <?php endforeach; ?>
    <?php if ($hasMoreNotices): ?>
    <div style="padding:0.75rem;">
        <a href="?<?= http_build_query(array_merge($_GET, ['nl' => $noticeLimit + 20])) ?>" class="btn btn-outline" style="font-size:var(--fs-xs);padding:0.35rem 1.5rem;">더보기 (<?= count($allNotices) - $noticeLimit ?>건 더)</a>
    </div>
    <?php endif; ?>
    <?php else: ?>
    <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">팀 공지사항이 없습니다</div>
    <?php endif; ?>
</div>

</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
Chart.defaults.color = getComputedStyle(document.documentElement).getPropertyValue('--text-secondary').trim() || '#aaa';
new Chart(document.getElementById('teamContribChart'), {
    type: 'doughnut',
    data: {
        labels: <?= $teamRevLabels ?>,
        datasets: [{
            data: <?= $teamRevValues ?>,
            backgroundColor: ['#4ECDC4','#CCCCCC','#00E676','#AA00FF','#00BCD4','#FF1744','#FFD600','#E91E63'],
            borderWidth: 0
        }]
    },
    options: {
        cutout: '65%',
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            legend: { display: false },
            tooltip: {
                callbacks: {
                    label: function(c) { return c.label + ': ' + c.parsed + '%'; }
                }
            }
        }
    }
});
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
