<?php
// pages/incentive.php — 인센티브 산출 (검토 상태 관리 포함)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
requireLogin();
$db = (new Database())->getConnection();
$user = currentUser();

// 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) {}
}
// ── POST: 상태 변경 (header 출력 전) ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $targetStaffId = (int)($_POST['target_staff_id'] ?? 0);
    $targetMonth = $_POST['target_month'] ?? '';
    $newStatus = $_POST['new_status'] ?? '';
    $memo = trim($_POST['memo'] ?? '');

    if ($action === 'change_status' && $targetStaffId && $targetMonth && $newStatus) {
        $allowed = false;
        if (in_array($newStatus, ['대표승인','확정'])) {
            if (in_array($user['role'], ['ceo','sysadmin'])) $allowed = true;
        } else {
            if (in_array($user['role'], ['ceo','sysadmin'])) $allowed = true;
            elseif ($targetStaffId == $user['staff_id']) $allowed = true;
        }

        $msg = '권한이 없습니다.';
        if ($allowed) {
            $db->exec("CREATE TABLE IF NOT EXISTS incentive_review (review_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT NOT NULL, sale_month VARCHAR(7) NOT NULL, review_status ENUM('대기','검토중','승인요청','대표승인','반려','확정') DEFAULT '대기', review_memo VARCHAR(300) DEFAULT '', reviewed_by INT DEFAULT NULL, ceo_approved_by INT DEFAULT NULL, ceo_memo VARCHAR(300) DEFAULT '', updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uk_staff_month(staff_id, sale_month))");
            $db->exec("CREATE TABLE IF NOT EXISTS incentive_review_log (log_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT NOT NULL, sale_month VARCHAR(7) NOT NULL, old_status VARCHAR(20), new_status VARCHAR(20), memo VARCHAR(300) DEFAULT '', changed_by INT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");

            $oldRow = $db->prepare("SELECT review_status FROM incentive_review WHERE staff_id=? AND sale_month=?");
            $oldRow->execute([$targetStaffId, $targetMonth]);
            $oldStatus = $oldRow->fetchColumn() ?: '대기';

            $db->prepare("INSERT INTO incentive_review (staff_id, sale_month, review_status, review_memo, reviewed_by) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE review_status=VALUES(review_status), review_memo=VALUES(review_memo), reviewed_by=VALUES(reviewed_by)")
               ->execute([$targetStaffId, $targetMonth, $newStatus, $memo, $user['staff_id']]);

            if (in_array($newStatus, ['대표승인','확정'])) {
                $db->prepare("UPDATE incentive_review SET ceo_approved_by=?, ceo_memo=? WHERE staff_id=? AND sale_month=?")
                   ->execute([$user['staff_id'], $memo, $targetStaffId, $targetMonth]);
            }

            $db->prepare("INSERT INTO incentive_review_log (staff_id, sale_month, old_status, new_status, memo, changed_by) VALUES(?,?,?,?,?,?)")
               ->execute([$targetStaffId, $targetMonth, $oldStatus, $newStatus, $memo, $user['staff_id']]);

            $msg = "상태가 '{$newStatus}'(으)로 변경되었습니다.";
        }
        header("Location: ".BASE_URL."pages/incentive.php?month={$targetMonth}&msg=" . urlencode($msg));
        exit;
    }
}

// ── header 로드 ──
require_once __DIR__ . '/../includes/header.php';
$perm = getMenuPerm($db, 'incentive', $user['role']);
if (in_array($user['role'], ['sysadmin','ceo','manager'])) { $perm['view_scope'] = 'all'; }
$message = $_GET['msg'] ?? '';

$db->exec("CREATE TABLE IF NOT EXISTS incentive_review (review_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT NOT NULL, sale_month VARCHAR(7) NOT NULL, review_status ENUM('대기','검토중','승인요청','대표승인','반려','확정') DEFAULT '대기', review_memo VARCHAR(300) DEFAULT '', reviewed_by INT DEFAULT NULL, ceo_approved_by INT DEFAULT NULL, ceo_memo VARCHAR(300) DEFAULT '', updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uk_staff_month(staff_id, sale_month))");

$policyMap = $db->query("SELECT rule_key, rule_value FROM policy_rule WHERE rule_key IN ('incentive_min_deals','deal_target_monthly','revenue_target_monthly','profit_target_monthly')")->fetchAll(PDO::FETCH_KEY_PAIR);
$minDeals = (int)str_replace(',', '', $policyMap['incentive_min_deals'] ?? '3');

// v_profit_by_person VIEW 재생성 (월 기준: contract_date 월, 없으면 NULL)
$db->exec("DROP VIEW IF EXISTS v_profit_by_person");
$db->exec("CREATE VIEW v_profit_by_person AS SELECT s.staff_id,st.name,st.grade,st.team,DATE_FORMAT(s.contract_date,'%Y-%m') AS sale_month,COUNT(*) AS deal_count,SUM(s.revenue) AS total_revenue,SUM(s.cost) AS total_cost,SUM(s.net_profit) AS total_net_profit,CASE WHEN COUNT(*)>0 THEN ROUND(SUM(s.revenue)/COUNT(*)) ELSE 0 END AS avg_deal_price FROM sales s JOIN staff st ON s.staff_id=st.staff_id WHERE s.stage IN('계약','촬영','방송완료') GROUP BY s.staff_id,st.name,st.grade,st.team,DATE_FORMAT(s.contract_date,'%Y-%m')");

$db->exec("DROP VIEW IF EXISTS v_incentive_calc");
$db->exec("CREATE VIEW v_incentive_calc AS
    SELECT p.staff_id, p.name, p.grade, p.team, p.sale_month,
        p.deal_count, p.total_revenue, p.total_net_profit,
        IFNULL(CAST(pr_d.rule_value AS SIGNED), 10) AS target_deals,
        IFNULL(CAST(REPLACE(pr_a.rule_value,',','') AS SIGNED), 0) AS target_amount,
        CASE WHEN COALESCE(ir.is_active,1)=1 AND p.total_net_profit > 0
             AND p.deal_count >= IFNULL(CAST(REPLACE(pr_min.rule_value,',','') AS SIGNED), 3)
             THEN 'Y' ELSE 'N' END AS eligible,
        CASE WHEN COALESCE(ir.is_active,1)=1 AND p.total_net_profit > 0
             THEN ROUND(p.total_net_profit * COALESCE(ir.min_rate,0)) ELSE 0 END AS incentive_min,
        CASE WHEN COALESCE(ir.is_active,1)=1 AND p.total_net_profit > 0
             THEN ROUND(p.total_net_profit * COALESCE(ir.max_rate,0)) ELSE 0 END AS incentive_max,
        COALESCE(ir.min_rate,0) AS min_rate, COALESCE(ir.max_rate,0) AS max_rate, ir.basis AS rate_basis,
        COALESCE(ir.is_active,1) AS grade_incentive_active
    FROM v_profit_by_person p
    LEFT JOIN incentive_rate ir ON p.grade = ir.grade
    LEFT JOIN policy_rule pr_d ON pr_d.rule_key = 'deal_target_monthly'
    LEFT JOIN policy_rule pr_a ON pr_a.rule_key = 'profit_target_monthly'
    LEFT JOIN policy_rule pr_min ON pr_min.rule_key = 'incentive_min_deals'");

// ── 필터 ──
$filterMonth = $_GET['month'] ?? '';
$fYear = $_GET['year'] ?? date('Y');
$filterGrade = $_GET['grade'] ?? '';
$filterStaff = $_GET['staff_id'] ?? '';
$filterTeam = $_GET['team'] ?? '';
$filterEligible = $_GET['eligible'] ?? '';
$filterReviewSt = $_GET['review_st'] ?? '';

$incYears = $db->query("SELECT DISTINCT LEFT(sale_month,4) FROM v_profit_by_person WHERE sale_month IS NOT NULL ORDER BY 1 DESC")->fetchAll(PDO::FETCH_COLUMN);
if (!$incYears) $incYears = [date('Y')];
$months = $db->query("SELECT DISTINCT sale_month FROM v_profit_by_person WHERE sale_month IS NOT NULL ORDER BY sale_month DESC")->fetchAll(PDO::FETCH_COLUMN);
$grades = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 AND grade_name NOT IN('대표') ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
$teamList = $db->query("SELECT team_name FROM team_master WHERE is_active=1 AND team_name NOT IN('경영진','경영지원','오너','시스템') ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
$staffOpts = $db->query("SELECT s.staff_id, s.name FROM staff s LEFT JOIN user_account ua ON s.staff_id=ua.staff_id WHERE s.is_active=1 AND (ua.user_role IS NULL OR ua.user_role NOT IN('ceo','sysadmin','manager')) ORDER BY s.name")->fetchAll();

$sql = "SELECT ic.*, COALESCE(ir.review_status, '대기') AS review_st, ir.review_memo, ir.reviewed_by, ir.ceo_approved_by, ir.ceo_memo, ir.updated_at AS review_updated
    FROM v_incentive_calc ic
    LEFT JOIN incentive_review ir ON ic.staff_id=ir.staff_id AND ic.sale_month=ir.sale_month
    LEFT JOIN incentive_rate ir2 ON ic.grade=ir2.grade
    WHERE (LEFT(ic.sale_month,4) = ? OR ic.sale_month IS NULL) AND COALESCE(ir2.is_active,1) = 1";
$params = [$fYear];
if ($filterMonth) { $sql .= " AND ic.sale_month = ?"; $params[] = $filterMonth; }
if ($filterGrade) { $sql .= " AND ic.grade = ?"; $params[] = $filterGrade; }
if ($filterStaff) { $sql .= " AND ic.staff_id = ?"; $params[] = $filterStaff; }
if ($filterTeam) { $sql .= " AND ic.team = ?"; $params[] = $filterTeam; }
if ($filterEligible) { $sql .= " AND ic.eligible = ?"; $params[] = $filterEligible; }
if ($filterReviewSt) { $sql .= " AND COALESCE(ir.review_status, '대기') = ?"; $params[] = $filterReviewSt; }
if ($perm['view_scope'] === 'own') { $sql .= " AND ic.staff_id = ?"; $params[] = $user['staff_id']; }
elseif ($perm['view_scope'] === 'team') { $myT=$db->prepare("SELECT team FROM staff WHERE staff_id=?"); $myT->execute([$user['staff_id']]); $tm=$myT->fetchColumn(); if($tm){$sql.=" AND ic.team=?";$params[]=$tm;} }
$sql .= " ORDER BY ic.sale_month DESC, ic.total_net_profit DESC";
$stmt = $db->prepare($sql); $stmt->execute($params);
$allIncentives = $stmt->fetchAll();

// 페이지네이션
$totalCnt = count($allIncentives);
$perPage = 20; $page = max(1,(int)($_GET['page']??1));
$totalPages = max(1, ceil($totalCnt / $perPage));
$incentives = array_slice($allIncentives, ($page-1)*$perPage, $perPage);

// 리뷰어 이름 캐시
$reviewerNames = [];
$allReviewerIds = array_unique(array_filter(array_merge(array_column($allIncentives, 'reviewed_by'), array_column($allIncentives, 'ceo_approved_by'))));
if ($allReviewerIds) {
    $inPh = implode(',', array_fill(0, count($allReviewerIds), '?'));
    $rn = $db->prepare("SELECT staff_id, name FROM staff WHERE staff_id IN ($inPh)");
    $rn->execute(array_values($allReviewerIds));
    foreach ($rn->fetchAll() as $r) $reviewerNames[$r['staff_id']] = $r['name'];
}

function reviewBadge($status) {
    $map = ['대기'=>'badge-gray','검토중'=>'badge-info','승인요청'=>'badge-warning','대표승인'=>'badge-success','반려'=>'badge-danger','확정'=>'badge-success'];
    $icons = ['대기'=>'⏳','검토중'=>'🔍','승인요청'=>'📤','대표승인'=>'✅','반려'=>'❌','확정'=>'🎉'];
    return '<span class="badge '.($map[$status]??'badge-gray').'">'.($icons[$status]??'📋').' '.$status.'</span>';
}
?>

<div class="page-header">
    <h2>💎 인센티브 산출</h2>
    <div class="breadcrumb">INCENTIVE_ENGINE · 검토 범위 자동 산출</div>
</div>

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

<div class="alert alert-warning">
    ⚠ 인센티브는 <strong>"확정 지급"이 아닌 "검토 대상/범위 산출"</strong>입니다.
    대표/시스템관리자 최종 승인 전까지 확정되지 않습니다.
</div>

<!-- 직급별 인센티브 산출 비율표 (위로 배치) -->
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3>📋 직급별 인센티브 산출 비율표</h3></div>
    <div class="table-wrap"><table>
        <thead><tr><th>직급</th><th>상태</th><th>최소 비율</th><th>최대 비율</th><th>산출 기준</th><th>비고</th></tr></thead>
        <tbody>
        <?php
        $gmRateList = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 AND TRIM(grade_name)!='' ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
        $irRateMap = []; try { foreach($db->query("SELECT * FROM incentive_rate")->fetchAll() as $ir) { $irRateMap[$ir['grade']]=$ir; } } catch(Exception $e){}
        foreach ($gmRateList as $gn): $r = $irRateMap[$gn] ?? null; $gradeActive = $r ? (int)($r['is_active'] ?? 1) : 1; ?>
        <tr style="<?= !$gradeActive ? 'opacity:0.4;' : '' ?>">
            <td><span class="badge <?= $gradeActive ? 'badge-info' : 'badge-gray' ?>"><?= htmlspecialchars($gn) ?></span></td>
            <td><?= $gradeActive ? '<span class="badge badge-success">활성</span>' : '<span class="badge badge-gray">비활성</span>' ?></td>
            <td><?= $r ? round($r['min_rate']*100,1) : 3 ?>%</td><td><?= $r ? round($r['max_rate']*100,1) : 8 ?>%</td>
            <td><?= htmlspecialchars($r['basis'] ?? '순이익 기준') ?></td>
            <td class="text-left"><?= htmlspecialchars($r['memo'] ?? '') ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table></div>
</div>

<!-- 필터 -->
<div class="card" style="margin-bottom:1rem;padding:0.75rem 1rem;">
    <form method="GET" style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
        <select name="year" onchange="this.form.submit()" class="dash-filter" style="width:7rem;">
            <?php foreach($incYears as $y): ?><option value="<?= $y ?>" <?= $fYear==$y?'selected':'' ?>><?= $y ?>년</option><?php endforeach; ?>
        </select>
        <select name="month" onchange="this.form.submit()" class="dash-filter" style="width:9rem;">
            <option value="">월 전체</option>
            <?php foreach ($months as $m): ?><option value="<?= $m ?>" <?= $filterMonth===$m?'selected':'' ?>><?= $m ?></option><?php endforeach; ?>
        </select>
        <select name="grade" onchange="this.form.submit()" class="dash-filter" style="width:7rem;">
            <option value="">직급 전체</option>
            <?php foreach($grades as $g): ?><option value="<?= $g ?>" <?= $filterGrade===$g?'selected':'' ?>><?= $g ?></option><?php endforeach; ?>
        </select>
        <select name="team" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">팀 전체</option>
            <?php foreach($teamList as $t): ?><option value="<?= $t ?>" <?= $filterTeam===$t?'selected':'' ?>><?= htmlspecialchars($t) ?></option><?php endforeach; ?>
        </select>
        <select name="staff_id" onchange="this.form.submit()" class="dash-filter" style="width:9rem;">
            <option value="">담당자 전체</option>
            <?php foreach($staffOpts as $s): ?><option value="<?= $s['staff_id'] ?>" <?= $filterStaff==$s['staff_id']?'selected':'' ?>><?= htmlspecialchars($s['name']) ?></option><?php endforeach; ?>
        </select>
        <select name="eligible" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">검토 대상 전체</option>
            <option value="Y" <?= $filterEligible==='Y'?'selected':'' ?>>✅ 대상</option>
            <option value="N" <?= $filterEligible==='N'?'selected':'' ?>>❌ 제외</option>
        </select>
        <select name="review_st" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">검토 상태 전체</option>
            <?php foreach(['대기','검토중','승인요청','대표승인','반려','확정'] as $rs): ?>
            <option value="<?= $rs ?>" <?= $filterReviewSt===$rs?'selected':'' ?>><?= $rs ?></option>
            <?php endforeach; ?>
        </select>
    </form>
</div>

<!-- 인센티브 산출 현황 -->
<div class="card">
    <div class="card-header"><h3>인센티브 산출 현황 (<?= $totalCnt ?>건)</h3></div>
    <div class="table-wrap"><table>
        <thead><tr>
            <th>이름</th><th>직급</th><th>팀</th><th>월</th>
            <th>성사/목표</th><th>매출/목표</th><th>순이익</th>
            <th>검토 대상</th><th>최소</th><th>최대</th>
            <th>검토 상태</th><th>산출 기준</th><th>상태 변경</th>
        </tr></thead>
        <tbody>
        <?php foreach ($incentives as $inc):
            $reviewSt = $inc['review_st'] ?? '대기';
            $isOwn = ($inc['staff_id'] == $user['staff_id']);
            $canChange = in_array($user['role'], ['ceo','sysadmin']) || $isOwn;
            $td = (int)($inc['target_deals'] ?? 3);
            $ta = (int)($inc['target_amount'] ?? 0);
            $dealMet = $inc['deal_count'] >= $td;
            $amtMet = $ta > 0 && ($inc['total_revenue'] ?? 0) >= $ta;
        ?>
        <tr style="<?= $isOwn ? 'background:rgba(var(--accent-rgb),0.04);' : '' ?>">
            <td><strong><?= htmlspecialchars($inc['name']) ?></strong></td>
            <td><span class="badge badge-info"><?= $inc['grade'] ?></span></td>
            <td><?= htmlspecialchars($inc['team']) ?></td>
            <td><?= $inc['sale_month'] ?: '<span style="color:var(--text-tertiary);">-</span>' ?></td>
            <td style="text-align:center;">
                <strong style="color:<?= $dealMet?'var(--success)':'inherit' ?>;"><?= $inc['deal_count'] ?></strong>
                <span style="color:var(--text-tertiary);font-size:var(--fs-xs);">/ <?= $td ?>건</span>
                <?php if ($dealMet): ?><span style="font-size:var(--fs-xs);">✅</span><?php endif; ?>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">최소 <?= $minDeals ?>건</div>
            </td>
            <td class="text-right" style="font-size:var(--fs-xs);">
                <span class="font-mono" style="color:<?= $amtMet?'var(--success)':'inherit' ?>;"><?= number_format($inc['total_revenue'] ?? 0) ?></span>
                <?php if ($ta > 0): ?>
                <div style="color:var(--text-tertiary);font-size:var(--fs-xs);">목표 <?= number_format($ta/10000) ?>만 <?php if ($amtMet): ?>✅<?php endif; ?></div>
                <?php endif; ?>
            </td>
            <td class="text-right font-mono"><?= number_format($inc['total_net_profit']) ?></td>
            <td><?= ($inc['eligible']??'N')==='Y' ? '<span class="badge badge-success">✅ 대상</span>' : '<span class="badge badge-danger">❌ 제외</span>' ?></td>
            <td class="text-right font-mono"><?= $inc['incentive_min'] > 0 ? number_format($inc['incentive_min']) : '-' ?></td>
            <td class="text-right font-mono"><?= $inc['incentive_max'] > 0 ? number_format($inc['incentive_max']) : '-' ?></td>
            <td>
                <?= reviewBadge($reviewSt) ?>
                <?php if ($inc['review_memo']): ?>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:2px;" title="<?= htmlspecialchars($inc['review_memo']) ?>">💬 <?= mb_strimwidth(htmlspecialchars($inc['review_memo']),0,20,'...') ?></div>
                <?php endif; ?>
                <?php if ($inc['reviewed_by']): ?>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">by <?= htmlspecialchars($reviewerNames[$inc['reviewed_by']] ?? '') ?></div>
                <?php endif; ?>
            </td>
            <td class="text-left" style="font-size:var(--fs-xs);max-width:10rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php
                if ($dealMet) { $memo = "건수 달성 · {$inc['grade']} 기준"; }
                elseif ($amtMet) { $memo = "금액 달성 · {$inc['grade']} 기준"; }
                else { $memo = "미달(건수:{$inc['deal_count']}/{$td})"; }
                echo htmlspecialchars($memo);
            ?>"><?= htmlspecialchars($memo) ?></td>
            <td>
                <?php if ($canChange && ($inc['eligible']??'N')==='Y'): ?>
                <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;"
                    onclick="openReviewModal(<?= $inc['staff_id'] ?>, '<?= $inc['sale_month'] ?>', '<?= $reviewSt ?>', '<?= htmlspecialchars($inc['name']) ?>')">변경</button>
                <?php else: ?><span style="color:var(--text-tertiary);font-size:var(--fs-xs);">—</span><?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($incentives)): ?><tr><td colspan="13" class="text-muted">데이터가 없습니다.</td></tr><?php endif; ?>
        </tbody>
    </table></div>
    <?php if ($totalCnt > 0): ?>
    <div style="display:flex;justify-content:center;align-items:center;gap:0.5rem;padding:1rem;">
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">총 <?= $totalCnt ?>건 (<?= $page ?>/<?= $totalPages ?>)</span>
        <?php if ($totalPages > 1): ?>
        <?php if ($page>1): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page-1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">‹ 이전</a><?php endif; ?>
        <?php for($p=max(1,$page-2);$p<=min($totalPages,$page+2);$p++): ?>
        <a href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);border-radius:4px;text-decoration:none;<?= $p===$page?'background:var(--accent);color:var(--bg-color);font-weight:700;':'color:var(--text-secondary);' ?>"><?= $p ?></a>
        <?php endfor; ?>
        <?php if ($page<$totalPages): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page+1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">다음 ›</a><?php endif; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<!-- 검토 상태 변경 모달 -->
<div class="modal-overlay" id="reviewModal">
    <div class="modal" style="max-width:420px;">
        <div class="modal-header">
            <h3>📋 검토 상태 변경</h3>
            <button class="modal-close" onclick="document.getElementById('reviewModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="change_status">
            <input type="hidden" name="target_staff_id" id="rv_staff_id">
            <input type="hidden" name="target_month" id="rv_month">
            <div style="margin-bottom:0.75rem;">
                <strong id="rv_name"></strong> · <span id="rv_month_display"></span>
                <div style="margin-top:0.25rem;" id="rv_current_badge"></div>
            </div>
            <div class="form-group">
                <label>변경할 상태</label>
                <select name="new_status" id="rv_new_status" class="dash-filter" style="width:100%;" required>
                    <option value="대기">⏳ 대기</option>
                    <option value="검토중">🔍 검토중</option>
                    <option value="승인요청">📤 승인요청</option>
                    <option value="반려">❌ 반려</option>
                    <?php if (in_array($user['role'], ['ceo','sysadmin'])): ?>
                    <option value="대표승인">✅ 대표승인</option>
                    <option value="확정">🎉 확정</option>
                    <?php endif; ?>
                </select>
            </div>
            <div class="form-group">
                <label>사유 <span class="required">*</span></label>
                <textarea name="memo" rows="2" required placeholder="상태 변경 사유를 입력하세요"></textarea>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;">상태 변경</button>
        </form>
    </div>
</div>

<script>
function openReviewModal(staffId, month, currentStatus, name) {
    document.getElementById('rv_staff_id').value = staffId;
    document.getElementById('rv_month').value = month;
    document.getElementById('rv_name').textContent = name;
    document.getElementById('rv_month_display').textContent = month;
    document.getElementById('rv_current_badge').innerHTML = '현재: <strong>' + currentStatus + '</strong>';
    document.getElementById('rv_new_status').value = currentStatus;
    document.getElementById('reviewModal').classList.add('show');
}
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
