<?php
// includes/header.php — 비디오 배경 + 글래스 사이드바 + 사용자 테마
if (!file_exists(__DIR__ . '/../config/database.php')) { $_base = '/' . trim(str_replace(str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']??''), '', str_replace('\\','/',dirname(__DIR__))), '/') . '/'; header('Location: '.$_base.'setup.php'); exit; }
require_once __DIR__ . '/../config/auth.php';
// getMenuPerm 안전 보장
if (!function_exists('getMenuPerm')) {
    function getMenuPerm($db, $menuKey, $roleKey = null) {
        if (!$roleKey) $roleKey = $_SESSION['user_role'] ?? 'staff';
        try {
            $stmt = $db->prepare("SELECT * FROM menu_role_permission WHERE menu_key=? AND role_key=?");
            $stmt->execute([$menuKey, $roleKey]);
            $p = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($p) return $p;
        } catch(Exception $e) {}
        if (in_array($roleKey, ['sysadmin','ceo'])) return ['view_scope'=>'all','can_create'=>1,'can_edit'=>1,'can_delete'=>1,'need_ceo_approval'=>0,'need_sysadmin_approval'=>0];
        if ($roleKey === 'manager') return ['view_scope'=>'all','can_create'=>1,'can_edit'=>1,'can_delete'=>1,'need_ceo_approval'=>0,'need_sysadmin_approval'=>0];
        return ['view_scope'=>'own','can_create'=>1,'can_edit'=>0,'can_delete'=>0,'need_ceo_approval'=>0,'need_sysadmin_approval'=>1];
    }
}
requireLogin();

$user = currentUser();
$currentPage = basename($_SERVER['PHP_SELF'], '.php');

if (!isset($db)) {
    require_once __DIR__ . '/../config/database.php';
    $db = (new Database())->getConnection();
}
if (function_exists('ensureViews')) ensureViews($db);

// 공지사항 + 메신저 메뉴 자동 등록 (모든 역할, INSERT IGNORE로 중복 안전)
try {
    $allRoles = ['staff','team_leader','manager','ceo','sysadmin'];
    foreach ($allRoles as $r) {
        $db->prepare("INSERT IGNORE INTO menu_permission (user_role,menu_key,menu_label,menu_icon,menu_group,menu_url,sort_order) VALUES(?,'notice','공지사항','📌','메인','/AP_One/pages/notice.php',0)")->execute([$r]);
        $db->prepare("INSERT IGNORE INTO menu_permission (user_role,menu_key,menu_label,menu_icon,menu_group,menu_url,sort_order) VALUES(?,'messenger','메신저','💬','메인','/AP_One/pages/messenger.php',1)")->execute([$r]);
    }
} catch(Exception $e) {}
$menus = getMenusForRole($db, $user['role'], $user['team'] ?? '');
$roleLabel = getRoleLabel($user['role']);

// ── 팀/직급 마스터 (전역) ──
$db->exec("CREATE TABLE IF NOT EXISTS team_master (team_id INT AUTO_INCREMENT PRIMARY KEY, team_name VARCHAR(50) NOT NULL UNIQUE, description VARCHAR(200) DEFAULT '', is_active TINYINT(1) DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
$db->exec("CREATE TABLE IF NOT EXISTS grade_master (grade_id INT AUTO_INCREMENT PRIMARY KEY, grade_name VARCHAR(30) NOT NULL UNIQUE, sort_order INT DEFAULT 0, is_active TINYINT(1) DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");

// ── 사용자 테마 로드 ──
$db->exec("CREATE TABLE IF NOT EXISTS user_theme (
    theme_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL UNIQUE,
    accent_color VARCHAR(20) DEFAULT '#E53935', icon_color VARCHAR(20) DEFAULT '#E53935',
    glass_bg VARCHAR(50) DEFAULT 'rgba(12,12,16,0.75)', card_bg_color VARCHAR(20) DEFAULT '#0C0C10',
    text_color VARCHAR(20) DEFAULT '#EAEAEA', sidebar_bg VARCHAR(50) DEFAULT 'rgba(10,10,14,0.82)',
    form_line_color VARCHAR(20) DEFAULT '#333338', form_placeholder VARCHAR(20) DEFAULT '#555560',
    video_opacity DECIMAL(3,2) DEFAULT 0.65, video_url VARCHAR(500) DEFAULT '',
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

$themeStmt = $db->prepare("SELECT accent_color, icon_color, glass_bg, card_bg_color, text_color, sidebar_bg, form_line_color, form_placeholder, video_opacity, video_url FROM user_theme WHERE user_id = ?");
$themeStmt->execute([$user['user_id']]);
$theme = $themeStmt->fetch(PDO::FETCH_ASSOC);
if (!$theme) {
    // 기본 테마 자동 저장
    $theme = ['accent_color' => '#E53935', 'icon_color' => '#E53935', 'glass_bg' => 'rgba(12,12,16,0.75)', 'card_bg_color' => '#0C0C10', 'text_color' => '#EAEAEA', 'video_opacity' => 0.65,
              'sidebar_bg' => 'rgba(10,10,14,0.82)', 'form_line_color' => '#333338', 'form_placeholder' => '#555560', 'video_url' => ''];
    try {
        $db->prepare("INSERT INTO user_theme (user_id, accent_color, icon_color, glass_bg, card_bg_color, text_color, sidebar_bg, form_line_color, form_placeholder, video_opacity, video_url) VALUES(?,?,?,?,?,?,?,?,?,?,?)")
           ->execute([$user['user_id'], $theme['accent_color'], $theme['accent_color'], $theme['glass_bg'], $theme['card_bg_color'], $theme['text_color'], $theme['sidebar_bg'], $theme['form_line_color'], $theme['form_placeholder'], $theme['video_opacity'], '']);
    } catch(Exception $e) {}
}

// accent hex → rgb
$hex = ltrim($theme['accent_color'], '#');
$accentR = hexdec(substr($hex, 0, 2));
$accentG = hexdec(substr($hex, 2, 2));
$accentB = hexdec(substr($hex, 4, 2));

// card_bg hex → rgb
$cbHex = ltrim($theme['card_bg_color'] ?? '#0C0C10', '#');
$cbR = hexdec(substr($cbHex, 0, 2));
$cbG = hexdec(substr($cbHex, 2, 2));
$cbB = hexdec(substr($cbHex, 4, 2));

// glass_bg에서 opacity 추출
$glassOpacity = 0.75;
if (preg_match('/[\d.]+\)$/', $theme['glass_bg'], $m)) {
    $glassOpacity = floatval($m[0]);
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AP MEDIA ONE</title>
    <?php
    // 파비콘 동적 로드 (favicon.png 또는 favicon.ico)
    $faviconFiles = glob(__DIR__ . '/../assets/favicon.*');
    $faviconUrl = '';
    $faviconType = 'image/png';
    foreach ($faviconFiles as $ff) {
        $fext = strtolower(pathinfo($ff, PATHINFO_EXTENSION));
        if (in_array($fext, ['png','ico'])) {
            $faviconUrl = BASE_URL . 'assets/' . basename($ff);
            $faviconType = $fext === 'ico' ? 'image/x-icon' : 'image/png';
            break;
        }
    }
    if ($faviconUrl):
    ?>
    <link rel="icon" type="<?= $faviconType ?>" href="<?= $faviconUrl ?>?v=<?= filemtime($faviconFiles[0] ?? '') ?>">
    <link rel="shortcut icon" href="<?= $faviconUrl ?>?v=<?= filemtime($faviconFiles[0] ?? '') ?>">
    <?php endif; ?>
    <link rel="stylesheet" href="<?=BASE_URL?>assets/css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --accent: <?= $theme['accent_color'] ?>;
            --accent-rgb: <?= "{$accentR},{$accentG},{$accentB}" ?>;
            --accent-light: rgba(<?= "{$accentR},{$accentG},{$accentB}" ?>, 0.15);
            --accent-glow: rgba(<?= "{$accentR},{$accentG},{$accentB}" ?>, 0.3);
            --accent-text: <?= $theme['accent_color'] ?>;
            --icon-color: <?= !empty($theme['icon_color']) ? $theme['icon_color'] : $theme['accent_color'] ?>;
            --glass-card-bg: rgba(<?= "{$cbR},{$cbG},{$cbB}" ?>, <?= $glassOpacity ?>);
            --card-bg-rgb: <?= "{$cbR},{$cbG},{$cbB}" ?>;
            --text-primary: <?= $theme['text_color'] ?? '#EAEAEA' ?>;
<?php
            // text-primary에서 secondary/tertiary 파생 (rgba)
            $tHex = ltrim($theme['text_color'] ?? '#EAEAEA', '#');
            $tR = hexdec(substr($tHex,0,2));
            $tG = hexdec(substr($tHex,2,2));
            $tB = hexdec(substr($tHex,4,2));
?>
            --text-secondary: rgba(<?= "{$tR},{$tG},{$tB}" ?>, 0.6);
            --text-tertiary: rgba(<?= "{$tR},{$tG},{$tB}" ?>, 0.38);
            --video-dim: <?= $theme['video_opacity'] ?>;
            --sidebar-bg: <?= $theme['sidebar_bg'] ?? 'rgba(10,10,14,0.82)' ?>;
<?php
            // sidebar opacity 추출
            $sbOpacity = 0.82;
            if (preg_match('/([\d.]+)\)\s*$/', $theme['sidebar_bg'] ?? '', $sbM)) {
                $sbOpacity = floatval($sbM[1]);
            }
?>
            --sidebar-opacity: <?= $sbOpacity ?>;
            --form-line-color: <?= $theme['form_line_color'] ?? '#333338' ?>;
            --form-placeholder: <?= $theme['form_placeholder'] ?? '#555560' ?>;
        }
        /* 전체 테이블 중앙 정렬 */
        table th, table td { text-align: center !important; vertical-align: middle !important; }
    </style>
</head>
<body>

<!-- 비디오 배경 -->
<?php
$_videoSrc = !empty($theme['video_url']) ? $theme['video_url'] : BASE_URL.'assets/bg-video.mp4';
$_videoType = str_ends_with(strtolower($_videoSrc), '.webm') ? 'video/webm' : 'video/mp4';
?>
<div class="video-bg">
    <video autoplay muted loop playsinline>
        <source src="<?= htmlspecialchars($_videoSrc) ?>?t=<?= time() ?>" type="<?= $_videoType ?>">
    </video>
</div>

<div class="app-wrapper">

<aside class="sidebar" id="mainSidebar">
    <button class="sidebar-toggle" id="sidebarToggle" title="사이드바 접기/펼치기"><svg viewBox="0 0 24 24" id="toggleIcon" style="transition:transform 0.3s ease;"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg></button>
    <div class="sidebar-inner">
    <div class="sidebar-header">
        <a href="<?=BASE_URL?>pages/home.php" style="text-decoration:none;">
        <?php $logoFiles = glob(__DIR__ . '/../assets/logo.*');
        if ($logoFiles): ?>
        <img src="<?=BASE_URL?>assets/<?= basename($logoFiles[0]) ?>" style="max-height:2rem;max-width:10rem;object-fit:contain;cursor:pointer;" alt="Logo">
        <?php else: ?>
        <h1>AP MEDIA ONE</h1>
        <?php endif; ?>
        </a>
        <div class="subtitle">통합 운영 자동화 시스템</div>
    </div>

    <nav class="sidebar-nav">
        <?php
        // ═══ 사이드바 메뉴 맵 (역할별 접근 제어) ═══
        $myRole = $user['role'];
        $isTL = ($myRole === 'team_leader');
        $isMgr = ($myRole === 'manager');
        $isCeo = ($myRole === 'ceo');
        $isSys = ($myRole === 'sysadmin');
        $isAdmin = ($isCeo || $isSys);

        // ── 메뉴 마스터 정의 (유일한 진실의 소스) ──
        $masterMenus = [
            // [key, label, icon, group, url, sort, roles]
            ['home','홈','🏠','메인',BASE_URL.'pages/home.php',0,'*'],
            ['notice','공지사항','📌','메인',BASE_URL.'pages/notice.php',1,'*'],
            ['team_notice','팀 공지사항','📢','메인',BASE_URL.'pages/team_notice.php',2,'team_leader,manager,ceo,sysadmin'],
            ['team_status','팀 현황','🏢','메인',BASE_URL.'pages/team_status.php',3,'team_leader,manager,ceo,sysadmin'],
            ['dashboard','대시보드','📈','메인',BASE_URL.'pages/dashboard.php',4,'*'],
            ['company_db','기업 DB','🏢','운영',BASE_URL.'pages/company_db.php',9,'*'],
            ['staff_mgmt','조직 현황','👥','운영',BASE_URL.'pages/staff.php',10,'manager,ceo,sysadmin'],
            ['exec_report','경영 보고서','📑','운영',BASE_URL.'pages/exec_report.php',11,'ceo,sysadmin'],
            ['policy','규정 안내','📋','영업',BASE_URL.'pages/policy.php',20,'*'],
            ['sales_report','실적 보고서','📝','영업',BASE_URL.'pages/sales_report.php',21,'*'],
            ['sales','실적 검토','💰','영업',BASE_URL.'pages/sales.php',22,'team_leader,manager,ceo,sysadmin'],
            ['profit','영업 이익현황','📊','영업',BASE_URL.'pages/profit.php',23,'*'],
            ['kpi','KPI 달성률','🎯','영업',BASE_URL.'pages/kpi.php',24,'*'],
            ['pipeline','영업 단계 현황','🔄','영업',BASE_URL.'pages/pipeline.php',25,'*'],
            ['performance','평가 점수','⭐','인사',BASE_URL.'pages/performance.php',30,'*'],
            ['admin_teams','인사 관리','🏅','인사',BASE_URL.'pages/admin_teams.php',31,'ceo,sysadmin'],
            ['evaluation','인사 평가','📝','인사',BASE_URL.'pages/evaluation.php',32,'manager,ceo,sysadmin'],
            ['team_assign','팀장 선정','👑','인사',BASE_URL.'pages/admin_team_assign.php',33,'manager,ceo,sysadmin'],
            ['incentive','인센티브 산출','💎','인사',BASE_URL.'pages/incentive.php',34,'*'],
            ['approval','인센티브 검토','✅','인사',BASE_URL.'pages/approval.php',35,'manager,ceo,sysadmin'],
            ['campaign','캠페인 관리','📢','마케팅',BASE_URL.'pages/marketing/campaign.php',50,'*'],
            ['mkt_performance','마케팅 실적','📊','마케팅',BASE_URL.'pages/marketing/mkt_performance.php',51,'*'],
            ['roi_analysis','ROI 분석','📈','마케팅',BASE_URL.'pages/marketing/roi_analysis.php',52,'manager,ceo,sysadmin'],
            ['brand_strategy','브랜드 전략','🎯','마케팅',BASE_URL.'pages/marketing/brand_strategy.php',53,'manager,ceo,sysadmin'],
            ['content_pipeline','콘텐츠 파이프라인','📝','마케팅',BASE_URL.'pages/marketing/content_pipeline.php',54,'*'],
            ['risk_control','리스크 컨트롤','🛡️','마케팅',BASE_URL.'pages/marketing/risk_control.php',55,'manager,ceo,sysadmin'],
            ['admin_sysinfo','시스템 정보','🖥️','시스템 설정',BASE_URL.'pages/admin_sysinfo.php',60,'sysadmin'],
            ['promotion','프로모션','🎯','시스템 설정',BASE_URL.'pages/promotion.php',61,'manager,ceo,sysadmin'],
            ['incentive_rate','인센티브 비율','💹','시스템 설정',BASE_URL.'pages/incentive_rate.php',62,'ceo,sysadmin'],
            ['admin_accounts','계정 관리','🔑','시스템 설정',BASE_URL.'pages/admin_accounts.php',63,'sysadmin'],
            ['admin_audit','로그 추적','🔍','시스템 설정',BASE_URL.'pages/admin_audit.php',64,'sysadmin'],
            ['menu_manage','권한 관리','🛡️','시스템 설정',BASE_URL.'pages/menu_manage.php',65,'ceo,sysadmin'],
            ['policy_settings','정책 관리','⚙️','시스템 설정',BASE_URL.'pages/policy_settings.php',66,'ceo,sysadmin'],
        ];

        // ── DB 완전 동기화: 모든 역할에 25개 메뉴 전체 보장 ──
        $menuVersion = 'v37_menu_sync';
        if (($_SESSION['menu_ver'] ?? '') !== $menuVersion) {
            $allRoles = ['staff','team_leader','manager','ceo','sysadmin'];
            // 1) 기존 전체 레코드 (role+key => [perm_id, is_visible])
            $existing = [];
            foreach ($db->query("SELECT perm_id, user_role, menu_key, is_visible FROM menu_permission")->fetchAll() as $e) {
                $pair = $e['user_role'] . '|' . $e['menu_key'];
                if (isset($existing[$pair])) {
                    $db->prepare("DELETE FROM menu_permission WHERE perm_id=?")->execute([$e['perm_id']]);
                } else {
                    $existing[$pair] = ['id' => $e['perm_id'], 'vis' => $e['is_visible']];
                }
            }
            // 2) 마스터에 없는 메뉴 삭제
            $masterKeys = array_map(function($m){ return $m[0]; }, $masterMenus);
            foreach ($existing as $pair => $info) {
                $key = explode('|', $pair)[1];
                if (!in_array($key, $masterKeys)) {
                    $db->prepare("DELETE FROM menu_permission WHERE perm_id=?")->execute([$info['id']]);
                    unset($existing[$pair]);
                }
            }
            // 3) 모든 역할에 25개 전체: 없으면 INSERT, 있으면 라벨/그룹/순서만 UPDATE (is_visible 유지)
            $mIns = $db->prepare("INSERT INTO menu_permission (user_role,menu_key,menu_label,menu_icon,menu_group,menu_url,sort_order,is_visible) VALUES(?,?,?,?,?,?,?,?)");
            $mUpd = $db->prepare("UPDATE menu_permission SET menu_label=?,menu_icon=?,menu_group=?,menu_url=?,sort_order=? WHERE perm_id=?");
            foreach ($masterMenus as $fm) {
                $defaultRoles = $fm[6] === '*' ? $allRoles : array_map('trim', explode(',', $fm[6]));
                foreach ($allRoles as $rk) {
                    $pair = $rk . '|' . $fm[0];
                    if (isset($existing[$pair])) {
                        $mUpd->execute([$fm[1], $fm[2], $fm[3], $fm[4], $fm[5], $existing[$pair]['id']]);
                    } else {
                        $vis = in_array($rk, $defaultRoles) ? 1 : 0;
                        $mIns->execute([$rk, $fm[0], $fm[1], $fm[2], $fm[3], $fm[4], $fm[5], $vis]);
                    }
                }
            }
            $_SESSION['menu_ver'] = $menuVersion;
        }

        // ── 사이드바 메뉴: DB에서 로드 (역할 합산) ──
        // 현재 역할 + team_master에서 팀장이면 team_leader 메뉴 합산
        // + 상위 역할 포함 (team_leader는 staff 포함, manager는 team_leader+staff 포함 등)
        $roles = [$myRole];
        
        // team_master에서 팀장이면 team_leader 메뉴도 합산
        $isTeamLeaderInDB = $db->prepare("SELECT COUNT(*) FROM team_master WHERE leader_staff_id=? AND is_active=1");
        $isTeamLeaderInDB->execute([$user['staff_id'] ?? 0]);
        if ($isTeamLeaderInDB->fetchColumn() > 0 && $myRole !== 'team_leader') {
            $roles[] = 'team_leader';
        }
        
        // team_leader_log에서 이전 역할 확인 — 팀장이 되기 전 관리자였으면 manager 메뉴도 합산
        if ($myRole === 'team_leader') {
            try {
                $prevRoleStmt = $db->prepare("SELECT previous_role FROM team_leader_log WHERE staff_id=? AND new_role='team_leader' ORDER BY assigned_at DESC LIMIT 1");
                $prevRoleStmt->execute([$user['staff_id'] ?? 0]);
                $prevRole = $prevRoleStmt->fetchColumn();
                if ($prevRole && $prevRole !== 'team_leader' && !in_array($prevRole, $roles)) {
                    $roles[] = $prevRole;
                }
            } catch(Exception $e) {}
        }
        
        $roles = array_unique($roles);
        $placeholders = implode(',', array_fill(0, count($roles), '?'));
        $menuStmt = $db->prepare("SELECT menu_key, menu_label, menu_icon, menu_group, menu_url, sort_order FROM menu_permission WHERE user_role IN ({$placeholders}) AND is_visible=1 ORDER BY sort_order");
        $menuStmt->execute($roles);
        $dbMenuRows = $menuStmt->fetchAll();

        // 중복 제거 (menu_key 기준, 먼저 나온 것 우선)
        $seen = [];
        $uniqueRows = [];
        foreach ($dbMenuRows as $row) {
            if (!isset($seen[$row['menu_key']])) {
                $seen[$row['menu_key']] = true;
                $uniqueRows[] = $row;
            }
        }
        $dbMenuRows = $uniqueRows;

        // 그룹별로 정리
        $sidebarMenu = [];
        foreach ($dbMenuRows as $row) {
            $sidebarMenu[$row['menu_group']][] = [
                'key'   => $row['menu_key'],
                'label' => $row['menu_label'],
                'icon'  => $row['menu_icon'],
                'url'   => $row['menu_url'],
            ];
        }

        foreach ($sidebarMenu as $group => $visibleItems):
            if (!$visibleItems) continue;
            $isSystem = ($group === '시스템 설정');
        ?>
        <div class="nav-section" <?= $isSystem ? 'style="margin-top:0.5rem;border-top:1px solid rgba(255,255,255,0.06);padding-top:0.5rem;"' : '' ?>><?= $isSystem ? '⚙️ ' : '' ?><?= htmlspecialchars($group) ?></div>
        <?php foreach ($visibleItems as $item):
            $menuFile = strtok(basename($item['url']), '?');
            $menuBasename = basename($menuFile, '.php');
            $isActive = ($currentPage === $menuBasename) ? 'active' : '';
        ?>
        <a href="<?= $item['url'] ?>" class="<?= $isActive ?>" <?= $isSystem ? 'style="font-size:var(--fs-xs);padding:0.4rem 1rem;"' : '' ?>>
            <span class="icon"><?= $item['icon'] ?></span><span class="menu-label"><?= htmlspecialchars($item['label']) ?></span>
        </a>
        <?php endforeach; endforeach; ?>
    </nav>
    <div style="height:180px;flex-shrink:0;"></div><!-- spacer for fixed footer -->

    </div><!-- sidebar-inner -->
</aside>

<!-- 사이드바 하단 고정 (aside 밖 독립 fixed) -->
<div id="sidebarFooter" style="position:fixed;bottom:0;left:0;width:260px;background:rgba(0,0,0,0.5);border-top:1px solid rgba(255,255,255,0.08);padding:0.4rem 0;z-index:200;backdrop-filter:blur(15px);-webkit-backdrop-filter:blur(15px);color:var(--text-primary);">
    <a href="<?=BASE_URL?>pages/my_profile.php" class="<?= $currentPage==='my_profile'?'active':'' ?>" style="font-size:var(--fs-xs);padding:0.35rem 1rem;display:flex;align-items:center;gap:0.5rem;color:var(--text-primary);text-decoration:none;">
        <span class="icon">👤</span><span class="menu-label">내정보 변경</span>
    </a>
    <a href="<?=BASE_URL?>pages/theme_settings.php" class="<?= $currentPage==='theme_settings'?'active':'' ?>" style="font-size:var(--fs-xs);padding:0.35rem 1rem;display:flex;align-items:center;gap:0.5rem;color:var(--text-primary);text-decoration:none;">
        <span class="icon">🎨</span><span class="menu-label">테마 설정</span>
    </a>
    <div style="display:flex;align-items:center;justify-content:space-between;padding:0.5rem 1rem 0.25rem;margin-top:0.25rem;border-top:1px solid rgba(255,255,255,0.06);">
        <div style="display:flex;flex-direction:column;gap:0.1rem;">
            <div style="font-size:var(--fs-sm);font-weight:600;color:var(--text-primary);"><?= crownName($user['name'], $user['role']) ?></div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><span class="role-<?= $user['role'] ?>"><?= $roleLabel ?></span></div>
        </div>
        <a href="<?=BASE_URL?>logout.php" style="font-size:var(--fs-xs);color:var(--text-tertiary);text-decoration:none;padding:0.2rem 0.4rem;border:1px solid var(--border);border-radius:4px;white-space:nowrap;" onmouseover="this.style.color='var(--accent)'" onmouseout="this.style.color='var(--text-tertiary)'">로그아웃</a>
    </div>
</div>

<?php
// ── 알림 시스템 (오른쪽 상단 fixed) ──
$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)
)");
$notiCount = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND is_read=0");
$notiCount->execute([$user['user_id']]); $unreadNoti = $notiCount->fetchColumn();
$notiItems = $db->prepare("SELECT * FROM notifications WHERE user_id=? ORDER BY created_at DESC LIMIT 10");
$notiItems->execute([$user['user_id']]); $notiList = $notiItems->fetchAll();

// 팀장 이름 목록 (왕관 자동 표시용)
$teamLeaderNames = [];
try {
    $teamLeaderNames = $db->query("SELECT DISTINCT s.name FROM staff s JOIN user_account u ON s.staff_id=u.staff_id WHERE u.user_role='team_leader' AND u.is_active=1")->fetchAll(PDO::FETCH_COLUMN);
} catch(Exception $e) {}
?>
<div id="fixedNotiWrap" style="position:fixed;top:1.5rem;right:2.5rem;z-index:10000;display:flex;align-items:center;gap:0.75rem;">
    <div style="position:relative;">
        <a href="javascript:void(0)" onclick="document.getElementById('notiDrop').classList.toggle('show')" style="display:flex;align-items:center;justify-content:center;width:3.2rem;height:3.2rem;background:var(--glass-card-bg);backdrop-filter:blur(12px);border:1px solid var(--border);border-radius:50%;font-size:1.5rem;text-decoration:none;cursor:pointer;transition:box-shadow 0.2s;" title="알림">
            🔔
            <?php if ($unreadNoti > 0): ?>
            <span style="position:absolute;top:-1px;right:-1px;background:var(--danger,#ff4444);color:#fff;font-size:0.6rem;font-weight:800;border-radius:50%;min-width:1.15rem;height:1.15rem;display:flex;align-items:center;justify-content:center;padding:0 0.2rem;"><?= $unreadNoti > 99 ? '99+' : $unreadNoti ?></span>
            <?php endif; ?>
        </a>
        <div id="notiDrop" style="display:none;position:absolute;right:0;top:calc(100% + 0.5rem);width:20rem;background:var(--glass-card-bg);backdrop-filter:blur(20px);border:1px solid var(--border);border-radius:var(--radius-sm);box-shadow:0 8px 24px rgba(0,0,0,0.3);max-height:20rem;overflow-y:auto;">
            <div style="padding:0.6rem 0.75rem;border-bottom:1px solid var(--border);font-size:var(--fs-sm);font-weight:700;color:var(--text-primary);display:flex;justify-content:space-between;align-items:center;">
                <span>🔔 알림</span>
                <?php if($unreadNoti): ?><a href="<?=BASE_URL?>pages/home.php?noti=read_all" style="font-size:var(--fs-xs);color:var(--accent);text-decoration:none;">모두 읽음</a><?php endif; ?>
            </div>
            <?php if($notiList): foreach($notiList as $ni): ?>
            <a href="<?= htmlspecialchars($ni['link']?:BASE_URL.'pages/home.php') ?>" style="display:block;padding:0.5rem 0.75rem;border-bottom:1px solid var(--border);text-decoration:none;font-size:var(--fs-xs);color:<?= !$ni['is_read']?'var(--text-primary)':'var(--text-tertiary)' ?>;<?= !$ni['is_read']?'background:rgba(var(--accent-rgb),0.04);':'' ?>">
                <?= htmlspecialchars($ni['message']) ?>
                <span style="display:block;font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:0.15rem;"><?= date('m/d H:i',strtotime($ni['created_at'])) ?></span>
            </a>
            <?php endforeach; else: ?>
            <div style="padding:1.5rem;text-align:center;font-size:var(--fs-xs);color:var(--text-tertiary);">알림이 없습니다</div>
            <?php endif; ?>
        </div>
        <style>
            #notiDrop.show{display:block!important;}
            #fixedNotiWrap a:hover{box-shadow:0 0 0 3px rgba(var(--accent-rgb),0.2);}
        </style>
    </div>
</div>
<script>
// 알림 외부 클릭 시 닫기
document.addEventListener('click',function(e){
    var nd=document.getElementById('notiDrop'),nw=document.getElementById('fixedNotiWrap');
    if(nd&&nw&&!nw.contains(e.target))nd.classList.remove('show');
});
// 팀장 왕관 자동 표시 (이름 앞에 👑 추가)
(function(){
    var leaders=<?= json_encode($teamLeaderNames) ?>;
    if(!leaders||!leaders.length)return;
    document.querySelectorAll('td strong, .stat-card strong, td a strong').forEach(function(el){
        var t=el.textContent.trim();
        if(t.indexOf('👑')===0)return;
        if(leaders.indexOf(t)!==-1) el.textContent='👑 '+t;
    });
})();
</script>

<main class="main-content">
