<?php
// pages/home.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 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)");

$canWrite = in_array($_SESSION['user_role'], ['manager','ceo','sysadmin']);
$isAdmin = in_array($_SESSION['user_role'], ['manager','ceo','sysadmin']);
$curMonth = date('Y-m');

// POST/GET 처리 (header 전)
// 알림 읽음 처리
if (isset($_GET['noti']) && $_GET['noti']==='read_all') {
    $db->prepare("UPDATE notifications SET is_read=1 WHERE user_id=?")->execute([$_SESSION['user_id']]);
    header("Location: ".BASE_URL."pages/home.php"); exit;
}
// 개별 알림 읽음 후 리다이렉트
if (isset($_GET['noti_read'])) {
    $nid = (int)$_GET['noti_read'];
    $noti = $db->prepare("SELECT link FROM notifications WHERE noti_id=? AND user_id=?"); $noti->execute([$nid, $_SESSION['user_id']]); $nLink = $noti->fetchColumn();
    $db->prepare("UPDATE notifications SET is_read=1 WHERE noti_id=? AND user_id=?")->execute([$nid, $_SESSION['user_id']]);
    header("Location: ".($nLink ?: BASE_URL."pages/home.php")); exit;
}

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

// 팀장(team_master 기준)이면서 관리자인 경우 → 홈에서는 개인 레이아웃 사용
$isTeamLeaderDB = false;
try {
    $tlChk = $db->prepare("SELECT COUNT(*) FROM team_master WHERE leader_staff_id=? AND is_active=1");
    $tlChk->execute([$user['staff_id'] ?? 0]);
    $isTeamLeaderDB = ($tlChk->fetchColumn() > 0);
} catch(Exception $e) {}
if ($isTeamLeaderDB && $_SESSION['user_role'] !== 'ceo' && $_SESSION['user_role'] !== 'sysadmin') {
    $isAdmin = false;
}

// ── 프로필 ──
$profileStmt = $db->prepare("SELECT st.*, ua.login_id, ua.last_login, ua.user_role FROM staff st JOIN user_account ua ON st.staff_id=ua.staff_id WHERE ua.user_id=?");
$profileStmt->execute([$user['user_id']]);
$profile = $profileStmt->fetch(PDO::FETCH_ASSOC);

$hireDate = new DateTime($profile['hire_date']); $now = new DateTime();
$yearsWorked = max(1, $hireDate->diff($now)->y);
$usedAnnual = 0;

// ── 슬라이드 ──
$db->exec("CREATE TABLE IF NOT EXISTS user_images (img_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, filename VARCHAR(255), sort_order INT DEFAULT 0, uploaded_at DATETIME DEFAULT CURRENT_TIMESTAMP, INDEX idx_user(user_id))");
$slides = $db->prepare("SELECT filename FROM user_images WHERE user_id=? ORDER BY sort_order");
$slides->execute([$user['user_id']]); $slides = $slides->fetchAll(PDO::FETCH_COLUMN);

// ── 내 실적 (이번 달) ──
$mySales = $db->prepare("SELECT COALESCE(SUM(revenue),0) AS rev, COALESCE(SUM(net_profit),0) AS profit FROM sales WHERE staff_id=? AND sale_month=?");
$mySales->execute([$user['staff_id'], $curMonth]); $my = $mySales->fetch();

// 오늘 순이익
$todayProfit = $db->prepare("SELECT COALESCE(SUM(net_profit),0) FROM sales WHERE staff_id=? AND DATE(created_at)=CURDATE()");
$todayProfit->execute([$user['staff_id']]); $todayProfit = $todayProfit->fetchColumn();

// ── 평가점수 (최근) ──
$myScore = $db->prepare("SELECT * FROM performance_score WHERE staff_id=? ORDER BY eval_month DESC LIMIT 1");
$myScore->execute([$user['staff_id']]); $score = $myScore->fetch();
$scoreTotalNum = 0; $scoreMax = 0;
if ($score) {
    $scoreTotalNum = ($score['quant_revenue_rate']??0) + ($score['quant_deal_rate']??0) + ($score['qual_attitude']??0) + ($score['qual_teamwork']??0) + ($score['qual_contrib']??0);
    $scoreMax = 100 + 100 + 10 + 10 + 10; // 정량2개(100점 만점) + 정성3개(10점 만점)
}

// ── KPI 달성률 (이번 달) ──
$myKpi = $db->prepare("SELECT target_deals, target_amount FROM kpi_target WHERE staff_id=? AND target_month=?");
$myKpi->execute([$user['staff_id'], $curMonth]); $kpi = $myKpi->fetch();
// 개인 목표 없으면 정책 기본값 사용
if (!$kpi || (!$kpi['target_deals'] && !$kpi['target_amount'])) {
    try { $policyTargets = $db->query("SELECT rule_key, rule_value FROM policy_rule WHERE rule_key IN ('revenue_target_monthly','profit_target_monthly','deal_target_monthly','incentive_min_deals')")->fetchAll(PDO::FETCH_KEY_PAIR); } catch(Exception $e) { $policyTargets = []; }
    $kpi = ['target_deals' => (int)str_replace(',', '', $policyTargets['deal_target_monthly'] ?? '0'), 'target_amount' => (int)str_replace(',', '', $policyTargets['profit_target_monthly'] ?? '0')];
}
$myDeals = $db->prepare("SELECT COUNT(*) FROM sales WHERE staff_id=? AND sale_month=? AND stage IN ('계약','촬영','방송완료')");
$myDeals->execute([$user['staff_id'], $curMonth]); $dealCnt = $myDeals->fetchColumn();
$kpiDealRate = ($kpi && $kpi['target_deals']>0) ? round($dealCnt/$kpi['target_deals']*100,1) : 0;
$kpiAmtRate = ($kpi && $kpi['target_amount']>0) ? round($my['profit']/$kpi['target_amount']*100,1) : 0;

// ── 승인 대기 ──
$pendingApproval = $db->query("SELECT COUNT(*) FROM approval_flow WHERE approve_status='대기'")->fetchColumn();
// ── 가입 승인 대기 ──
$pendingUsers = 0;
if (in_array($_SESSION['user_role']??'', ['sysadmin','ceo','manager'])) {
    try { $pendingUsers = (int)$db->query("SELECT COUNT(*) FROM user_account WHERE approval_status='대기'")->fetchColumn(); } catch(Exception $e) {}
}

// ── 계약성사 건수 (년/월/주/일) ──
$contractYear = $db->prepare("SELECT COUNT(*) FROM sales WHERE staff_id=? AND YEAR(contract_date)=YEAR(CURDATE()) AND stage IN ('계약','촬영','방송완료') AND confirm_type='확정'");
$contractYear->execute([$user['staff_id']]); $contractYearCnt = $contractYear->fetchColumn();
$contractMonth = $db->prepare("SELECT COUNT(*) FROM sales WHERE staff_id=? AND sale_month=? AND stage IN ('계약','촬영','방송완료') AND confirm_type='확정'");
$contractMonth->execute([$user['staff_id'], $curMonth]); $contractMonthCnt = $contractMonth->fetchColumn();
$weekStart = date('Y-m-d', strtotime('monday this week'));
$contractWeek = $db->prepare("SELECT COUNT(*) FROM sales WHERE staff_id=? AND contract_date>=? AND stage IN ('계약','촬영','방송완료') AND confirm_type='확정'");
$contractWeek->execute([$user['staff_id'], $weekStart]); $contractWeekCnt = $contractWeek->fetchColumn();
$contractDay = $db->prepare("SELECT COUNT(*) FROM sales WHERE staff_id=? AND DATE(contract_date)=CURDATE() AND stage IN ('계약','촬영','방송완료') AND confirm_type='확정'");
$contractDay->execute([$user['staff_id']]); $contractDayCnt = $contractDay->fetchColumn();

// ── 조직 인원 / 인센티브 (관리자만) ──
$orgCount = 0; $incentiveData = [];
$fIncYear = $_GET['inc_year'] ?? date('Y');
$fIncMonth = $_GET['inc_month'] ?? $curMonth;

// incentive_rate.is_active 컬럼 보장
try { $db->query("SELECT is_active FROM incentive_rate LIMIT 0"); } catch(Exception $e) {
    try { $db->exec("ALTER TABLE incentive_rate ADD COLUMN is_active TINYINT(1) DEFAULT 1"); } catch(Exception $e2) {}
}

if ($isAdmin) {
    $orgCount = $db->query("SELECT COUNT(*) FROM staff WHERE is_active=1")->fetchColumn();
    try { $incentiveData = $db->query("SELECT ic.staff_id, ic.name, ic.grade, ic.team, ic.sale_month, ic.total_net_profit, ic.eligible, ic.incentive_min, ic.incentive_max FROM v_incentive_calc ic LEFT JOIN incentive_rate ir2 ON ic.grade=ir2.grade WHERE ic.sale_month='$curMonth' AND COALESCE(ir2.is_active,1)=1 ORDER BY ic.total_net_profit DESC LIMIT 10")->fetchAll(); } catch(Exception $e) { $incentiveData = []; }

    // ── 관리자용: 실적 직원 제외 조건 (ceo/sysadmin/manager, 단 팀장은 포함) ──
    $excludeRoles = "('ceo','sysadmin','manager')";

    // 평가점수 평균 (관리직 제외)
    $avgScoreQ = $db->query("SELECT AVG(
        COALESCE(ps.quant_revenue_rate,0)+COALESCE(ps.quant_deal_rate,0)+COALESCE(ps.qual_attitude,0)+COALESCE(ps.qual_teamwork,0)+COALESCE(ps.qual_contrib,0)
    ) AS avg_score
    FROM performance_score ps
    JOIN staff st ON ps.staff_id=st.staff_id
    WHERE ps.eval_month=(SELECT MAX(eval_month) FROM performance_score)
    AND NOT EXISTS (SELECT 1 FROM user_account ua WHERE ua.staff_id=st.staff_id AND ua.user_role IN $excludeRoles)");
    $adminAvgScore = round((float)($avgScoreQ->fetchColumn() ?? 0), 1);

    // KPI 평균 달성률 (관리직 제외)
    $avgKpiQ = $db->query("SELECT
        AVG(CASE WHEN ic.target_deals > 0 THEN ic.deal_count / ic.target_deals * 100 ELSE 0 END) AS avg_deal_rate,
        AVG(CASE WHEN ic.target_amount > 0 THEN ic.total_revenue / ic.target_amount * 100 ELSE 0 END) AS avg_amt_rate
    FROM v_incentive_calc ic
    JOIN staff st ON ic.staff_id=st.staff_id
    WHERE ic.sale_month='$curMonth'
    AND NOT EXISTS (SELECT 1 FROM user_account ua WHERE ua.staff_id=st.staff_id AND ua.user_role IN $excludeRoles)");
    $avgKpi = $avgKpiQ->fetch();
    $adminAvgDealRate = round((float)($avgKpi['avg_deal_rate'] ?? 0), 1);
    $adminAvgAmtRate = round((float)($avgKpi['avg_amt_rate'] ?? 0), 1);

    // 계약 성사 평균 (관리직 제외) - 월간/연간
    $avgContractMonth = $db->query("SELECT AVG(cnt) FROM (
        SELECT COUNT(*) AS cnt FROM sales s JOIN staff st ON s.staff_id=st.staff_id
        WHERE s.sale_month='$curMonth' AND s.stage IN ('계약','촬영','방송완료') AND s.confirm_type='확정'
        AND NOT EXISTS (SELECT 1 FROM user_account ua WHERE ua.staff_id=st.staff_id AND ua.user_role IN $excludeRoles)
        GROUP BY s.staff_id
    ) sub")->fetchColumn();
    $adminAvgContractMonth = (int)round((float)($avgContractMonth ?? 0));

    $avgContractYear = $db->query("SELECT AVG(cnt) FROM (
        SELECT COUNT(*) AS cnt FROM sales s JOIN staff st ON s.staff_id=st.staff_id
        WHERE YEAR(s.contract_date)=YEAR(CURDATE()) AND s.stage IN ('계약','촬영','방송완료') AND s.confirm_type='확정'
        AND NOT EXISTS (SELECT 1 FROM user_account ua WHERE ua.staff_id=st.staff_id AND ua.user_role IN $excludeRoles)
        GROUP BY s.staff_id
    ) sub")->fetchColumn();
    $adminAvgContractYear = (int)round((float)($avgContractYear ?? 0));

    // 인센티브 검토 대기 건수 (approval_flow 연동 — 역할별 상세)
    try {
        // 관리자 기준: 대기/확인/보류
        $mgrWait = (int)$db->query("SELECT COUNT(*) FROM approval_flow WHERE review_status='대기'")->fetchColumn();
        $mgrConfirm = (int)$db->query("SELECT COUNT(*) FROM approval_flow WHERE review_status='확인'")->fetchColumn();
        $mgrHold = (int)$db->query("SELECT COUNT(*) FROM approval_flow WHERE review_status='보류'")->fetchColumn();
        // 대표 기준: 대기/승인/보류
        $ceoWait = (int)$db->query("SELECT COUNT(*) FROM approval_flow WHERE review_status='확인' AND approve_status='대기'")->fetchColumn();
        $ceoApproved = (int)$db->query("SELECT COUNT(*) FROM approval_flow WHERE approve_status='승인'")->fetchColumn();
        $ceoHold = (int)$db->query("SELECT COUNT(*) FROM approval_flow WHERE approve_status='보류'")->fetchColumn();
    } catch(Exception $e) { $mgrWait=0; $mgrConfirm=0; $mgrHold=0; $ceoWait=0; $ceoApproved=0; $ceoHold=0; }

    // 총 인센티브 집계 (월간 + 누적)
    $incSummaryMonth = $db->query("SELECT
        COUNT(CASE WHEN ic.eligible='Y' THEN 1 END) AS eligible_cnt,
        SUM(CASE WHEN ic.eligible='Y' THEN ic.incentive_max ELSE 0 END) AS total_max,
        SUM(CASE WHEN ic.eligible='Y' THEN ic.incentive_min ELSE 0 END) AS total_min
    FROM v_incentive_calc ic WHERE ic.sale_month='$fIncMonth'")->fetch();

    $incTopMonth = $db->query("SELECT ic.name, ic.incentive_max FROM v_incentive_calc ic WHERE ic.sale_month='$fIncMonth' AND ic.eligible='Y' ORDER BY ic.incentive_max DESC LIMIT 1")->fetch();
    $incBottomMonth = $db->query("SELECT ic.name, ic.incentive_min FROM v_incentive_calc ic WHERE ic.sale_month='$fIncMonth' AND ic.eligible='Y' AND ic.incentive_min > 0 ORDER BY ic.incentive_min ASC LIMIT 1")->fetch();

    // 사용 가능한 월 목록
    $availIncMonths = $db->query("SELECT DISTINCT sale_month FROM sales ORDER BY sale_month DESC")->fetchAll(PDO::FETCH_COLUMN);
    if (!$availIncMonths) $availIncMonths = [$curMonth];

    // 누적 (해당 연도)
    $incSummaryYear = $db->query("SELECT
        COUNT(DISTINCT CASE WHEN ic.eligible='Y' THEN ic.staff_id END) AS eligible_cnt,
        SUM(CASE WHEN ic.eligible='Y' THEN ic.incentive_max ELSE 0 END) AS total_max,
        SUM(CASE WHEN ic.eligible='Y' THEN ic.incentive_min ELSE 0 END) AS total_min
    FROM v_incentive_calc ic WHERE LEFT(ic.sale_month,4)='$fIncYear'")->fetch();

    $incTopYear = $db->query("SELECT ic.name, SUM(ic.incentive_max) AS total FROM v_incentive_calc ic WHERE LEFT(ic.sale_month,4)='$fIncYear' AND ic.eligible='Y' GROUP BY ic.staff_id, ic.name ORDER BY total DESC LIMIT 1")->fetch();
    $incBottomYear = $db->query("SELECT ic.name, SUM(ic.incentive_min) AS total FROM v_incentive_calc ic WHERE LEFT(ic.sale_month,4)='$fIncYear' AND ic.eligible='Y' GROUP BY ic.staff_id, ic.name HAVING total > 0 ORDER BY total ASC LIMIT 1")->fetch();
}

// ── 내 인센티브 ──
$myIncentive = $db->prepare("SELECT * FROM v_incentive_calc WHERE staff_id=? AND sale_month=? LIMIT 1");
$myIncentive->execute([$user['staff_id'], $curMonth]); $myInc = $myIncentive->fetch();

// ── 매출 기여도 ──
$fMonth = $_GET['month'] ?? '';
$contribWhere = "WHERE s.stage IN ('계약','촬영','방송완료') AND s.confirm_type='확정'";
$contribParams = [];
if ($fMonth) { $contribWhere .= " AND s.sale_month=?"; $contribParams[] = $fMonth; }
else { $contribWhere .= " AND s.sale_month=?"; $contribParams[] = $curMonth; }
$totalRevAll = $db->prepare("SELECT COALESCE(SUM(s.revenue),0) FROM sales s $contribWhere");
$totalRevAll->execute($contribParams); $totalRevenue = (int)$totalRevAll->fetchColumn();

// 관리직 제외 기여도 (일반 사용자 전체)
$staffContrib = $db->prepare("SELECT s.staff_id, st.name, st.team, st.grade, SUM(s.revenue) AS rev
    FROM sales s JOIN staff st ON s.staff_id=st.staff_id
    $contribWhere AND st.grade NOT IN ('대표','본부장','총괄')
    AND NOT EXISTS (SELECT 1 FROM user_account ua WHERE ua.staff_id=st.staff_id AND ua.user_role IN ('ceo','sysadmin'))
    GROUP BY s.staff_id ORDER BY rev DESC");
$staffContrib->execute($contribParams);
$contribData = $staffContrib->fetchAll();
$contribTotal = array_sum(array_column($contribData, 'rev'));

// ── 인센티브 현황 테이블 데이터 ──
$incYears = $db->query("SELECT DISTINCT LEFT(sale_month,4) FROM sales ORDER BY 1 DESC")->fetchAll(PDO::FETCH_COLUMN);
if (!$incYears) $incYears = [date('Y')];
$fIncTableMonth = $_GET['inc_month'] ?? '';
$incMonthCond = $fIncTableMonth ? "AND ic.sale_month=?" : "";
$incMonthParams = $fIncTableMonth ? [$fIncTableMonth] : [];
// 최소 성사건수 (인센티브 대상 기준)
try { $incMinDeals = (int)str_replace(',', '', $db->query("SELECT rule_value FROM policy_rule WHERE rule_key='incentive_min_deals'")->fetchColumn()); } catch(Exception $e) { $incMinDeals = 3; }
if (!$incMinDeals) $incMinDeals = 3;
try { $policyRevTarget = (int)str_replace(',', '', $db->query("SELECT rule_value FROM policy_rule WHERE rule_key='revenue_target_monthly'")->fetchColumn()); } catch(Exception $e) { $policyRevTarget = 0; }
try { $policyProfitTarget = (int)str_replace(',', '', $db->query("SELECT rule_value FROM policy_rule WHERE rule_key='profit_target_monthly'")->fetchColumn()); } catch(Exception $e) { $policyProfitTarget = 0; }
try { $policyDealTarget = (int)str_replace(',', '', $db->query("SELECT rule_value FROM policy_rule WHERE rule_key='deal_target_monthly'")->fetchColumn()); } catch(Exception $e) { $policyDealTarget = 0; }

// 대표/시스템관리자: 개인별 상세, 관리자(팀장 아닌): 자기팀, 팀장/직원: 본인
try {
$curMonthForInc = $fIncTableMonth ?: date('Y-m');
if (in_array($user['role'], ['ceo','sysadmin']) && !$isTeamLeaderDB) {
    $incSql = "SELECT ic.sale_month, ic.name, ic.staff_id, ic.grade, ic.deal_count AS deals,
        ic.total_net_profit AS profit, ic.total_revenue, ic.incentive_min, ic.incentive_max, ic.eligible, ic.target_deals, ic.target_amount, ic.rate_basis,
        COALESCE(af2.review_status, '대기') AS review_status, COALESCE(af2.approve_status, '대기') AS approve_status,
        af2.final_amount
        FROM v_incentive_calc ic
        LEFT JOIN approval_flow af2 ON ic.staff_id=af2.staff_id AND ic.sale_month=af2.approval_month
        WHERE (LEFT(ic.sale_month,4)=? OR ic.sale_month IS NULL)";
    $incParams = [$fIncYear];
    if ($fIncTableMonth) { $incSql .= " AND ic.sale_month = ?"; $incParams[] = $fIncTableMonth; }
    $incSql .= " ORDER BY ic.sale_month DESC, ic.total_net_profit DESC";
    $incMonthly = $db->prepare($incSql);
    $incMonthly->execute($incParams); $incMonthlyData = $incMonthly->fetchAll();
} elseif ($user['role'] === 'manager' && !$isTeamLeaderDB) {
    $myTeamQ = $db->prepare("SELECT team FROM staff WHERE staff_id=?");
    $myTeamQ->execute([$user['staff_id']]); $myTeamName = $myTeamQ->fetchColumn();
    $incSql = "SELECT ic.sale_month, ic.name, ic.staff_id, ic.grade, ic.deal_count AS deals,
        ic.total_net_profit AS profit, ic.total_revenue, ic.incentive_min, ic.incentive_max, ic.eligible, ic.target_deals, ic.target_amount, ic.rate_basis,
        COALESCE(af2.review_status, '대기') AS review_status, COALESCE(af2.approve_status, '대기') AS approve_status,
        af2.final_amount
        FROM v_incentive_calc ic
        LEFT JOIN approval_flow af2 ON ic.staff_id=af2.staff_id AND ic.sale_month=af2.approval_month
        WHERE ic.team=? AND (LEFT(ic.sale_month,4)=? OR ic.sale_month IS NULL)";
    $incParams = [$myTeamName ?: '', $fIncYear];
    if ($fIncTableMonth) { $incSql .= " AND ic.sale_month = ?"; $incParams[] = $fIncTableMonth; }
    $incSql .= " ORDER BY ic.sale_month DESC, ic.total_net_profit DESC";
    $incMonthly = $db->prepare($incSql);
    $incMonthly->execute($incParams); $incMonthlyData = $incMonthly->fetchAll();
} else {
    $incMonthly = $db->prepare("SELECT ic.sale_month, ic.name, ic.staff_id, ic.grade, ic.deal_count AS deals,
        ic.total_net_profit AS profit, ic.total_revenue, ic.incentive_min, ic.incentive_max, ic.eligible, ic.target_deals, ic.target_amount, ic.rate_basis,
        COALESCE(af2.review_status, '대기') AS review_status, COALESCE(af2.approve_status, '대기') AS approve_status,
        (SELECT af.final_amount FROM approval_flow af WHERE af.staff_id=? AND af.approval_month=ic.sale_month AND af.approve_status='승인' ORDER BY af.approval_id DESC LIMIT 1) AS final_amount
        FROM v_incentive_calc ic
        LEFT JOIN approval_flow af2 ON ic.staff_id=af2.staff_id AND ic.sale_month=af2.approval_month
        WHERE ic.staff_id=? AND LEFT(ic.sale_month,4)=? $incMonthCond ORDER BY ic.sale_month DESC");
    $incMonthly->execute(array_merge([$user['staff_id'], $user['staff_id'], $fIncYear], $incMonthParams));
    $incMonthlyData = $incMonthly->fetchAll();
}
} catch(Exception $e) { $incMonthlyData = []; }
// ── 공지사항 (최신 5개만, 전체는 notice.php) ──
$notices = $db->query("SELECT n.*, s.name AS author_name FROM notice n LEFT JOIN user_account u ON n.author_id=u.user_id LEFT JOIN staff s ON u.staff_id=s.staff_id ORDER BY n.is_pinned DESC, n.created_at DESC LIMIT 5")->fetchAll();

// ── 알림 (7일 보관, 페이지네이션) ──
$db->exec("DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
$notiTotal = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND is_read=0");
$notiTotal->execute([$_SESSION['user_id']]); $notiTotalCount = (int)$notiTotal->fetchColumn();
$notiPage = max(1, (int)($_GET['noti_page'] ?? 1));
$notiPerPage = 5;
$notiOffset = ($notiPage - 1) * $notiPerPage;
$notiTotalPages = max(1, ceil($notiTotalCount / $notiPerPage));
$myNotis = $db->prepare("SELECT * FROM notifications WHERE user_id=? AND is_read=0 ORDER BY created_at DESC LIMIT $notiPerPage OFFSET $notiOffset");
$myNotis->execute([$_SESSION['user_id']]); $notiList = $myNotis->fetchAll();
$unreadCount = $notiTotalCount;

// ── 최근 활동 (관리자: 전체, 일반: 개인) ──
$actItems = [];
if ($isAdmin) {
    // 전체 사용자 최근 활동
    try {
        $aStmt = $db->query("SELECT '승인' AS type, CONCAT(s.name,' ',af.approval_month,' ',af.approve_status) AS detail, af.approve_status AS status, COALESCE(af.approve_date, af.review_date) AS updated_at FROM approval_flow af JOIN staff s ON af.staff_id=s.staff_id ORDER BY af.approval_id DESC LIMIT 10");
        foreach($aStmt->fetchAll() as $a) $actItems[] = $a;
    } catch(Exception $e) {}
    try {
        $sStmt = $db->query("SELECT '매출' AS type, CONCAT(st.name,' - ',sa.company_name,' ',sa.program_name) AS detail, sa.stage AS status, sa.created_at AS updated_at FROM sales sa JOIN staff st ON sa.staff_id=st.staff_id ORDER BY sa.created_at DESC LIMIT 10");
        foreach($sStmt->fetchAll() as $s) $actItems[] = $s;
    } catch(Exception $e) {}
    try {
        $iStmt = $db->query("SELECT '인센티브' AS type, CONCAT(ic.name,' ',ic.sale_month,' 순이익 ',FORMAT(ic.total_net_profit,0),'원') AS detail, ic.eligible AS status, ic.sale_month AS updated_at FROM v_incentive_calc ic ORDER BY ic.sale_month DESC, ic.total_net_profit DESC LIMIT 10");
        foreach($iStmt->fetchAll() as $iv) $actItems[] = $iv;
    } catch(Exception $e) {}
} else {
    // 개인 활동
    try {
        $aStmt = $db->prepare("SELECT '승인' AS type, CONCAT(approval_month,' ',approve_status) AS detail, approve_status AS status, COALESCE(approve_date, review_date) AS updated_at FROM approval_flow WHERE staff_id=? ORDER BY approval_id DESC LIMIT 5");
        $aStmt->execute([$user['staff_id']]);
        foreach($aStmt->fetchAll() as $a) $actItems[] = $a;
    } catch(Exception $e) {}
    try {
        $sStmt = $db->prepare("SELECT '매출' AS type, CONCAT(company_name,' - ',program_name) AS detail, stage AS status, created_at AS updated_at FROM sales WHERE staff_id=? ORDER BY created_at DESC LIMIT 5");
        $sStmt->execute([$user['staff_id']]);
        foreach($sStmt->fetchAll() as $s) $actItems[] = $s;
    } catch(Exception $e) {}
    try {
        $iStmt = $db->prepare("SELECT '인센티브' AS type, CONCAT(sale_month,' 순이익 ',FORMAT(total_net_profit,0),'원') AS detail, eligible AS status, sale_month AS updated_at FROM v_incentive_calc WHERE staff_id=? ORDER BY sale_month DESC LIMIT 3");
        $iStmt->execute([$user['staff_id']]);
        foreach($iStmt->fetchAll() as $iv) $actItems[] = $iv;
    } catch(Exception $e) {}
}
usort($actItems, fn($a,$b) => strtotime($b['updated_at']??'0') - strtotime($a['updated_at']??'0'));
$recentActivity = array_slice($actItems, 0, 10);
?>

<?php
$hour = (int)date('H');
if ($hour >= 18) { $greetLine1 = 'AP Media의 하루가 저물었습니다..'; $greetLine2 = '오늘도 수고한 당신을 응원합니다!'; }
elseif ($hour >= 12) { $greetLine1 = 'AP Media의 오후가 시작되었습니다.'; $greetLine2 = '오늘도 좋은 하루 되세요!'; }
else { $greetLine1 = 'AP Media의 하루가 시작 되었습니다.'; $greetLine2 = '오늘도 좋은 하루 되세요!'; }
$showLoginPopup = false;
if (!empty($_SESSION['show_login_popup'])) { $showLoginPopup = true; unset($_SESSION['show_login_popup']); }
?>
<?php
// 프로모션 (활성)
$activePromos = [];
try {
    $db->exec("CREATE TABLE IF NOT EXISTS promotion (promo_id INT AUTO_INCREMENT PRIMARY KEY, promo_month VARCHAR(7), title VARCHAR(200), description TEXT, is_active TINYINT(1) DEFAULT 1, created_by INT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
    $activePromos = $db->query("SELECT * FROM promotion WHERE is_active=1 AND promo_month='".date('Y-m')."' ORDER BY promo_id DESC")->fetchAll();
} catch(Exception $e) {}
?>
<div class="page-header"><h2>🏠 홈</h2>
    <div class="breadcrumb"><?= date('Y년 m월 d일 l') ?></div>
</div>

<?php if ($activePromos): ?>
<div style="margin-bottom:1rem;">
<?php foreach ($activePromos as $promo): ?>
<div style="background:linear-gradient(90deg, rgba(var(--accent-rgb),0.12), rgba(var(--accent-rgb),0.03));border:1px solid rgba(var(--accent-rgb),0.2);border-radius:var(--radius-sm);padding:0.75rem 1rem;margin-bottom:0.5rem;display:flex;align-items:center;gap:0.75rem;">
    <span style="font-size:1.25rem;">🎯</span>
    <div><strong style="font-size:var(--fs-sm);color:var(--accent-text);">[<?= $promo['promo_month'] ?>] <?= htmlspecialchars($promo['title']) ?></strong>
    <?php if($promo['description']): ?><div style="font-size:var(--fs-xs);color:var(--text-secondary);margin-top:0.15rem;"><?= htmlspecialchars($promo['description']) ?></div><?php endif; ?>
    </div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ═══ 알림 패널 (최상단) ═══ -->
<?php if ($notiTotalCount > 0): ?>
<div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header">
        <h3>🔔 알림 <?php if($unreadCount): ?><span class="badge badge-danger" style="font-size:var(--fs-xs);margin-left:0.25rem;"><?= $unreadCount ?> 새 알림</span><?php endif; ?>
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:400;margin-left:0.5rem;">7일 후 메시지 사라집니다</span></h3>
        <?php if($unreadCount): ?><a href="?noti=read_all" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);">모두 읽음</a><?php endif; ?>
    </div>
    <div>
    <?php foreach($notiList as $n):
        $daysLeft = 7 - (int)((time() - strtotime($n['created_at'])) / 86400);
    ?>
    <a href="<?= BASE_URL ?>pages/home.php?noti_read=<?= $n['noti_id'] ?>" style="display:flex;gap:0.75rem;align-items:center;padding:0.5rem 1rem;border-bottom:1px solid var(--border);text-decoration:none;">
        <span style="font-size:var(--fs-sm);flex:1;color:<?= !$n['is_read']?'var(--text-primary)':'var(--text-tertiary)' ?>;"><?= htmlspecialchars($n['message']) ?></span>
        <span style="font-size:var(--fs-xs);color:<?= $daysLeft<=2?'var(--accent)':'var(--text-tertiary)' ?>;white-space:nowrap;"><?= date('m/d H:i', strtotime($n['created_at'])) ?><?= $daysLeft<=2 ? ' · '.$daysLeft.'일 남음' : '' ?></span>
    </a>
    <?php endforeach; ?>
    </div>
    <?php if ($notiTotalPages > 1): ?>
    <div style="display:flex;justify-content:center;align-items:center;gap:0.5rem;padding:0.5rem;">
        <?php if ($notiPage > 1): ?><a href="?noti_page=<?= $notiPage-1 ?>" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;">◀ 이전</a><?php endif; ?>
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $notiPage ?> / <?= $notiTotalPages ?></span>
        <?php if ($notiPage < $notiTotalPages): ?><a href="?noti_page=<?= $notiPage+1 ?>" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;">다음 ▶</a><?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- ═══ 상단: 프로필 + 슬라이드 + 공지사항 ═══ -->
<?php
$myContrib = 0;
foreach ($contribData as $cd) { if ($cd['staff_id'] == $user['staff_id']) { $myContrib = (int)$cd['rev']; break; } }
$myPct = $contribTotal > 0 ? round($myContrib / $contribTotal * 100, 1) : 0;
$chartContrib = array_slice($contribData, 0, 8);
$contribLabels = json_encode(array_map(fn($c) => $c['name'], $chartContrib), JSON_UNESCAPED_UNICODE);
$contribValues = json_encode(array_map(fn($c) => round((int)$c['rev'] / max($contribTotal,1) * 100, 1), $chartContrib));
?>

<?php if ($isAdmin): ?>
<!-- ═══ 관리자/대표 홈 레이아웃 ═══ -->
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1.25rem;margin-bottom:1.25rem;align-items:stretch;grid-auto-rows:minmax(0,1fr);max-height:18rem;overflow:hidden;">
    <!-- 프로필 카드 -->
    <div class="card" style="padding:1rem;overflow:hidden;display:flex;align-items:center;justify-content:center;gap:2rem;">
        <!-- 사진 -->
        <div style="width:6.5rem;height:6.5rem;border-radius:50%;overflow:hidden;flex-shrink:0;background:var(--card-bg-color);border:2px solid var(--border);">
            <?php
            $photoSrc = BASE_URL.'assets/empty.png';
            $profileGlob = glob(__DIR__ . '/../assets/theme/' . $user['user_id'] . '/profile.*');
            if ($profileGlob) { $photoSrc = BASE_URL.'assets/theme/' . $user['user_id'] . '/' . basename($profileGlob[0]); }
            ?>
            <img src="<?= $photoSrc ?>" alt="프로필" style="width:100%;height:100%;object-fit:cover;">
        </div>
        <!-- 정보 -->
        <div style="min-width:0;">
            <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.15rem;">
                <span style="font-size:var(--fs-lg);font-weight:700;color:var(--text-primary);"><?= crownName($profile['name'], $_SESSION['user_role']??'') ?></span>
                <span style="display:inline-block;padding:0.1rem 0.45rem;border-radius:10px;font-size:var(--fs-xs);font-weight:700;color:var(--accent-text);border:1.5px solid var(--accent);background:rgba(var(--accent-rgb),0.1);white-space:nowrap;"><?= trim($profile['grade']) ? htmlspecialchars($profile['grade']) : '직급없음' ?></span>
            </div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.5rem;"><?= htmlspecialchars($profile['login_id']) ?> · <?= getRoleLabel($profile['user_role']) ?></div>
            <div style="display:flex;gap:1.25rem;font-size:var(--fs-xs);padding-top:0.4rem;border-top:1px solid var(--border);flex-wrap:wrap;">
                <div><span style="color:var(--text-tertiary);">팀</span> <strong style="color:var(--text-primary);margin-left:0.2rem;"><?= htmlspecialchars($profile['team'] ?: '-') ?></strong></div>
                <div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><span style="color:var(--text-tertiary);">이메일</span> <strong style="color:var(--text-primary);margin-left:0.2rem;"><?= htmlspecialchars($profile['email']) ?></strong></div>
                <div><span style="color:var(--text-tertiary);">입사일</span> <strong style="color:var(--text-primary);margin-left:0.2rem;"><?= $profile['hire_date'] ?></strong></div>
            </div>
        </div>
    </div>

    <!-- 이미지 슬라이드 (독립 카드) -->
    <div class="card" style="padding:0;overflow:hidden;">
        <?php if ($slides): ?>
        <div class="home-slide-wrap" style="height:100%;"><div class="home-slide-track" id="slideTrack" style="height:100%;">
            <?php foreach($slides as $sf): ?><div class="home-slide-item" style="height:100%;"><img src="<?=BASE_URL?>assets/theme/<?= $user['user_id'] ?>/slides/<?= htmlspecialchars($sf) ?>" alt="" style="width:100%;height:100%;object-fit:cover;"></div><?php endforeach; ?>
        </div></div>
        <?php else: ?>
        <div style="height:100%;display:flex;align-items:center;justify-content:center;color:var(--text-tertiary);font-size:var(--fs-xs);min-height:7rem;">
            <a href="<?=BASE_URL?>pages/theme_settings.php" style="color:var(--accent);">🖼️ 이미지 추가</a>
        </div>
        <?php endif; ?>
    </div>

    <!-- 공지사항 (최신 5개, 클릭시 notice.php로 이동) -->
    <div class="card" style="display:flex;flex-direction:column;overflow:hidden;">
        <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;flex-shrink:0;">
            <h3>📌 공지사항</h3>
            <a href="<?=BASE_URL?>pages/notice.php" style="font-size:var(--fs-xs);color:var(--accent);text-decoration:none;">전체보기 →</a>
        </div>
        <div style="flex:1;overflow-y:auto;">
        <?php if ($notices): foreach($notices as $n): ?>
        <a href="<?=BASE_URL?>pages/notice.php?mode=view&id=<?= $n['notice_id'] ?>" style="padding:0.45rem 0.75rem;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:0.75rem;text-decoration:none;transition:background 0.15s;" onmouseover="this.style.background='rgba(255,255,255,0.03)'" onmouseout="this.style.opacity='1'">
            <div style="flex:1;min-width:0;font-size:var(--fs-sm);font-weight:600;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                <?php if($n['is_pinned']): ?><span style="color:var(--accent);">📌</span> <?php endif; ?><?= htmlspecialchars($n['title']) ?>
            </div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);white-space:nowrap;"><?= date('m/d',strtotime($n['created_at'])) ?></div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);white-space:nowrap;"><?= htmlspecialchars($n['author_name']??'') ?></div>
        </a>
        <?php endforeach; else: ?>
        <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">공지사항 없음</div>
        <?php endif; ?>
        </div>
    </div>
</div>

<!-- ═══ 실적 요약 (관리자: 그룹핑) ═══ -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0.75rem;margin-bottom:1.25rem;">

    <!-- 그룹1: 조직 현황 -->
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--accent-text);font-weight:700;margin-bottom:0.75rem;padding-bottom:0.35rem;border-bottom:1px solid var(--border);">👥 조직 현황</div>
        <div style="">
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">조직 인원</div>
            <div style="font-size:var(--fs-xl);font-weight:800;color:var(--text-primary);"><?= $orgCount ?></div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">명</div>
        </div>
    </div>

    <!-- 그룹2: 성과 지표 (평균) -->
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--accent-text);font-weight:700;margin-bottom:0.75rem;padding-bottom:0.35rem;border-bottom:1px solid var(--border);">📊 성과 지표 (직원 평균)</div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;">
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">평가점수</div>
                <div style="font-size:var(--fs-lg);font-weight:800;color:var(--text-primary);"><?= $adminAvgScore ?></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);">KPI 달성률</div>
                <div style="font-size:var(--fs-lg);font-weight:800;color:<?= $adminAvgAmtRate>=100?'var(--success)':'var(--warning)' ?>;"><?= $adminAvgAmtRate ?>%</div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">매출 기준</div>
            </div>
        </div>
    </div>

    <!-- 그룹3: 계약 성사 (평균) -->
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--accent-text);font-weight:700;margin-bottom:0.75rem;padding-bottom:0.35rem;border-bottom:1px solid var(--border);">📋 계약 성사 (직원 평균)</div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;">
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">연간 평균</div>
                <div style="font-size:var(--fs-lg);font-weight:800;color:var(--text-primary);"><?= $adminAvgContractYear ?></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:800;color:var(--accent-text);"><?= $adminAvgContractMonth ?></div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">건/인</div>
            </div>
        </div>
    </div>

    <!-- 그룹4: KPI 건수 달성률 -->
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--accent-text);font-weight:700;margin-bottom:0.75rem;padding-bottom:0.35rem;border-bottom:1px solid var(--border);">🎯 KPI 건수 (직원 평균)</div>
        <div style="display:grid;grid-template-columns:1fr;gap:0.5rem;">
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">건수 달성률</div>
                <div style="font-size:var(--fs-xl);font-weight:800;color:<?= $adminAvgDealRate>=100?'var(--success)':'var(--warning)' ?>;"><?= $adminAvgDealRate ?>%</div>
            </div>
        </div>
    </div>
</div>

<!-- ═══ 총 인센티브 (관리자) ═══ -->
<div class="card" style="margin-bottom:1.25rem;padding:1rem;">
    <div style="font-size:var(--fs-xs);color:var(--accent-text);font-weight:700;margin-bottom:0.75rem;padding-bottom:0.35rem;border-bottom:1px solid var(--border);">💎 총 인센티브</div>

    <!-- 인센티브 검토 현황 -->
    <div style="background:rgba(var(--accent-rgb),0.06);border-radius:var(--radius-sm);padding:0.75rem;margin-bottom:0.75rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.5rem;">✅ 인센티브 지급 검토 현황</div>
        <?php if ($user['role'] === 'sysadmin'): ?>
        <!-- 시스템관리자: 관리자 + 대표 모두 -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;">
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.35rem;">📋 관리자 검토</div>
                <div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
                    <a href="<?=BASE_URL?>pages/approval.php?review=대기" style="text-decoration:none;"><span class="badge badge-gray" style="font-size:var(--fs-xs);cursor:pointer;">대기 <strong><?= $mgrWait ?></strong></span></a>
                    <a href="<?=BASE_URL?>pages/approval.php?review=확인" style="text-decoration:none;"><span class="badge badge-info" style="font-size:var(--fs-xs);cursor:pointer;">확인 <strong><?= $mgrConfirm ?></strong></span></a>
                    <a href="<?=BASE_URL?>pages/approval.php?review=보류" style="text-decoration:none;"><span class="badge badge-danger" style="font-size:var(--fs-xs);cursor:pointer;">보류 <strong><?= $mgrHold ?></strong></span></a>
                </div>
            </div>
            <div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.35rem;">🏛 대표 승인</div>
                <div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
                    <a href="<?=BASE_URL?>pages/approval.php?approve=대기" style="text-decoration:none;"><span class="badge badge-gray" style="font-size:var(--fs-xs);cursor:pointer;">대기 <strong><?= $ceoWait ?></strong></span></a>
                    <a href="<?=BASE_URL?>pages/approval.php?approve=승인" style="text-decoration:none;"><span class="badge badge-success" style="font-size:var(--fs-xs);cursor:pointer;">승인 <strong><?= $ceoApproved ?></strong></span></a>
                    <a href="<?=BASE_URL?>pages/approval.php?approve=보류" style="text-decoration:none;"><span class="badge badge-danger" style="font-size:var(--fs-xs);cursor:pointer;">보류 <strong><?= $ceoHold ?></strong></span></a>
                </div>
            </div>
        </div>
        <?php elseif ($user['role'] === 'manager'): ?>
        <!-- 관리자: 관리자 검토만 -->
        <div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.35rem;">📋 관리자 검토</div>
            <div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
                <a href="<?=BASE_URL?>pages/approval.php?review=대기" style="text-decoration:none;"><span class="badge badge-gray" style="font-size:var(--fs-xs);cursor:pointer;">대기 <strong><?= $mgrWait ?></strong></span></a>
                <a href="<?=BASE_URL?>pages/approval.php?review=확인" style="text-decoration:none;"><span class="badge badge-info" style="font-size:var(--fs-xs);cursor:pointer;">확인 <strong><?= $mgrConfirm ?></strong></span></a>
                <a href="<?=BASE_URL?>pages/approval.php?review=보류" style="text-decoration:none;"><span class="badge badge-danger" style="font-size:var(--fs-xs);cursor:pointer;">보류 <strong><?= $mgrHold ?></strong></span></a>
            </div>
        </div>
        <?php elseif ($user['role'] === 'ceo'): ?>
        <!-- 대표: 대표 승인만 -->
        <div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.35rem;">🏛 대표 승인</div>
            <div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
                <a href="<?=BASE_URL?>pages/approval.php?approve=대기" style="text-decoration:none;"><span class="badge badge-gray" style="font-size:var(--fs-xs);cursor:pointer;">대기 <strong><?= $ceoWait ?></strong></span></a>
                <a href="<?=BASE_URL?>pages/approval.php?approve=승인" style="text-decoration:none;"><span class="badge badge-success" style="font-size:var(--fs-xs);cursor:pointer;">승인 <strong><?= $ceoApproved ?></strong></span></a>
                <a href="<?=BASE_URL?>pages/approval.php?approve=보류" style="text-decoration:none;"><span class="badge badge-danger" style="font-size:var(--fs-xs);cursor:pointer;">보류 <strong><?= $ceoHold ?></strong></span></a>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
        <!-- 월간 -->
        <div style="background:rgba(var(--accent-rgb),0.04);border-radius:var(--radius-sm);padding:0.75rem;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.5rem;">
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;">📅 월간</div>
                <form method="GET" style="display:inline;">
                    <input type="hidden" name="inc_year" value="<?= $fIncYear ?>">
                    <select name="inc_month" onchange="this.form.submit()" class="dash-filter" style="width:7.5rem;font-size:var(--fs-xs);padding:0.15rem 0.3rem;">
                        <?php foreach ($availIncMonths as $aim): ?>
                        <option value="<?= $aim ?>" <?= $fIncMonth===$aim?'selected':'' ?>><?= $aim ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.5rem;">
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">대상 인원</div>
                    <div style="font-size:var(--fs-lg);font-weight:800;color:var(--accent-text);"><?= (int)($incSummaryMonth['eligible_cnt'] ?? 0) ?><span style="font-size:var(--fs-xs);color:var(--text-tertiary);">명</span></div>
                </div>
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">총 인센티브</div>
                    <div style="font-size:var(--fs-lg);font-weight:800;color:var(--success);"><?= number_format(((int)($incSummaryMonth['total_min']??0)+(int)($incSummaryMonth['total_max']??0))/2/10000) ?><span style="font-size:var(--fs-xs);color:var(--text-tertiary);">만</span></div>
                </div>
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">🔺 최고</div>
                    <div style="font-size:var(--fs-sm);font-weight:700;color:var(--success);"><?= $incTopMonth ? number_format((int)$incTopMonth['incentive_max']/10000).'만' : '-' ?></div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($incTopMonth['name'] ?? '') ?></div>
                </div>
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">🔻 최소</div>
                    <div style="font-size:var(--fs-sm);font-weight:700;color:var(--warning);"><?= $incBottomMonth ? number_format((int)$incBottomMonth['incentive_min']/10000).'만' : '-' ?></div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($incBottomMonth['name'] ?? '') ?></div>
                </div>
            </div>
        </div>
        <!-- 누적 -->
        <div style="background:rgba(var(--accent-rgb),0.04);border-radius:var(--radius-sm);padding:0.75rem;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.5rem;">
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;">📊 누적</div>
                <form method="GET" style="display:inline;">
                    <input type="hidden" name="inc_month" value="<?= $fIncMonth ?>">
                    <select name="inc_year" onchange="this.form.submit()" class="dash-filter" style="width:5.5rem;font-size:var(--fs-xs);padding:0.15rem 0.3rem;">
                        <?php foreach ($incYears as $iy): ?>
                        <option value="<?= $iy ?>" <?= $fIncYear==$iy?'selected':'' ?>><?= $iy ?>년</option>
                        <?php endforeach; ?>
                    </select>
                </form>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.5rem;">
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">대상 인원</div>
                    <div style="font-size:var(--fs-lg);font-weight:800;color:var(--accent-text);"><?= (int)($incSummaryYear['eligible_cnt'] ?? 0) ?><span style="font-size:var(--fs-xs);color:var(--text-tertiary);">명</span></div>
                </div>
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">총 인센티브</div>
                    <div style="font-size:var(--fs-lg);font-weight:800;color:var(--success);"><?= number_format(((int)($incSummaryYear['total_min']??0)+(int)($incSummaryYear['total_max']??0))/2/10000) ?><span style="font-size:var(--fs-xs);color:var(--text-tertiary);">만</span></div>
                </div>
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">🔺 최고</div>
                    <div style="font-size:var(--fs-sm);font-weight:700;color:var(--success);"><?= $incTopYear ? number_format((int)$incTopYear['total']/10000).'만' : '-' ?></div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($incTopYear['name'] ?? '') ?></div>
                </div>
                <div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">🔻 최소</div>
                    <div style="font-size:var(--fs-sm);font-weight:700;color:var(--warning);"><?= $incBottomYear ? number_format((int)$incBottomYear['total']/10000).'만' : '-' ?></div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($incBottomYear['name'] ?? '') ?></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

<?php else: ?>
<!-- ═══ 일반 사용자 홈 레이아웃 ═══ -->
<div style="display:grid;grid-template-columns:5fr 3fr 4fr;gap:1.25rem;margin-bottom:1.25rem;max-height:18rem;overflow:hidden;">

    <!-- 프로필 카드 -->
    <div class="card" style="padding:1.25rem;">
        <div style="display:flex;gap:1.25rem;align-items:stretch;height:100%;">
            <!-- 아바타 + 기본 정보 -->
            <div style="flex:1;">
                <div style="display:flex;align-items:center;gap:0.75rem;margin-bottom:1rem;">
                    <div style="width:5rem;height:5rem;border-radius:50%;overflow:hidden;flex-shrink:0;background:var(--card-bg-color);border:2px solid var(--border);">
                        <?php
                        $photoSrc = BASE_URL.'assets/empty.png';
                        $profileGlob = glob(__DIR__ . '/../assets/theme/' . $user['user_id'] . '/profile.*');
                        if ($profileGlob) { $photoSrc = BASE_URL.'assets/theme/' . $user['user_id'] . '/' . basename($profileGlob[0]); }
                        ?>
                        <img src="<?= $photoSrc ?>" alt="프로필" style="width:100%;height:100%;object-fit:cover;">
                    </div>
                    <div>
                        <div style="font-size:var(--fs-lg);font-weight:700;color:var(--text-primary);"><?= crownName($profile['name'], $_SESSION['user_role']??'') ?></div>
                        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($profile['login_id']) ?> · <?= getRoleLabel($profile['user_role']) ?></div>
                    </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.5rem 1.25rem;font-size:var(--fs-sm);">
                    <div style="grid-column:span 2;font-size:var(--fs-xs);color:var(--accent-text);font-weight:600;padding-top:0.25rem;border-top:1px solid var(--border);">📋 소속</div>
                    <div><span style="color:var(--text-tertiary);">팀</span> <strong style="color:var(--text-primary);margin-left:0.25rem;"><?= htmlspecialchars($profile['team']) ?></strong></div>
                    <div><span style="color:var(--text-tertiary);">직급</span> <strong style="color:var(--text-primary);margin-left:0.25rem;"><?= htmlspecialchars($profile['grade']) ?></strong></div>
                    <div style="grid-column:span 2;font-size:var(--fs-xs);color:var(--accent-text);font-weight:600;padding-top:0.25rem;margin-top:0.25rem;border-top:1px solid var(--border);">📧 연락</div>
                    <div><span style="color:var(--text-tertiary);">이메일</span> <strong style="color:var(--text-primary);margin-left:0.25rem;"><?= htmlspecialchars($profile['email']) ?></strong></div>
                    <div style="grid-column:span 2;font-size:var(--fs-xs);color:var(--accent-text);font-weight:600;padding-top:0.25rem;margin-top:0.25rem;border-top:1px solid var(--border);">📅 근무</div>
                    <div><span style="color:var(--text-tertiary);">입사일</span> <strong style="color:var(--text-primary);margin-left:0.25rem;"><?= $profile['hire_date'] ?></strong></div>
                    <?php /* 사용 연차 삭제됨 */ ?>
                    <div><span style="color:var(--text-tertiary);">최종 로그인</span> <strong style="color:var(--text-primary);margin-left:0.25rem;"><?= $profile['last_login']?date('m/d H:i',strtotime($profile['last_login'])):'-' ?></strong></div>
                </div>
            </div>
            <!-- 슬라이드 (버튼 없이) -->
            <div style="width:16rem;flex-shrink:0;display:flex;flex-direction:column;">
                <?php if ($slides): ?>
                <div class="home-slide-wrap"><div class="home-slide-track" id="slideTrack">
                    <?php foreach($slides as $sf): ?><div class="home-slide-item"><img src="<?=BASE_URL?>assets/theme/<?= $user['user_id'] ?>/slides/<?= htmlspecialchars($sf) ?>" alt=""></div><?php endforeach; ?>
                </div>
                </div>
                <?php else: ?>
                <div style="height:100%;display:flex;align-items:center;justify-content:center;color:var(--text-tertiary);font-size:var(--fs-xs);border:1px dashed var(--form-line-color);border-radius:var(--radius-sm);min-height:7rem;">
                    <a href="<?=BASE_URL?>pages/theme_settings.php" style="color:var(--accent);">🖼️ 이미지 추가</a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- 매출 기여도 차트 (일반 사용자) -->
    <div class="card" style="padding:1rem;display:flex;flex-direction:column;align-items:center;">
        <div style="display:flex;justify-content:space-between;align-items:center;width:100%;margin-bottom:0.5rem;">
            <h3 style="margin:0;font-size:var(--fs-sm);">📊 매출 기여도</h3>
            <span style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $fMonth ?: $curMonth ?></span>
        </div>
        <div style="position:relative;width:180px;height:180px;">
            <canvas id="contribDonut"></canvas>
            <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);">
                <div style="font-size:1.75rem;font-weight:800;color:var(--accent-text);"><?= $myPct ?>%</div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">내 기여도</div>
            </div>
        </div>
        <div style="margin-top:0.75rem;font-size:var(--fs-xs);color:var(--text-tertiary);">
            내 매출 <strong style="color:var(--accent-text);"><?= number_format($myContrib/10000) ?>만</strong>
            / 전체 <?= number_format($contribTotal/10000) ?>만
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function(){
        const ctx = document.getElementById('contribDonut');
        if(!ctx) return;
        new Chart(ctx, {
            type:'doughnut',
            data:{
                labels:['나','기타'],
                datasets:[{data:[<?= $myPct ?>, <?= round(100 - $myPct, 1) ?>],
                    backgroundColor:['#00BCD4','#FF6D00'],
                    borderWidth:0, hoverOffset:4}]
            },
            options:{
                cutout:'72%',
                responsive:true, maintainAspectRatio:true,
                plugins:{legend:{display:false},tooltip:{
                    callbacks:{label:function(c){return c.label+': '+c.parsed+'%';}}
                }}
            }
        });
    });
    </script>

    <!-- 공지사항 (최신 5개, 클릭시 notice.php로 이동) -->
    <div class="card" style="display:flex;flex-direction:column;">
        <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;flex-shrink:0;">
            <h3>📌 공지사항</h3>
            <a href="<?=BASE_URL?>pages/notice.php" style="font-size:var(--fs-xs);color:var(--accent);text-decoration:none;">전체보기 →</a>
        </div>
        <div style="flex:1;overflow-y:auto;">
        <?php if ($notices): foreach($notices as $n): ?>
        <a href="<?=BASE_URL?>pages/notice.php?mode=view&id=<?= $n['notice_id'] ?>" style="padding:0.45rem 0.75rem;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:0.75rem;text-decoration:none;transition:background 0.15s;" onmouseover="this.style.background='rgba(255,255,255,0.03)'" onmouseout="this.style.opacity='1'">
            <div style="flex:1;min-width:0;font-size:var(--fs-sm);font-weight:600;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                <?php if($n['is_pinned']): ?><span style="color:var(--accent);">📌</span> <?php endif; ?><?= htmlspecialchars($n['title']) ?>
            </div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);white-space:nowrap;"><?= date('m/d',strtotime($n['created_at'])) ?></div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);white-space:nowrap;"><?= htmlspecialchars($n['author_name']??'') ?></div>
        </a>
        <?php endforeach; else: ?>
        <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">공지사항 없음</div>
        <?php endif; ?>
        </div>
    </div>
</div>

<!-- ═══ 실적 요약 카드 (일반 사용자) ═══ -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(9rem,1fr));gap:0.75rem;margin-bottom:1.25rem;">
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">오늘 순이익</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:<?= $todayProfit>=0?'var(--success)':'var(--accent)' ?>;"><?= number_format($todayProfit/10000) ?></div>
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">만원</div>
    </div>
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">이번달 매출</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:var(--accent-text);"><?= number_format($my['rev']/10000) ?></div>
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">만원</div>
    </div>
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">이번달 순이익</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:var(--success);"><?= number_format($my['profit']/10000) ?></div>
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">만원</div>
    </div>
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">평가점수</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:var(--text-primary);"><?= $score ? number_format($scoreTotalNum,1) : '-' ?></div>
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $score ? $score['eval_month'] : '' ?></div>
    </div>
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">KPI 달성률</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:<?= $kpiAmtRate>=100?'var(--success)':'var(--warning)' ?>;"><?= $kpiAmtRate ?>%</div>
    </div>
    <div class="card" style="padding:0.75rem;grid-column:span 2;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.5rem;font-weight:600;">📋 계약 성사</div>
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0.5rem;">
            <div><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">연간</div><div style="font-size:var(--fs-lg);font-weight:800;color:var(--text-primary);"><?= $contractYearCnt ?></div></div>
            <div><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">월간</div><div style="font-size:var(--fs-lg);font-weight:800;color:var(--accent-text);"><?= $contractMonthCnt ?></div></div>
            <div><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">주간</div><div style="font-size:var(--fs-lg);font-weight:800;color:var(--success);"><?= $contractWeekCnt ?></div></div>
            <div><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">오늘</div><div style="font-size:var(--fs-lg);font-weight:800;color:var(--warning);"><?= $contractDayCnt ?></div></div>
        </div>
    </div>
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">승인 대기</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:var(--warning);"><?= $pendingApproval ?></div>
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">건</div>
    </div>
    <?php if ($pendingUsers > 0): ?>
    <a href="<?=BASE_URL?>pages/admin_accounts.php" style="text-decoration:none;">
    <div class="card" style="padding:1rem;border:1px solid rgba(255,152,0,0.3);animation:pulse 2s infinite;">
        <div style="font-size:var(--fs-xs);color:var(--warning);">📋 가입 대기</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:var(--warning);"><?= $pendingUsers ?></div>
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">명 승인 필요</div>
    </div>
    </a>
    <style>@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.7}}</style>
    <?php endif; ?>
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">인센티브 (예상)</div>
        <div style="font-size:var(--fs-xl);font-weight:800;color:var(--accent-text);">
            <?= $myInc ? number_format($myInc['incentive_min']/10000).'~'.number_format($myInc['incentive_max']/10000) : '0' ?>
        </div>
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">만원</div>
    </div>
</div>
<?php endif; ?>

<!-- ═══ 하단: 인센티브 현황 + 최근 활동 ═══ -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;">

    <!-- 인센티브 현황 (연간 월별) -->
    <div class="card">
        <div class="card-header" style="flex-wrap:wrap;gap:0.5rem;">
            <h3>💎 인센티브 현황</h3>
            <form method="GET" style="display:flex;gap:0.5rem;align-items:center;">
                <select name="inc_year" onchange="this.form.submit()" class="dash-filter" style="width:6rem;font-size:var(--fs-xs);">
                    <?php foreach ($incYears as $iy): ?><option value="<?= $iy ?>" <?= $fIncYear==$iy?'selected':'' ?>><?= $iy ?>년</option><?php endforeach; ?>
                </select>
                <input type="hidden" name="inc_month" value="<?= $fIncMonth ?>">
                <select name="inc_month" onchange="this.form.submit()" class="dash-filter" style="width:7.5rem;font-size:var(--fs-xs);">
                    <option value="">전체</option>
                    <?php foreach ($availIncMonths ?? [] as $aim): ?>
                    <option value="<?= $aim ?>" <?= ($_GET['inc_month']??'')===$aim?'selected':'' ?>><?= $aim ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>
        <?php if ($incMonthlyData): ?>
        <div style="overflow-x:auto;">
        <table class="data-table">
            <?php if (in_array($user['role'], ['ceo','sysadmin']) && !$isTeamLeaderDB): ?>
            <!-- 대표/시스템관리자: 년월, 이름, 성사건수, 순이익, 예상금액, 대상, 확정여부 -->
            <thead><tr><th>년월</th><th>이름</th><th style="">성사</th><th style="">매출/목표</th><th style="">순이익</th><th style="">예상금액</th><th style="">대상</th><th style="">확정</th></tr></thead>
            <tbody>
            <?php foreach(array_slice($incMonthlyData, 0, 10) as $im):
                $approved = (($im['approve_status']??'') === '승인');
                $confirmedAmt = $im['final_amount'] ?? null;
                $imTd = (int)($im['target_deals'] ?: $incMinDeals);
                $imTa = $policyProfitTarget;
                $imDealMet = ($im['deals'] ?? 0) >= $imTd;
                $imAmtMet = $imTa > 0 && ($im['total_revenue'] ?? 0) >= $imTa;
                $imEligible = ($im['eligible'] ?? 'N') === 'Y';
                $imIncMin = (int)($im['incentive_min'] ?? 0);
                $imIncMax = (int)($im['incentive_max'] ?? 0);
                if ($imIncMin == 0 && ($im['profit']??0) > 0) {
                    $rt = function_exists('getIncRate') ? getIncRate($db, $im['grade']??'') : null;
                    if($rt){$imIncMin=round($im['profit']*$rt['min_rate']);$imIncMax=round($im['profit']*$rt['max_rate']);}
                }
            ?>
            <tr>
                <td style="font-size:var(--fs-xs);"><?= $im['sale_month'] ?></td>
                <td><strong><?= htmlspecialchars($im['name']) ?></strong></td>
                <td style="font-size:var(--fs-xs);text-align:center;">
                    <strong><?= $im['deals'] ?></strong><span style="color:var(--text-tertiary);">/ <?= $imTd ?></span>
                    <?php if($imDealMet):?>✅<?php endif;?>
                    <div style="font-size:0.6rem;color:var(--text-tertiary);">최소 <?= $incMinDeals ?>건</div>
                </td>
                <td style="font-size:var(--fs-xs);text-align:center;">
                    <span class="font-mono"><?= number_format(($im['total_revenue']??0)/10000) ?></span>만
                    <?php if($policyProfitTarget > 0): ?><div style="font-size:0.6rem;color:var(--text-tertiary);">목표 <?= number_format($policyProfitTarget/10000) ?>만</div><?php endif; ?>
                </td>
                <td style="" class="font-mono"><?= number_format(($im['profit']??0)/10000) ?>만</td>
                <td style="color:var(--accent-text);font-size:var(--fs-xs);">
                    <?php if ($confirmedAmt): ?><strong><?= number_format($confirmedAmt/10000) ?>만</strong>
                    <?php else: ?><?= number_format($imIncMin/10000) ?>~<?= number_format($imIncMax/10000) ?>만<?php endif; ?>
                </td>
                <td style=""><?= $imEligible ? '<span class="badge badge-success" style="font-size:var(--fs-xs);">대상</span>' : '<span class="badge badge-danger" style="font-size:var(--fs-xs);">제외</span>' ?></td>
                <td style="">
                    <?php if ($approved): ?><span class="badge badge-success">확정</span>
                    <?php elseif (($im['approve_status']??'') === '보류' || ($im['review_status']??'') === '보류'): ?><span class="badge badge-warning">보류</span>
                    <?php else: ?><span class="badge <?= ($im['review_status']??'')==='확인'?'badge-info':'badge-gray' ?>"><?php if(($im['review_status']??'')==='확인'): ?>관리자 확인<?php elseif(($im['approve_status']??'')==='대기' && ($im['review_status']??'')==='대기'): ?>대기<?php else: ?><?= htmlspecialchars($im['review_status']??'대기') ?><?php endif; ?></span><?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>

            <?php elseif ($user['role'] === 'manager' && !$isTeamLeaderDB): ?>
            <thead><tr><th>년월</th><th>이름</th><th style="">성사</th><th style="">매출/목표</th><th style="">순이익</th><th style="">예상금액</th><th style="">대상</th><th style="">확정</th></tr></thead>
            <tbody>
            <?php foreach(array_slice($incMonthlyData, 0, 10) as $im):
                $approved = (($im['approve_status']??'') === '승인');
                $confirmedAmt = $im['final_amount'] ?? null;
                $imTd = (int)($im['target_deals'] ?: $incMinDeals); $imTa = $policyProfitTarget;
                $imDealMet = ($im['deals'] ?? 0) >= $imTd; $imAmtMet = $imTa > 0 && ($im['total_revenue'] ?? 0) >= $imTa;
                $imEligible = ($im['eligible'] ?? 'N') === 'Y';
                $imIncMin = (int)($im['incentive_min'] ?? 0); $imIncMax = (int)($im['incentive_max'] ?? 0);
                if ($imIncMin == 0 && ($im['profit']??0) > 0) {
                    $rt = function_exists('getIncRate') ? getIncRate($db, $im['grade']??'') : null;
                    if($rt){$imIncMin=round($im['profit']*$rt['min_rate']);$imIncMax=round($im['profit']*$rt['max_rate']);}
                }
            ?>
            <tr<?= $im['staff_id']==$user['staff_id']?' style="background:rgba(var(--accent-rgb),0.06);"':'' ?>>
                <td style="font-size:var(--fs-xs);"><?= $im['sale_month'] ?></td>
                <td><strong><?= htmlspecialchars($im['name']) ?></strong></td>
                <td style="font-size:var(--fs-xs);text-align:center;"><strong><?= $im['deals'] ?></strong><span style="color:var(--text-tertiary);">/ <?= $imTd ?></span><?php if($imDealMet):?>✅<?php endif;?><div style="font-size:0.6rem;color:var(--text-tertiary);">최소 <?= $incMinDeals ?>건</div></td>
                <td style="font-size:var(--fs-xs);text-align:center;" class="font-mono"><?= number_format(($im['total_revenue']??0)/10000) ?>만<?php if($policyProfitTarget > 0): ?><div style="font-size:0.6rem;color:var(--text-tertiary);">목표 <?= number_format($policyProfitTarget/10000) ?>만</div><?php endif; ?></td>
                <td style="" class="font-mono"><?= number_format(($im['profit']??0)/10000) ?>만</td>
                <td style="color:var(--accent-text);font-size:var(--fs-xs);">
                    <?php if ($confirmedAmt): ?><strong><?= number_format($confirmedAmt/10000) ?>만</strong>
                    <?php else: ?><?= number_format($imIncMin/10000) ?>~<?= number_format($imIncMax/10000) ?>만<?php endif; ?>
                </td>
                <td style=""><?= $imEligible ? '<span class="badge badge-success" style="font-size:var(--fs-xs);">대상</span>' : '<span class="badge badge-danger" style="font-size:var(--fs-xs);">제외</span>' ?></td>
                <td style="">
                    <?php if ($approved): ?><span class="badge badge-success">확정</span>
                    <?php elseif (($im['approve_status']??'') === '보류' || ($im['review_status']??'') === '보류'): ?><span class="badge badge-warning">보류</span>
                    <?php else: ?><span class="badge <?= ($im['review_status']??'')==='확인'?'badge-info':'badge-gray' ?>"><?php if(($im['review_status']??'')==='확인'): ?>관리자 확인<?php elseif(($im['approve_status']??'')==='대기' && ($im['review_status']??'')==='대기'): ?>대기<?php else: ?><?= htmlspecialchars($im['review_status']??'대기') ?><?php endif; ?></span><?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>

            <?php else: ?>
            <!-- 일반 사용자 -->
            <thead><tr><th>년월</th><th style="">성사</th><th style="">매출/목표</th><th style="">순이익</th><th style="">예상금액</th><th style="">대상</th><th style="">확정</th></tr></thead>
            <tbody>
            <?php foreach(array_slice($incMonthlyData, 0, 10) as $im):
                $approved = (($im['approve_status']??'') === '승인');
                $confirmedAmt = $im['final_amount'] ?? null;
                $imTd = (int)($im['target_deals'] ?: $incMinDeals); $imTa = $policyProfitTarget;
                $imDealMet = ($im['deals'] ?? 0) >= $imTd; $imAmtMet = $imTa > 0 && ($im['total_revenue'] ?? 0) >= $imTa;
                $imEligible = ($im['eligible'] ?? 'N') === 'Y';
                $imIncMin = (int)($im['incentive_min'] ?? 0); $imIncMax = (int)($im['incentive_max'] ?? 0);
                if ($imIncMin == 0 && ($im['profit']??0) > 0) {
                    $rt = function_exists('getIncRate') ? getIncRate($db, $im['grade']??'') : null;
                    if($rt){$imIncMin=round($im['profit']*$rt['min_rate']);$imIncMax=round($im['profit']*$rt['max_rate']);}
                }
            ?>
            <tr>
                <td><strong><?= $im['sale_month'] ?></strong></td>
                <td style="font-size:var(--fs-xs);text-align:center;"><strong><?= $im['deals'] ?></strong><span style="color:var(--text-tertiary);">/ <?= $imTd ?></span><?php if($imDealMet):?>✅<?php endif;?><div style="font-size:0.6rem;color:var(--text-tertiary);">최소 <?= $incMinDeals ?>건</div></td>
                <td style="font-size:var(--fs-xs);text-align:center;" class="font-mono"><?= number_format(($im['total_revenue']??0)/10000) ?>만<?php if($policyProfitTarget > 0): ?><div style="font-size:0.6rem;color:var(--text-tertiary);">목표 <?= number_format($policyProfitTarget/10000) ?>만</div><?php endif; ?></td>
                <td style="" class="font-mono"><?= number_format(($im['profit']??0)/10000) ?>만</td>
                <td style="color:var(--accent-text);font-size:var(--fs-xs);">
                    <?php if ($confirmedAmt): ?><strong><?= number_format($confirmedAmt/10000) ?>만</strong>
                    <?php else: ?><?= number_format($imIncMin/10000) ?>~<?= number_format($imIncMax/10000) ?>만<?php endif; ?>
                </td>
                <td style=""><?= $imEligible ? '<span class="badge badge-success" style="font-size:var(--fs-xs);">대상</span>' : '<span class="badge badge-danger" style="font-size:var(--fs-xs);">제외</span>' ?></td>
                <td style="">
                    <?php if ($approved): ?><span class="badge badge-success">확정</span>
                    <?php elseif (($im['approve_status']??'') === '보류' || ($im['review_status']??'') === '보류'): ?><span class="badge badge-warning">보류</span>
                    <?php else: ?><span class="badge <?= ($im['review_status']??'')==='확인'?'badge-info':'badge-gray' ?>"><?php if(($im['review_status']??'')==='확인'): ?>관리자 확인<?php elseif(($im['approve_status']??'')==='대기' && ($im['review_status']??'')==='대기'): ?>대기<?php else: ?><?= htmlspecialchars($im['review_status']??'대기') ?><?php endif; ?></span><?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
            <?php endif; ?>
        </table>
        </div>
        <div style="padding:0.5rem;display:flex;justify-content:center;"><a href="<?=BASE_URL?>pages/incentive.php" title="더보기" style="display:inline-flex;align-items:center;justify-content:center;width:2.5rem;height:2.5rem;border-radius:50%;border:none;background:var(--accent);color:var(--bg-color);text-decoration:none;font-weight:400;transition:background 0.2s;" onmouseover="this.style.opacity='0.8'" onmouseout="this.style.opacity='1'"><span style="font-size:1.6rem;line-height:1;display:flex;align-items:center;justify-content:center;width:100%;height:100%;padding:0;">+</span></a></div>
        <?php else: ?>
        <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">인센티브 데이터 없음</div>
        <?php endif; ?>
    </div>

    <!-- 내 최근 활동 -->
    <div class="card">
        <div class="card-header"><h3><?= $isAdmin ? '📋 최근 활동' : '📋 내 최근 활동' ?></h3></div>
        <?php if ($recentActivity): ?>
        <table class="data-table">
            <thead><tr><th>구분</th><th>내용</th><th>상태</th><th>시간</th></tr></thead>
            <tbody>
            <?php foreach(array_slice($recentActivity, 0, 10) as $act): ?>
            <tr>
                <td><span class="badge <?= $act['type']==='매출'?'badge-info':'badge-warning' ?>" style="font-size:var(--fs-xs);"><?= $act['type'] ?></span></td>
                <td style="font-size:var(--fs-xs);max-width:10rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= htmlspecialchars($act['detail']??'-') ?></td>
                <td><span class="badge badge-gray" style="font-size:var(--fs-xs);"><?= htmlspecialchars($act['status']??'-') ?></span></td>
                <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $act['updated_at']?date('m/d H:i',strtotime($act['updated_at'])):'-' ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <div style="padding:0.5rem;display:flex;justify-content:center;"><a href="<?=BASE_URL?>pages/sales.php" title="더보기" style="display:inline-flex;align-items:center;justify-content:center;width:2.5rem;height:2.5rem;border-radius:50%;border:none;background:var(--accent);color:var(--bg-color);text-decoration:none;font-weight:400;transition:background 0.2s;" onmouseover="this.style.opacity='0.8'" onmouseout="this.style.opacity='1'"><span style="font-size:1.6rem;line-height:1;display:flex;align-items:center;justify-content:center;width:100%;height:100%;padding:0;">+</span></a></div>
        <?php else: ?>
        <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">최근 활동이 없습니다</div>
        <?php endif; ?>
    </div>
</div>


<style>
.home-slide-wrap{position:relative;border-radius:var(--radius-sm);overflow:hidden;flex:1;min-height:7rem;}
.home-slide-track{display:flex;transition:transform 0.5s ease;height:100%;}
.home-slide-item{min-width:100%;height:100%;}
.home-slide-item img{width:100%;height:100%;object-fit:cover;}
</style>
<script>
(function(){var idx=0;var track=document.getElementById('slideTrack');
if(!track)return;var items=track.children.length;if(items<=1)return;
setInterval(function(){idx=(idx+1)%items;track.style.transform='translateX(-'+idx*100+'%)';},5000);})();
</script>
<?php if ($showLoginPopup): ?>
<div id="loginPopup" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);z-index:9999;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);" onclick="this.style.display='none'">
    <div style="padding:2.5rem 3rem;background:var(--glass-card-bg);border-radius:var(--radius);backdrop-filter:blur(20px);border:1px solid var(--border);">
        <div style="font-size:1.5rem;font-weight:700;color:var(--text-primary);margin-bottom:0.5rem;"><?= $greetLine1 ?></div>
        <div style="font-size:var(--fs-sm);color:var(--text-secondary);"><?= $greetLine2 ?></div>
        <div style="margin-top:1.25rem;font-size:var(--fs-xs);color:var(--text-tertiary);">클릭하여 닫기</div>
    </div>
</div>
<script>setTimeout(()=>{const p=document.getElementById('loginPopup');if(p)p.style.display='none';},5000);</script>
<?php endif; ?>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
