<?php
// pages/staff.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; }
$myRole = $_SESSION['user_role']??'';


$db = (new Database())->getConnection();
$user = currentUser();
$msg = '';

// 직원 정보 수정
if ($_SERVER['REQUEST_METHOD']==='POST') {
    $action = $_POST['action']??'';

    if ($action==='edit_staff' && in_array($_SESSION['user_role'] ?? '', ['manager','ceo','sysadmin'])) {
        $sid = (int)$_POST['staff_id'];
        $db->prepare("UPDATE staff SET name=?, email=?, phone=?, grade=?, team=?, memo=? WHERE staff_id=?")
           ->execute([trim($_POST['name']),trim($_POST['email']),trim($_POST['phone']??''),$_POST['grade'],$_POST['team'],trim($_POST['memo']??''),$sid]);
        writeAudit($db,'staff',$sid,'UPDATE',['name'=>$_POST['name'],'grade'=>$_POST['grade'],'team'=>$_POST['team']]);
        $msg = '정보가 수정되었습니다.';
    }

    // ── 팀장 후보 추천 (관리자만) ──
    if ($action==='nominate_leader' && $myRole === 'manager') {
        $targetUid = (int)$_POST['target_user_id'];
        $reason = trim($_POST['reason'] ?? '');
        $info = $db->prepare("SELECT u.user_id,u.user_role,u.staff_id,s.name,s.team FROM user_account u JOIN staff s ON u.staff_id=s.staff_id WHERE u.user_id=?");
        $info->execute([$targetUid]); $t = $info->fetch();
        if ($t && $t['user_role']==='staff') {
            $db->exec("CREATE TABLE IF NOT EXISTS team_leader_candidate (
                cand_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT NOT NULL, user_id INT NOT NULL,
                nominated_by INT NOT NULL, nominated_by_name VARCHAR(50) DEFAULT '', reason VARCHAR(300) DEFAULT '',
                status ENUM('대기','승인','거절') DEFAULT '대기', resolved_by INT DEFAULT NULL, resolved_memo VARCHAR(300) DEFAULT '',
                resolved_at DATETIME DEFAULT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY uk_staff_pending(staff_id, status)
            )");
            try {
                $db->prepare("INSERT INTO team_leader_candidate (staff_id, user_id, nominated_by, nominated_by_name, reason) VALUES(?,?,?,?,?)")
                   ->execute([$t['staff_id'], $targetUid, $_SESSION['staff_id'] ?? 0, $user['name'] ?? '', $reason]);
                $msg = htmlspecialchars($t['name']).' 님을 팀장 후보로 추천했습니다. 대표/시스템관리자 승인 대기 중입니다.';
            } catch(Exception $e) {
                $msg = '이미 팀장 후보로 등록되어 있습니다.';
            }
        }
    }

    // ── 팀장 후보 최종 승인 (대표/시스템관리자만) ──
    if ($action==='approve_leader' && in_array($myRole, ['manager','ceo','sysadmin'])) {
        $candId = (int)$_POST['cand_id'];
        $decision = $_POST['decision'] ?? '';
        $resolvedMemo = trim($_POST['resolved_memo'] ?? '');
        $cand = $db->prepare("SELECT c.*, s.name, COALESCE(c.user_id, u.user_id) AS uid FROM team_leader_candidate c JOIN staff s ON c.staff_id=s.staff_id LEFT JOIN user_account u ON c.staff_id=u.staff_id WHERE c.cand_id=? AND COALESCE(c.status,'대기')='대기'");
        $cand->execute([$candId]); $c = $cand->fetch();
        if ($c) {
            if ($decision === '승인') {
                $db->prepare("UPDATE user_account SET user_role='team_leader' WHERE staff_id=?")->execute([$c['staff_id']]);
                $db->prepare("UPDATE staff SET role='팀장' WHERE staff_id=?")->execute([$c['staff_id']]);
                syncTeamLeaderOnRoleChange($db, $c['staff_id'], 'staff', 'team_leader');
                $db->exec("CREATE TABLE IF NOT EXISTS team_leader_log (log_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT, previous_role VARCHAR(20), new_role VARCHAR(20), assigned_by INT, reason TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
                $db->prepare("INSERT INTO team_leader_log (staff_id,previous_role,new_role,assigned_by,reason) VALUES(?,?,?,?,?)")
                   ->execute([$c['staff_id'],'staff','team_leader',$_SESSION['user_id'],$resolvedMemo]);
                writeAudit($db,'user_account',$c['uid'],'ROLE_CHANGE',['new'=>'team_leader'],['old'=>'staff']);
                $msg = htmlspecialchars($c['name']).' 님이 팀장으로 최종 승인되었습니다.';
            } else {
                $msg = htmlspecialchars($c['name']).' 님의 팀장 후보가 거절되었습니다.';
            }
            $db->prepare("UPDATE team_leader_candidate SET status=?, resolved_by=?, resolved_memo=?, resolved_at=NOW() WHERE cand_id=?")
               ->execute([$decision, $_SESSION['staff_id'] ?? 0, $resolvedMemo, $candId]);
        }
    }

    // ── 팀장 해제 (대표/시스템관리자만) ──
    if ($action==='demote_leader' && in_array($myRole, ['manager','ceo','sysadmin'])) {
        $targetUid = (int)$_POST['target_user_id'];
        $reason = trim($_POST['reason'] ?? '');
        $info = $db->prepare("SELECT u.user_id,u.user_role,u.staff_id,s.name FROM user_account u JOIN staff s ON u.staff_id=s.staff_id WHERE u.user_id=?");
        $info->execute([$targetUid]); $t = $info->fetch();
        if ($t && $t['user_role']==='team_leader') {
            $db->prepare("UPDATE user_account SET user_role='staff' WHERE user_id=?")->execute([$targetUid]);
            $db->prepare("UPDATE staff SET role='직원' WHERE staff_id=?")->execute([$t['staff_id']]);
            syncTeamLeaderOnRoleChange($db, $t['staff_id'], 'team_leader', 'staff');
            $db->exec("CREATE TABLE IF NOT EXISTS team_leader_log (log_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT, previous_role VARCHAR(20), new_role VARCHAR(20), assigned_by INT, reason TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
            $db->prepare("INSERT INTO team_leader_log (staff_id,previous_role,new_role,assigned_by,reason) VALUES(?,?,?,?,?)")
               ->execute([$t['staff_id'],'team_leader','staff',$_SESSION['user_id'],$reason]);
            writeAudit($db,'user_account',$targetUid,'ROLE_CHANGE',['new'=>'staff'],['old'=>'team_leader']);
            $msg = htmlspecialchars($t['name']).' 님이 직원으로 변경되었습니다.';
        }
    }

    if ($action==='deactivate') {
        $sid = (int)$_POST['staff_id'];
        $db->prepare("UPDATE staff SET is_active=0 WHERE staff_id=?")->execute([$sid]);
        writeAudit($db,'staff',$sid,'DEACTIVATE');
        $msg = '비활성화 처리되었습니다.';
    }
}

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

$fTeam = $_GET['team']??'';
$fGrade = $_GET['grade']??'';
$where = "WHERE s.is_active=1";
if ($fTeam) $where .= " AND s.team=".($db->quote($fTeam));
if ($fGrade) $where .= " AND s.grade=".($db->quote($fGrade));

$staffList = $db->query("SELECT s.*, ua.user_id AS uid, ua.user_role, ua.login_id, ua.last_login
    FROM staff s LEFT JOIN user_account ua ON s.staff_id=ua.staff_id $where ORDER BY s.team, s.grade DESC, s.name")->fetchAll();

// 직원 목록 (시스템관리자 포함)
$staffList = array_values($staffList);

$teams = $db->query("SELECT team_name AS team FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
$grades = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN); if(!$grades) $grades=['사원','선임','책임','수석','팀장','본부장','총괄','이사'];

// 직급별/팀별 현황
$gradeStats = [];
$teamStats = [];
foreach ($staffList as $s) {
    $g = $s['grade'] ?? '-';
    $t = $s['team'] ?? '-';
    $gradeStats[$g] = ($gradeStats[$g]??0)+1;
    $teamStats[$t] = ($teamStats[$t]??0)+1;
}
?>

<div class="page-header"><h2>👥 조직 현황</h2><div class="breadcrumb">운영 관리 &gt; 조직 현황 (팀 현황 + 인원 관리)</div></div>

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

<!-- 필터 (상단) -->
<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;">
        <span style="font-size:var(--fs-sm);color:var(--text-secondary);">팀:</span>
        <select name="team" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
            <option value="">전체</option>
            <?php foreach ($teams as $t): ?><option value="<?= htmlspecialchars($t) ?>" <?= $fTeam===$t?'selected':'' ?>><?= htmlspecialchars($t) ?></option><?php endforeach; ?>
        </select>
        <span style="font-size:var(--fs-sm);color:var(--text-secondary);">직급:</span>
        <select name="grade" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">전체</option>
            <?php foreach ($grades as $g): ?><option value="<?= htmlspecialchars($g) ?>" <?= ($fGrade??'')===$g?'selected':'' ?>><?= htmlspecialchars($g) ?></option><?php endforeach; ?>
        </select>
        <span style="font-size:var(--fs-sm);color:var(--text-tertiary);margin-left:auto;"><?= count($staffList) ?>명</span>
    </form>
</div>

<!-- 현황 요약: 팀별 원형 + 직급별 바 -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1rem;">
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.75rem;font-weight:600;">팀별 현황</div>
        <div style="max-height:12rem;display:flex;justify-content:center;"><canvas id="teamPieChart"></canvas></div>
    </div>
    <div class="card" style="padding:1rem;">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.75rem;font-weight:600;">직급별 현황</div>
        <div style="max-height:12rem;"><canvas id="gradeBarChart"></canvas></div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
{
const palette=['#2979FF','#FF6D00','#00E676','#AA00FF','#00BCD4','#FF1744','#FFD600','#76FF03','#D500F9','#00E5FF'];
const teamLabels=<?= json_encode(array_keys($teamStats)) ?>;
const teamData=<?= json_encode(array_values($teamStats)) ?>;
const teamTotal=teamData.reduce((a,b)=>a+b,0);
new Chart(document.getElementById('teamPieChart'),{type:'doughnut',data:{labels:teamLabels,datasets:[{data:teamData,backgroundColor:palette.slice(0,teamLabels.length),borderWidth:1,borderColor:'rgba(0,0,0,0.3)'}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'right',labels:{color:'#ccc',font:{size:12},padding:8,usePointStyle:true,pointStyle:'circle'}},tooltip:{callbacks:{label:function(ctx){var pct=teamTotal>0?(ctx.raw/teamTotal*100).toFixed(1):0;return ctx.label+': '+ctx.raw+'명 ('+pct+'%)';}}}}},plugins:[{afterDraw:function(chart){var ctx=chart.ctx;ctx.save();ctx.font='600 12px sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';chart.data.datasets[0].data.forEach(function(val,i){if(val<=0)return;var meta=chart.getDatasetMeta(0);var arc=meta.data[i];var props=arc.getProps(['x','y','startAngle','endAngle','innerRadius','outerRadius']);var midAngle=(props.startAngle+props.endAngle)/2;var midRadius=(props.innerRadius+props.outerRadius)/2;var x=props.x+Math.cos(midAngle)*midRadius;var y=props.y+Math.sin(midAngle)*midRadius;var pct=teamTotal>0?(val/teamTotal*100).toFixed(0):0;ctx.fillStyle='#fff';ctx.fillText(pct+'%',x,y);});ctx.restore();}}]});
const gradeLabels=<?= json_encode(array_keys($gradeStats)) ?>;
const gradeData=<?= json_encode(array_values($gradeStats)) ?>;
new Chart(document.getElementById('gradeBarChart'),{type:'bar',data:{labels:gradeLabels,datasets:[{data:gradeData,backgroundColor:palette.slice(0,gradeLabels.length),borderWidth:0,borderRadius:4}]},options:{indexAxis:'y',responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{x:{grid:{color:'rgba(255,255,255,0.05)'},ticks:{color:'#aaa',font:{size:12}}},y:{grid:{display:false},ticks:{color:'#ccc',font:{size:12}}}}}});
}
</script>

<?php
// 페이지네이션
$staffTotal = count($staffList);
$staffPerPage = 20; $staffPage = max(1,(int)($_GET['page']??1));
$staffTotalPages = max(1, ceil($staffTotal / $staffPerPage));
$staffPageList = array_slice($staffList, ($staffPage-1)*$staffPerPage, $staffPerPage);
?>

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

<div class="card">
    <div class="card-header"><h3>인원 목록</h3></div>
    <div style="overflow-x:auto;">
    <table class="data-table">
        <thead><tr><th>No</th><th>이름</th><th>이메일</th><th>전화</th><th>직급</th><th>팀</th><th>역할</th><th>입사일</th><th>액션</th></tr></thead>
        <tbody>
        <?php foreach ($staffPageList as $_idx => $s): $realIdx = ($staffPage-1)*$staffPerPage + $_idx; ?>
        <tr id="row-<?= $s['staff_id'] ?>">
            <td><?= $realIdx + 1 ?></td>
            <td><strong><?= crownName($s['name'], $s['user_role']??'') ?></strong></td>
            <td style="font-size:var(--fs-xs);"><?= $s['email']==='미기재'?'<span class="badge badge-danger">⚠ 미기재</span>':htmlspecialchars($s['email']) ?></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($s['phone']??'-') ?></td>
            <td><span class="badge badge-info"><?= $s['grade'] ?></span></td>
            <td><?= htmlspecialchars($s['team']) ?></td>
            <td>
                <?php if ($s['user_role']==='team_leader'||$s['role']==='팀장'): ?>
                    <span class="badge badge-warning">팀장</span>
                <?php elseif (str_contains($s['role'],'관리자')): ?>
                    <span class="badge badge-danger"><?= $s['role'] ?></span>
                <?php else: ?>
                    <?= $s['role'] ?>
                <?php endif; ?>
            </td>
            <td style="font-size:var(--fs-xs);"><?= $s['hire_date'] ?></td>
            <td style="white-space:nowrap;">
                <?php if (in_array($_SESSION['user_role'] ?? '', ['manager','ceo','sysadmin'])): ?>
                <button onclick="openEdit(<?= htmlspecialchars(json_encode($s)) ?>)" class="btn btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;">수정</button>
                <?php endif; ?>
                <?php if ($myRole === 'manager' && ($s['user_role']??'') === 'staff'): ?>
                <button onclick="openNominate(<?= $s['uid'] ?>, '<?= htmlspecialchars($s['name']) ?>')" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;color:var(--accent-text);">👑 후보추천</button>
                <?php endif; ?>
                <?php if (in_array($myRole, ['manager','ceo','sysadmin']) && ($s['user_role']??'') === 'team_leader'): ?>
                <button onclick="openDemote(<?= $s['uid'] ?>, '<?= htmlspecialchars($s['name']) ?>')" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;color:var(--danger);">팀장해제</button>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php if ($staffTotal > 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);">총 <?= $staffTotal ?>명 (<?= $staffPage ?>/<?= $staffTotalPages ?>)</span>
        <?php if ($staffTotalPages > 1): ?>
        <?php if ($staffPage>1): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$staffPage-1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">‹ 이전</a><?php endif; ?>
        <?php for($p=max(1,$staffPage-2);$p<=min($staffTotalPages,$staffPage+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===$staffPage?'background:var(--accent);color:var(--bg-color);font-weight:700;':'color:var(--text-secondary);' ?>"><?= $p ?></a>
        <?php endfor; ?>
        <?php if ($staffPage<$staffTotalPages): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$staffPage+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 id="editModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.6);z-index:999;align-items:center;justify-content:center;">
    <div class="card" style="width:90%;max-width:32rem;padding:1.5rem;position:relative;">
        <button onclick="closeModals()" style="position:absolute;top:0.75rem;right:0.75rem;background:none;border:none;color:var(--text-tertiary);font-size:1.25rem;cursor:pointer;">✕</button>
        <h3 style="margin-bottom:1rem;">직원 정보 수정</h3>
        <form method="POST">
            <input type="hidden" name="action" value="edit_staff">
            <input type="hidden" name="staff_id" id="editSid">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;">
                <div class="form-group"><label>이름</label><input type="text" name="name" id="editName" required></div>
                <div class="form-group"><label>이메일</label><input type="email" name="email" id="editEmail"></div>
                <div class="form-group"><label>전화</label><input type="text" name="phone" id="editPhone"></div>
                <div class="form-group"><label>직급</label><select name="grade" id="editGrade"><?php foreach($grades as $g): ?><option><?= $g ?></option><?php endforeach; ?></select></div>
                <div class="form-group"><label>팀</label><select name="team" id="editTeam"><?php foreach($teams as $t): ?><option><?= htmlspecialchars($t) ?></option><?php endforeach; ?></select></div>
            </div>
            <div style="display:flex;gap:0.5rem;margin-top:0.75rem;">
                <button type="submit" class="btn btn-primary">저장</button>
                <button type="button" onclick="closeModals()" class="btn btn-outline">취소</button>
            </div>
        </form>
    </div>
</div>

<script>
function closeModals(){document.getElementById('editModal').style.display='none';try{document.getElementById('nominateModal').style.display='none';}catch(e){}try{document.getElementById('demoteModal').style.display='none';}catch(e){}try{document.getElementById('approveLeaderModal').style.display='none';}catch(e){}}
function openEdit(s){
    document.getElementById('editSid').value=s.staff_id;
    document.getElementById('editName').value=s.name;
    document.getElementById('editEmail').value=s.email||'';
    document.getElementById('editPhone').value=s.phone||'';
    document.getElementById('editGrade').value=s.grade;
    document.getElementById('editTeam').value=s.team;
    document.getElementById('editModal').style.display='flex';
}
function openNominate(uid, name) {
    document.getElementById('nomUid').value = uid;
    document.getElementById('nomName').textContent = name;
    document.getElementById('nominateModal').style.display = 'flex';
}
function openDemote(uid, name) {
    document.getElementById('demoteUid').value = uid;
    document.getElementById('demoteName').textContent = name;
    document.getElementById('demoteModal').style.display = 'flex';
}
function openApproveLeader(candId, name, nominator, reason) {
    document.getElementById('appCandId').value = candId;
    document.getElementById('appName').textContent = name;
    document.getElementById('appNominator').textContent = nominator;
    document.getElementById('appReason').textContent = reason;
    document.getElementById('approveLeaderModal').style.display = 'flex';
}
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeModals();});
</script>

<!-- ═══ 팀장 후보 대기 목록 (대표/시스템관리자용) ═══ -->
<?php
// 팀장 후보 섹션
$candidates = [];
$pendingCount = 0;
try {
    $db->exec("CREATE TABLE IF NOT EXISTS team_leader_candidate (
        cand_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT NOT NULL, user_id INT NOT NULL,
        nominated_by INT NOT NULL, nominated_by_name VARCHAR(50) DEFAULT '', reason VARCHAR(300) DEFAULT '',
        status VARCHAR(10) DEFAULT '대기', resolved_by INT DEFAULT NULL, resolved_memo VARCHAR(300) DEFAULT '',
        resolved_at DATETIME DEFAULT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
    // status 컬럼 존재 확인 후 추가
    try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN status VARCHAR(10) DEFAULT '대기'"); } catch(Exception $e2) {}
    try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN user_id INT DEFAULT NULL AFTER staff_id"); } catch(Exception $e2) {}
    try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN nominated_by_name VARCHAR(50) DEFAULT '' AFTER nominated_by"); } catch(Exception $e2) {}
    try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN resolved_by INT DEFAULT NULL AFTER status"); } catch(Exception $e2) {}
    try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN resolved_memo VARCHAR(300) DEFAULT '' AFTER resolved_by"); } catch(Exception $e2) {}
    try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN resolved_at DATETIME DEFAULT NULL AFTER resolved_memo"); } catch(Exception $e2) {}
    $candidates = $db->query("SELECT c.cand_id, c.staff_id, COALESCE(c.user_id,u.user_id) AS user_id, c.nominated_by, COALESCE(c.nominated_by_name,'') AS nominated_by_name, COALESCE(c.reason,'') AS reason, COALESCE(c.status,'대기') AS status, c.resolved_by, c.resolved_memo, c.resolved_at, c.created_at, s.name AS staff_name, s.grade, s.team
        FROM team_leader_candidate c JOIN staff s ON c.staff_id=s.staff_id LEFT JOIN user_account u ON c.staff_id=u.staff_id
        ORDER BY c.created_at DESC")->fetchAll();
    $pendingCount = count(array_filter($candidates, fn($c) => ($c['status'] ?? '') === '대기'));
} catch(Exception $e) { $candidates = []; }
?>
<?php if ($candidates): ?>
<div class="card" style="margin-top:1.25rem;">
    <div class="card-header"><h3>👑 팀장 후보 <?php if($pendingCount): ?><span class="badge badge-warning"><?= $pendingCount ?>건 대기</span><?php endif; ?></h3></div>
    <div style="overflow-x:auto;">
    <table class="data-table">
        <thead><tr><th>NO</th><th>대상자</th><th>직급</th><th>팀</th><th>추천자</th><th>추천 사유</th><th>상태</th><th>처리일</th>
            <?php if (in_array($myRole, ['manager','ceo','sysadmin'])): ?><th>처리</th><?php endif; ?>
        </tr></thead>
        <tbody>
        <?php foreach ($candidates as $ci => $c): ?>
        <tr style="<?= $c['status']==='대기'?'background:rgba(var(--accent-rgb),0.04);':($c['status']==='거절'?'opacity:0.5;':'') ?>">
            <td><?= $ci+1 ?></td>
            <td><strong><?= htmlspecialchars($c['staff_name']) ?></strong></td>
            <td><span class="badge badge-info"><?= $c['grade'] ?></span></td>
            <td><?= htmlspecialchars($c['team']) ?></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($c['nominated_by_name']) ?></td>
            <td style="font-size:var(--fs-xs);max-width:10rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= htmlspecialchars($c['reason']) ?>"><?= htmlspecialchars($c['reason'] ?: '-') ?></td>
            <td>
                <span class="badge <?= $c['status']==='승인'?'badge-success':($c['status']==='거절'?'badge-danger':'badge-warning') ?>">
                    <?= $c['status']==='승인'?'✅':($c['status']==='거절'?'❌':'⏳') ?> <?= $c['status'] ?>
                </span>
                <?php if ($c['resolved_memo']): ?><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">💬 <?= mb_strimwidth(htmlspecialchars($c['resolved_memo']),0,15,'...') ?></div><?php endif; ?>
            </td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $c['resolved_at'] ? date('Y-m-d', strtotime($c['resolved_at'])) : '-' ?></td>
            <?php if (in_array($myRole, ['manager','ceo','sysadmin'])): ?>
            <td>
                <?php if ($c['status'] === '대기'): ?>
                <button onclick="openApproveLeader(<?= $c['cand_id'] ?>, '<?= htmlspecialchars($c['staff_name']) ?>', '<?= htmlspecialchars($c['nominated_by_name']) ?>', '<?= htmlspecialchars($c['reason']) ?>')"
                    class="btn btn-sm btn-primary" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;">심사</button>
                <?php else: ?><span style="color:var(--text-tertiary);">—</span><?php endif; ?>
            </td>
            <?php endif; ?>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>
<?php endif; ?>

<!-- 후보 추천 모달 (관리자용) -->
<div id="nominateModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.6);z-index:999;align-items:center;justify-content:center;">
    <div class="card" style="width:90%;max-width:24rem;padding:1.5rem;position:relative;">
        <button onclick="closeModals()" style="position:absolute;top:0.75rem;right:0.75rem;background:none;border:none;color:var(--text-tertiary);font-size:1.25rem;cursor:pointer;">✕</button>
        <h3 style="margin-bottom:1rem;">👑 팀장 후보 추천</h3>
        <p style="margin-bottom:0.75rem;"><strong id="nomName"></strong> 님을 팀장 후보로 추천합니다.</p>
        <form method="POST">
            <input type="hidden" name="action" value="nominate_leader">
            <input type="hidden" name="target_user_id" id="nomUid">
            <div class="form-group">
                <label>추천 사유 <span class="required">*</span></label>
                <textarea name="reason" rows="3" required placeholder="팀장 후보 추천 사유를 입력하세요"></textarea>
            </div>
            <div class="alert alert-info" style="font-size:var(--fs-xs);margin-bottom:0.75rem;">대표 또는 시스템 관리자의 최종 승인 후 팀장으로 선정됩니다.</div>
            <button type="submit" class="btn btn-primary" style="width:100%;">후보 추천</button>
        </form>
    </div>
</div>

<!-- 팀장 해제 모달 (대표/시스템관리자용) -->
<div id="demoteModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.6);z-index:999;align-items:center;justify-content:center;">
    <div class="card" style="width:90%;max-width:24rem;padding:1.5rem;position:relative;">
        <button onclick="closeModals()" style="position:absolute;top:0.75rem;right:0.75rem;background:none;border:none;color:var(--text-tertiary);font-size:1.25rem;cursor:pointer;">✕</button>
        <h3 style="margin-bottom:1rem;">팀장 해제</h3>
        <p style="margin-bottom:0.75rem;"><strong id="demoteName"></strong> 님의 팀장 직책을 해제합니다.</p>
        <form method="POST">
            <input type="hidden" name="action" value="demote_leader">
            <input type="hidden" name="target_user_id" id="demoteUid">
            <div class="form-group">
                <label>해제 사유</label>
                <textarea name="reason" rows="2" placeholder="해제 사유"></textarea>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;background:var(--danger);">팀장 해제</button>
        </form>
    </div>
</div>

<!-- 후보 승인/거절 모달 (대표/시스템관리자용) -->
<div id="approveLeaderModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.6);z-index:999;align-items:center;justify-content:center;">
    <div class="card" style="width:90%;max-width:26rem;padding:1.5rem;position:relative;">
        <button onclick="closeModals()" style="position:absolute;top:0.75rem;right:0.75rem;background:none;border:none;color:var(--text-tertiary);font-size:1.25rem;cursor:pointer;">✕</button>
        <h3 style="margin-bottom:1rem;">👑 팀장 후보 심사</h3>
        <div style="margin-bottom:0.75rem;">
            <div>대상자: <strong id="appName"></strong></div>
            <div style="font-size:var(--fs-xs);color:var(--text-secondary);">추천자: <span id="appNominator"></span></div>
            <div style="font-size:var(--fs-xs);color:var(--text-secondary);margin-top:0.25rem;">추천 사유: <span id="appReason"></span></div>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="approve_leader">
            <input type="hidden" name="cand_id" id="appCandId">
            <div class="form-group">
                <label>결정 <span class="required">*</span></label>
                <select name="decision" required>
                    <option value="승인">✅ 승인 (팀장 선정)</option>
                    <option value="거절">❌ 거절</option>
                </select>
            </div>
            <div class="form-group">
                <label>사유</label>
                <textarea name="resolved_memo" rows="2" placeholder="승인/거절 사유"></textarea>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;">최종 결정</button>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
