<?php
// pages/admin_team_assign.php — 팀장 선정 (관리자/대표/시스템관리자)
// 3단계: 직원 → 후보 지정 → 팀장 선정
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';

$db = (new Database())->getConnection();
$message = '';

// leader_staff_id 컬럼 보장
try { $db->exec("ALTER TABLE team_master ADD COLUMN leader_staff_id INT DEFAULT NULL AFTER description"); } catch(Exception $e) {}

// 후보 테이블 생성
$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 DEFAULT NULL,
    nominated_by INT,
    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,
    UNIQUE KEY uk_staff (staff_id)
)");
// 누락 컬럼 보장
try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN user_id INT DEFAULT NULL AFTER staff_id"); } catch(Exception $e) {}
try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN nominated_by_name VARCHAR(50) DEFAULT '' AFTER nominated_by"); } catch(Exception $e) {}
try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN status VARCHAR(10) DEFAULT '대기' AFTER reason"); } catch(Exception $e) {}
try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN resolved_by INT DEFAULT NULL AFTER status"); } catch(Exception $e) {}
try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN resolved_memo VARCHAR(300) DEFAULT '' AFTER resolved_by"); } catch(Exception $e) {}
try { $db->exec("ALTER TABLE team_leader_candidate ADD COLUMN resolved_at DATETIME DEFAULT NULL AFTER resolved_memo"); } catch(Exception $e) {}


$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,
    assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// ── POST 처리 ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $targetUserId = (int)($_POST['target_user_id'] ?? 0);
    $targetStaffId = (int)($_POST['target_staff_id'] ?? 0);

    // 후보 지정
    if ($action === 'nominate' && $targetStaffId) {
        $targetUidQ = $db->prepare("SELECT user_id FROM user_account WHERE staff_id=?"); $targetUidQ->execute([$targetStaffId]); $targetUidVal = (int)$targetUidQ->fetchColumn();
        $db->prepare("INSERT IGNORE INTO team_leader_candidate (staff_id, user_id, nominated_by, nominated_by_name, reason, status) VALUES(?,?,?,?,?,?)")
           ->execute([$targetStaffId, $targetUidVal, $user['user_id'], $user['name'] ?? '', trim($_POST['reason'] ?? ''), '대기']);
        $nm = $db->prepare("SELECT name FROM staff WHERE staff_id=?"); $nm->execute([$targetStaffId]);
        $message = htmlspecialchars($nm->fetchColumn()) . ' 님이 팀장 후보로 지정되었습니다.';
    }

    // 후보 해제
    if ($action === 'remove_candidate' && $targetStaffId) {
        $db->prepare("DELETE FROM team_leader_candidate WHERE staff_id=?")->execute([$targetStaffId]);
        $message = '후보 지정이 해제되었습니다.';
    }

    // 팀장 선정 (후보 → 팀장) — 팀 선택 필수
    if ($action === 'promote_to_team_leader' && $targetStaffId) {
        $assignTeam = trim($_POST['assign_team'] ?? '');
        $info = $db->prepare("SELECT s.staff_id, s.name, s.team, u.user_id, u.user_role FROM staff s LEFT JOIN user_account u ON s.staff_id=u.staff_id WHERE s.staff_id=?");
        $info->execute([$targetStaffId]);
        $target = $info->fetch();

        if (!$assignTeam) {
            $message = '팀을 선택해주세요.';
        } elseif ($target) {
            // 해당 팀에 이미 팀장이 있는지 체크
            $existLeader = $db->prepare("SELECT leader_staff_id FROM team_master WHERE team_name=? AND leader_staff_id IS NOT NULL AND leader_staff_id != 0");
            $existLeader->execute([$assignTeam]);
            $existLid = (int)$existLeader->fetchColumn();
            if ($existLid && $existLid != $target['staff_id']) {
                $message = '해당 팀에는 이미 팀장이 있습니다. 먼저 기존 팀장을 해제하세요.';
            } else {
                $prevRole = $target['user_role'] ?? 'staff';
                // user_account가 있으면 역할 업데이트
                if ($target['user_id']) {
                    $db->prepare("UPDATE user_account SET user_role='team_leader' WHERE user_id=?")->execute([$target['user_id']]);
                }
                $db->prepare("UPDATE staff SET role='팀장', team=? WHERE staff_id=?")->execute([$assignTeam, $target['staff_id']]);
                $db->prepare("UPDATE team_master SET leader_staff_id=? WHERE team_name=?")->execute([$target['staff_id'], $assignTeam]);
                $db->prepare("UPDATE team_leader_candidate SET status='승인', resolved_by=?, resolved_memo=?, resolved_at=NOW() WHERE staff_id=?")->execute([$user['user_id'], trim($_POST['reason'] ?? ''), $target['staff_id']]);
                $db->prepare("INSERT INTO team_leader_log (staff_id, previous_role, new_role, assigned_by, reason) VALUES(?,?,?,?,?)")
                   ->execute([$target['staff_id'], $prevRole, 'team_leader', $user['user_id'], trim($_POST['reason'] ?? '')]);
                if ($target['user_id']) writeAudit($db, 'user_account', $target['user_id'], 'ROLE_CHANGE', ['new_role'=>'team_leader','team'=>$assignTeam,'assigned_by'=>$user['name']], ['old_role'=>$prevRole]);
                $message = htmlspecialchars($target['name']) . " 님이 '{$assignTeam}' 팀장으로 선정되었습니다.";
            }
        } else {
            $message = '해당 직원을 찾을 수 없습니다.';
        }
    }

    // 팀장 해제
    if ($action === 'demote_from_team_leader' && ($targetStaffId || $targetUserId)) {
        if ($targetStaffId) {
            $info = $db->prepare("SELECT s.staff_id, s.name, u.user_id, u.user_role FROM staff s LEFT JOIN user_account u ON s.staff_id=u.staff_id WHERE s.staff_id=?");
            $info->execute([$targetStaffId]);
        } else {
            $info = $db->prepare("SELECT s.staff_id, s.name, u.user_id, u.user_role FROM user_account u JOIN staff s ON u.staff_id=s.staff_id WHERE u.user_id=?");
            $info->execute([$targetUserId]);
        }
        $target = $info->fetch();

        if ($target) {
            $isLeaderInTeam = $db->prepare("SELECT COUNT(*) FROM team_master WHERE leader_staff_id=?");
            $isLeaderInTeam->execute([$target['staff_id']]);
            if ($isLeaderInTeam->fetchColumn() > 0) {
                $prevRole = $target['user_role'] ?? 'team_leader';
                if ($target['user_id']) {
                    $db->prepare("UPDATE user_account SET user_role='staff' WHERE user_id=?")->execute([$target['user_id']]);
                }
                $db->prepare("UPDATE staff SET role='직원' WHERE staff_id=?")->execute([$target['staff_id']]);
                $db->prepare("UPDATE team_master SET leader_staff_id=NULL WHERE leader_staff_id=?")->execute([$target['staff_id']]);
                $db->prepare("INSERT INTO team_leader_log (staff_id, previous_role, new_role, assigned_by, reason) VALUES(?,?,?,?,?)")
                   ->execute([$target['staff_id'], $prevRole, 'staff', $user['user_id'], trim($_POST['reason'] ?? '')]);
                if ($target['user_id']) writeAudit($db, 'user_account', $target['user_id'], 'ROLE_CHANGE', ['new_role'=>'staff'], ['old_role'=>$prevRole]);
                $message = htmlspecialchars($target['name']) . ' 님이 직원으로 변경되었습니다.';
            }
        }
    }
}

// ── 팀 필터 ──
$filterTeam = $_GET['team'] ?? '';
$allTeamsList = $db->query("SELECT team_name AS team FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
// 팀장이 없는 팀만 (선정 가능)
$availableTeams = $db->query("SELECT team_name FROM team_master WHERE is_active=1 AND (leader_staff_id IS NULL OR leader_staff_id=0) ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);

// ── 현재 팀장 ──
$teamLeaders = $db->query("
    SELECT u.user_id, s.staff_id, s.name, s.grade, s.team, s.hire_date, u.user_role
    FROM team_master tm
    JOIN staff s ON tm.leader_staff_id = s.staff_id
    JOIN user_account u ON u.staff_id = s.staff_id
    WHERE tm.leader_staff_id IS NOT NULL AND tm.leader_staff_id != 0
      AND tm.is_active = 1 AND u.is_active = 1
    ORDER BY s.team, s.name
")->fetchAll();

// ── 후보 목록 ──
$candidates = $db->query("
    SELECT c.cand_id, c.staff_id, c.reason, c.created_at,
           s.name, s.grade, s.team, s.hire_date,
           u.user_id, u.user_role,
           s2.name AS nominated_by_name
    FROM team_leader_candidate c
    JOIN staff s ON c.staff_id = s.staff_id
    LEFT JOIN user_account u ON s.staff_id = u.staff_id
    LEFT JOIN user_account ua2 ON c.nominated_by = ua2.user_id
    LEFT JOIN staff s2 ON ua2.staff_id = s2.staff_id
    WHERE s.is_active = 1 AND COALESCE(c.status,'대기') IN ('대기')
    ORDER BY s.team, s.name
")->fetchAll();
$candidateStaffIds = array_column($candidates, 'staff_id');

// ── 일반 직원 (후보도 아니고 팀장도 아닌) ──
$leaderStaffIds = array_column($teamLeaders, 'staff_id');
$allStaff = $db->query("
    SELECT s.staff_id, s.name, s.grade, s.team, s.hire_date,
           u.user_id, u.user_role
    FROM staff s
    LEFT JOIN user_account u ON s.staff_id = u.staff_id
    WHERE s.is_active = 1
    ORDER BY s.team, s.name
")->fetchAll();

$normalStaff = array_filter($allStaff, fn($s) =>
    !in_array($s['staff_id'], $candidateStaffIds) &&
    !in_array($s['staff_id'], $leaderStaffIds)
);

// 팀 필터 적용
$fLeaders = $filterTeam ? array_filter($teamLeaders, fn($x) => $x['team'] === $filterTeam) : $teamLeaders;
$fCandidates = $filterTeam ? array_filter($candidates, fn($x) => $x['team'] === $filterTeam) : $candidates;
$fNormal = $filterTeam ? array_filter($normalStaff, fn($x) => $x['team'] === $filterTeam) : $normalStaff;

// ── 이력 ──
$logs = $db->query("
    SELECT tl.*, s.name AS staff_name, s.team, s2.name AS assigned_by_name
    FROM team_leader_log tl
    JOIN staff s ON tl.staff_id = s.staff_id
    LEFT JOIN user_account ua ON tl.assigned_by = ua.user_id
    LEFT JOIN staff s2 ON ua.staff_id = s2.staff_id
    ORDER BY tl.assigned_at DESC LIMIT 20
")->fetchAll();

$roleLabel = ['staff'=>'직원','team_leader'=>'팀장','manager'=>'관리자','ceo'=>'대표','sysadmin'=>'시스템관리자'];
?>

<div class="page-header">
    <h2>🏅 팀장 선정</h2>
    <div class="breadcrumb">직원 → 후보 지정 → 팀장 선정</div>
</div>

<?php if ($message): ?><div class="alert alert-success" style="margin-bottom:1rem;">✓ <?= $message ?></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:12rem;">
            <option value="">전체</option>
            <?php foreach ($allTeamsList as $t): ?>
            <option value="<?= htmlspecialchars($t) ?>" <?= $filterTeam===$t?'selected':'' ?>><?= htmlspecialchars($t) ?></option>
            <?php endforeach; ?>
        </select>
        <div style="margin-left:auto;display:flex;gap:1rem;font-size:var(--fs-sm);">
            <span style="color:var(--text-tertiary);">👑 팀장 <strong style="color:var(--accent-text);"><?= count($fLeaders) ?></strong></span>
            <span style="color:var(--text-tertiary);">⭐ 후보 <strong style="color:var(--warning);"><?= count($fCandidates) ?></strong></span>
            <span style="color:var(--text-tertiary);">👤 직원 <strong style="color:var(--text-primary);"><?= count($fNormal) ?></strong></span>
        </div>
    </form>
</div>

<!-- 프로세스 안내 -->
<div class="card" style="margin-bottom:1rem;padding:0.75rem;">
    <div style="display:flex;align-items:center;justify-content:center;gap:1.5rem;font-size:var(--fs-sm);">
        <div style=""><div style="font-size:1.25rem;">👤</div><div style="color:var(--text-secondary);">직원</div></div>
        <div style="color:var(--text-tertiary);">→</div>
        <div style="color:var(--warning);"><div style="font-size:1.25rem;">⭐</div><div>후보 지정</div></div>
        <div style="color:var(--text-tertiary);">→</div>
        <div style="color:var(--accent-text);"><div style="font-size:1.25rem;">👑</div><div>팀장 선정</div></div>
    </div>
</div>

<!-- ═══ 3단 레이아웃 ═══ -->
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;margin-bottom:1.25rem;">

    <!-- 1. 일반 직원 (→ 후보 지정) -->
    <div class="card">
        <div class="card-header"><h3>👤 직원 (<?= count($fNormal) ?>)</h3></div>
        <?php if (empty($fNormal)): ?>
        <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">해당 없음</div>
        <?php else: ?>
        <div style="max-height:26rem;overflow-y:auto;">
        <?php foreach ($fNormal as $s): ?>
        <div class="tl-item" style="display:flex;justify-content:space-between;align-items:center;">
            <div>
                <div style="font-size:var(--fs-sm);font-weight:600;color:var(--text-primary);"><?= htmlspecialchars($s['name']) ?></div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><span class="badge badge-info" style="font-size:var(--fs-xs);"><?= $s['grade'] ?></span> <?= htmlspecialchars($s['team']) ?></div>
            </div>
            <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;color:var(--warning);"
                onclick="openNominate(<?= $s['staff_id'] ?>,'<?= htmlspecialchars($s['name'],ENT_QUOTES) ?>')">후보 →</button>
        </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- 2. 후보 (→ 팀장 선정) -->
    <div class="card" style="border:1px solid rgba(255,179,0,0.15);">
        <div class="card-header" style="background:rgba(255,179,0,0.06);"><h3>⭐ 팀장 후보 (<?= count($fCandidates) ?>)</h3></div>
        <?php if (empty($fCandidates)): ?>
        <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">지정된 후보 없음<br><span style="font-size:var(--fs-xs);">직원 목록에서 후보를 지정하세요</span></div>
        <?php else: ?>
        <div style="max-height:26rem;overflow-y:auto;">
        <?php foreach ($fCandidates as $c): ?>
        <div class="tl-item">
            <div style="display:flex;justify-content:space-between;align-items:flex-start;">
                <div style="flex:1;min-width:0;">
                    <div style="font-size:var(--fs-sm);font-weight:700;color:var(--text-primary);">⭐ <?= htmlspecialchars($c['name']) ?></div>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><span class="badge badge-info" style="font-size:var(--fs-xs);"><?= $c['grade'] ?></span> <?= htmlspecialchars($c['team']) ?> · <?= $c['hire_date'] ?></div>
                    <?php if ($c['reason']): ?><div style="font-size:var(--fs-xs);color:var(--text-secondary);margin-top:0.125rem;">💬 <?= htmlspecialchars($c['reason']) ?></div><?php endif; ?>
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:0.125rem;">추천: <?= htmlspecialchars($c['nominated_by_name']??'-') ?> · <?= date('m/d',strtotime($c['created_at'])) ?></div>
                </div>
                <div style="display:flex;flex-direction:column;gap:0.25rem;flex-shrink:0;">
                    <?php if (!in_array($c['user_role']??'staff', ['team_leader'])): ?>
                    <button class="btn btn-sm btn-success" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;"
                        onclick="openPromote(<?= $c['staff_id'] ?>,'<?= htmlspecialchars($c['name'],ENT_QUOTES) ?>')">팀장 →</button>
                    <?php endif; ?>
                    <form method="POST" style="display:inline;"><input type="hidden" name="action" value="remove_candidate"><input type="hidden" name="target_staff_id" value="<?= $c['staff_id'] ?>">
                    <button type="submit" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;" onclick="return confirm('후보 해제?')">← 해제</button></form>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- 3. 현재 팀장 -->
    <div class="card" style="border:1px solid rgba(var(--accent-rgb),0.15);">
        <div class="card-header" style="background:rgba(var(--accent-rgb),0.06);"><h3>👑 현재 팀장 (<?= count($fLeaders) ?>)</h3></div>
        <?php if (empty($fLeaders)): ?>
        <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">팀장 없음</div>
        <?php else: ?>
        <div style="max-height:26rem;overflow-y:auto;">
        <?php foreach ($fLeaders as $tl): ?>
        <div class="tl-item" style="display:flex;justify-content:space-between;align-items:center;">
            <div>
                <div style="font-size:var(--fs-sm);font-weight:700;color:var(--text-primary);">👑 <?= htmlspecialchars($tl['name']) ?></div>
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><span class="badge badge-info" style="font-size:var(--fs-xs);"><?= $tl['grade'] ?></span> <?= htmlspecialchars($tl['team']) ?></div>
            </div>
            <button class="btn btn-sm btn-danger" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;"
                onclick="openDemote(<?= $tl['staff_id'] ?>,'<?= htmlspecialchars($tl['name'],ENT_QUOTES) ?>')">해제</button>
        </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- 이력 -->
<div class="card">
    <div class="card-header"><h3>📝 선정/해제 이력</h3></div>
    <?php if ($logs): ?>
    <table class="data-table">
        <thead><tr><th>일시</th><th>대상</th><th>팀</th><th>변경</th><th>처리자</th><th>사유</th></tr></thead>
        <tbody>
        <?php foreach ($logs as $l): ?>
        <tr>
            <td style="font-size:var(--fs-xs);"><?= date('Y-m-d H:i', strtotime($l['assigned_at'])) ?></td>
            <td><strong><?= htmlspecialchars($l['staff_name']) ?></strong></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($l['team']) ?></td>
            <td>
                <span class="badge badge-gray"><?= $roleLabel[$l['previous_role']] ?? $l['previous_role'] ?></span>
                →
                <span class="badge <?= $l['new_role']==='team_leader'?'badge-success':'badge-warning' ?>"><?= $roleLabel[$l['new_role']] ?? $l['new_role'] ?></span>
            </td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($l['assigned_by_name'] ?? '-') ?></td>
            <td style="font-size:var(--fs-xs);max-width:10rem;overflow:hidden;text-overflow:ellipsis;"><?= htmlspecialchars($l['reason'] ?? '') ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php else: ?>
    <div style="padding:1.5rem;color:var(--text-tertiary);font-size:var(--fs-sm);">이력 없음</div>
    <?php endif; ?>
</div>

<!-- 후보 지정 모달 -->
<div class="modal-overlay" id="nominateModal">
    <div class="modal">
        <div class="modal-header">
            <h3>⭐ 후보 지정 — <span id="nomName"></span></h3>
            <button class="modal-close" onclick="this.closest('.modal-overlay').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="nominate">
            <input type="hidden" name="target_staff_id" id="nomStaffId">
            <div class="form-group">
                <label>추천 사유</label>
                <textarea name="reason" rows="2" placeholder="팀장 후보 추천 사유 (선택)"></textarea>
            </div>
            <button type="submit" class="btn btn-primary" style="background:var(--warning);color:#000;">⭐ 후보 지정</button>
        </form>
    </div>
</div>

<!-- 팀장 선정 모달 -->
<div class="modal-overlay" id="promoteModal">
    <div class="modal">
        <div class="modal-header">
            <h3>👑 팀장 선정 — <span id="promoteName"></span></h3>
            <button class="modal-close" onclick="this.closest('.modal-overlay').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="promote_to_team_leader">
            <input type="hidden" name="target_staff_id" id="promoteStaffId">
            <div class="form-group">
                <label>배정 팀 *</label>
                <select name="assign_team" required style="width:100%;font-size:var(--fs-sm);">
                    <option value="">— 팀 선택 —</option>
                    <?php foreach ($availableTeams as $at): ?>
                    <option value="<?= htmlspecialchars($at) ?>"><?= htmlspecialchars($at) ?></option>
                    <?php endforeach; ?>
                </select>
                <?php if (empty($availableTeams)): ?>
                <div class="alert alert-warning" style="font-size:var(--fs-xs);margin-top:0.5rem;">⚠ 모든 팀에 팀장이 배정되어 있습니다. 먼저 기존 팀장을 해제하세요.</div>
                <?php endif; ?>
            </div>
            <div class="form-group">
                <label>선정 사유</label>
                <textarea name="reason" rows="2" placeholder="팀장 선정 사유 (선택)"></textarea>
            </div>
            <button type="submit" class="btn btn-success" <?= empty($availableTeams)?'disabled':'' ?>>👑 팀장으로 선정</button>
        </form>
    </div>
</div>

<!-- 팀장 해제 모달 -->
<div class="modal-overlay" id="demoteModal">
    <div class="modal">
        <div class="modal-header">
            <h3>⬇️ 팀장 해제 — <span id="demoteName"></span></h3>
            <button class="modal-close" onclick="this.closest('.modal-overlay').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="demote_from_team_leader">
            <input type="hidden" name="target_staff_id" id="demoteStaffId">
            <div class="form-group">
                <label>해제 사유</label>
                <textarea name="reason" rows="2" placeholder="해제 사유 (선택)"></textarea>
            </div>
            <div class="alert alert-warning" style="margin-bottom:0.75rem;">⚠ 팀장 해제 시 직원으로 변경됩니다.</div>
            <button type="submit" class="btn btn-danger">직원으로 변경</button>
        </form>
    </div>
</div>

<script>
function openNominate(sid, name) {
    document.getElementById('nomStaffId').value = sid;
    document.getElementById('nomName').textContent = name;
    document.getElementById('nominateModal').classList.add('show');
}
function openPromote(sid, name) {
    document.getElementById('promoteStaffId').value = sid;
    document.getElementById('promoteName').textContent = name;
    document.getElementById('promoteModal').classList.add('show');
}
function openDemote(sid, name) {
    document.getElementById('demoteStaffId').value = sid;
    document.getElementById('demoteName').textContent = name;
    document.getElementById('demoteModal').classList.add('show');
}
</script>

<style>
.tl-item { padding:0.625rem 0.75rem; border-bottom:1px solid rgba(255,255,255,0.06); transition:background 0.15s; }
.tl-item:hover { background:rgba(var(--accent-rgb),0.04); }
.tl-item:last-child { border-bottom:none; }
</style>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
