<?php
// pages/admin_teams.php — 인사관리 (팀 · 직급 관리)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
requireLogin();
$db = (new Database())->getConnection();

// ── 팀장 이력 삭제 POST (header 전에 처리해야 redirect 가능) ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $preAction = $_POST['action'] ?? '';
    if ($preAction === 'delete_leader_log') {
        $llId = (int)($_POST['log_id'] ?? 0);
        if ($llId) {
            $db->exec("CREATE TABLE IF NOT EXISTS team_leader_log (log_id INT AUTO_INCREMENT PRIMARY KEY, team_id INT NOT NULL, team_name VARCHAR(100) DEFAULT '', staff_id INT DEFAULT NULL, staff_name VARCHAR(50) DEFAULT '', action_type VARCHAR(20) NOT NULL, changed_by INT NOT NULL, changed_by_name VARCHAR(50) DEFAULT '', created_at DATETIME DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $db->prepare("DELETE FROM team_leader_log WHERE log_id=?")->execute([$llId]);
        }
        header("Location: ".BASE_URL."pages/admin_teams.php?tab=team&msg=" . urlencode('이력이 삭제되었습니다.')); exit;
    }
    if ($preAction === 'delete_all_leader_logs') {
        $db->exec("CREATE TABLE IF NOT EXISTS team_leader_log (log_id INT AUTO_INCREMENT PRIMARY KEY, team_id INT NOT NULL, team_name VARCHAR(100) DEFAULT '', staff_id INT DEFAULT NULL, staff_name VARCHAR(50) DEFAULT '', action_type VARCHAR(20) NOT NULL, changed_by INT NOT NULL, changed_by_name VARCHAR(50) DEFAULT '', created_at DATETIME DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        $db->exec("DELETE FROM team_leader_log");
        header("Location: ".BASE_URL."pages/admin_teams.php?tab=team&msg=" . urlencode('전체 이력이 삭제되었습니다.')); exit;
    }
}

require_once __DIR__ . '/../includes/header.php';
$message = $_GET['msg'] ?? '';

// 팀 마스터 테이블
$db->exec("CREATE TABLE IF NOT EXISTS team_master (
    team_id     INT AUTO_INCREMENT PRIMARY KEY,
    team_name   VARCHAR(50) NOT NULL UNIQUE,
    description VARCHAR(200) DEFAULT '',
    leader_staff_id INT DEFAULT NULL,
    is_active   TINYINT(1) DEFAULT 1,
    created_at  DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at  DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");
// 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 grade_master (
    grade_id    INT AUTO_INCREMENT PRIMARY KEY,
    grade_name  VARCHAR(30) NOT NULL UNIQUE,
    sort_order  INT DEFAULT 0,
    is_active   TINYINT(1) DEFAULT 1,
    created_at  DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// 기존 데이터 동기화
$existingTeams = $db->query("SELECT DISTINCT team FROM staff WHERE team IS NOT NULL AND team != '' ORDER BY team")->fetchAll(PDO::FETCH_COLUMN);
foreach ($existingTeams as $et) {
    $db->prepare("INSERT IGNORE INTO team_master (team_name) VALUES(?)")->execute([$et]);
}
$existingGrades = $db->query("SELECT DISTINCT grade FROM staff WHERE grade IS NOT NULL AND grade != '' ORDER BY grade")->fetchAll(PDO::FETCH_COLUMN);
$gOrder = 0;
foreach ($existingGrades as $eg) {
    $db->prepare("INSERT IGNORE INTO grade_master (grade_name, sort_order) VALUES(?,?)")->execute([$eg, $gOrder++]);
}

// POST 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // ── 팀 관리 ──
    if ($action === 'create_team') {
        $name = trim($_POST['team_name'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        if ($name) {
            try {
                $db->prepare("INSERT INTO team_master (team_name, description) VALUES(?,?)")->execute([$name, $desc]);
                writeAudit($db, 'team_master', $db->lastInsertId(), 'INSERT', ['team_name'=>$name]);
                $message = "'{$name}' 팀이 생성되었습니다.";
            } catch (PDOException $e) {
                $message = str_contains($e->getMessage(), 'Duplicate') ? '이미 존재하는 팀 이름입니다.' : '오류: '.$e->getMessage();
            }
        }
    }

    if ($action === 'update_team') {
        $teamId = (int)($_POST['team_id'] ?? 0);
        $newName = trim($_POST['team_name'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        $oldName = trim($_POST['old_name'] ?? '');
        if ($teamId && $newName) {
            try {
                $db->prepare("UPDATE team_master SET team_name=?, description=? WHERE team_id=?")->execute([$newName, $desc, $teamId]);
                if ($oldName && $oldName !== $newName) {
                    $db->prepare("UPDATE staff SET team=? WHERE team=?")->execute([$newName, $oldName]);
                }
                $message = "팀 정보가 수정되었습니다.";
            } catch (PDOException $e) {
                $message = str_contains($e->getMessage(), 'Duplicate') ? '이미 존재하는 팀 이름입니다.' : '오류: '.$e->getMessage();
            }
        }
    }

    if ($action === 'toggle_team') {
        $teamId = (int)($_POST['team_id'] ?? 0);
        if ($teamId) {
            $db->prepare("UPDATE team_master SET is_active = NOT is_active WHERE team_id=?")->execute([$teamId]);
            $message = '팀 상태가 변경되었습니다.';
        }
    }

    if ($action === 'delete_team') {
        $teamId = (int)($_POST['team_id'] ?? 0);
        $teamName = trim($_POST['team_name'] ?? '');
        if ($teamId && $teamName) {
            $db->exec("CREATE TABLE IF NOT EXISTS notifications (noti_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, message VARCHAR(500), link VARCHAR(200) DEFAULT '', is_read TINYINT(1) DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
            $members = $db->prepare("SELECT ua.user_id FROM staff s JOIN user_account ua ON s.staff_id=ua.staff_id WHERE s.team=?");
            $members->execute([$teamName]);
            foreach ($members->fetchAll(PDO::FETCH_COLUMN) as $uid) {
                $db->prepare("INSERT INTO notifications (user_id, message, link) VALUES(?,?,?)")->execute([$uid, "'{$teamName}' 팀이 개편 되었습니다. 관리자에게 문의하세요.", BASE_URL.'pages/home.php']);
            }
            $db->prepare("UPDATE staff SET team='' WHERE team=?")->execute([$teamName]);
            $db->prepare("DELETE FROM team_master WHERE team_id=?")->execute([$teamId]);
            writeAudit($db, 'team_master', $teamId, 'DELETE', ['team_name'=>$teamName]);
            $message = "'{$teamName}' 팀이 삭제되었습니다. 소속 직원에게 알림이 전송되었습니다.";
        }
    }

    if ($action === 'assign_member') {
        $teamName = trim($_POST['team_name'] ?? '');
        $staffId = (int)($_POST['staff_id'] ?? 0);
        if ($teamName && $staffId) {
            $db->prepare("UPDATE staff SET team=? WHERE staff_id=?")->execute([$teamName, $staffId]);
            $message = '팀원이 배정되었습니다.';
        }
    }

    if ($action === 'remove_member') {
        $staffId = (int)($_POST['staff_id'] ?? 0);
        if ($staffId) {
            $db->prepare("UPDATE staff SET team='' WHERE staff_id=?")->execute([$staffId]);
            $message = '팀원이 제외되었습니다.';
        }
    }

    // ── 팀장 선정/변경 (팀 관리에서) ──
    if ($action === 'set_team_leader') {
        $teamId = (int)($_POST['team_id'] ?? 0);
        $staffId = (int)($_POST['leader_staff_id'] ?? 0);
        if ($teamId) {
            // 기존 팀장 해제
            $oldLeader = $db->prepare("SELECT leader_staff_id FROM team_master WHERE team_id=?");
            $oldLeader->execute([$teamId]); $oldLid = (int)$oldLeader->fetchColumn();
            if ($oldLid && $oldLid != $staffId) {
                $oldUa = $db->prepare("SELECT user_id FROM user_account WHERE staff_id=? AND user_role='team_leader'");
                $oldUa->execute([$oldLid]); $oldUid = $oldUa->fetchColumn();
                if ($oldUid) {
                    $db->prepare("UPDATE user_account SET user_role='staff' WHERE user_id=?")->execute([$oldUid]);
                    $db->prepare("UPDATE staff SET role='직원' WHERE staff_id=?")->execute([$oldLid]);
                }
            }
            if ($staffId) {
                // 새 팀장 설정
                $db->prepare("UPDATE team_master SET leader_staff_id=? WHERE team_id=?")->execute([$staffId, $teamId]);
                $ua = $db->prepare("SELECT user_id FROM user_account WHERE staff_id=?"); $ua->execute([$staffId]); $uid = $ua->fetchColumn();
                if ($uid) {
                    $db->prepare("UPDATE user_account SET user_role='team_leader' WHERE user_id=?")->execute([$uid]);
                    $db->prepare("UPDATE staff SET role='팀장' WHERE staff_id=?")->execute([$staffId]);
                }
                $nm = $db->prepare("SELECT name FROM staff WHERE staff_id=?"); $nm->execute([$staffId]);
                $leaderName = $nm->fetchColumn();
                $message = htmlspecialchars($leaderName) . ' 님이 팀장으로 선정되었습니다.';
                // 이력 기록
                $tmNm = $db->prepare("SELECT team_name FROM team_master WHERE team_id=?"); $tmNm->execute([$teamId]);
                $db->prepare("INSERT INTO team_leader_log (team_id, team_name, staff_id, staff_name, action_type, changed_by, changed_by_name) VALUES(?,?,?,?,?,?,?)")
                   ->execute([$teamId, $tmNm->fetchColumn(), $staffId, $leaderName, '선정', $user['staff_id'], $user['name']]);
            } else {
                // 팀장 해제만
                $db->prepare("UPDATE team_master SET leader_staff_id=NULL WHERE team_id=?")->execute([$teamId]);
                $message = '팀장이 해제되었습니다.';
                // 이력 기록
                if ($oldLid) {
                    $oldName = $db->prepare("SELECT name FROM staff WHERE staff_id=?"); $oldName->execute([$oldLid]);
                    $tmNm = $db->prepare("SELECT team_name FROM team_master WHERE team_id=?"); $tmNm->execute([$teamId]);
                    $db->prepare("INSERT INTO team_leader_log (team_id, team_name, staff_id, staff_name, action_type, changed_by, changed_by_name) VALUES(?,?,?,?,?,?,?)")
                       ->execute([$teamId, $tmNm->fetchColumn(), $oldLid, $oldName->fetchColumn(), '해제', $user['staff_id'], $user['name']]);
                }
            }
        }
    }

    // ── 직급 관리 ──
    if ($action === 'create_grade') {
        $name = trim($_POST['grade_name'] ?? '');
        $order = (int)($_POST['sort_order'] ?? 0);
        if ($name) {
            try {
                $db->prepare("INSERT INTO grade_master (grade_name, sort_order) VALUES(?,?)")->execute([$name, $order]);
                $message = "'{$name}' 직급이 생성되었습니다.";
            } catch (PDOException $e) {
                $message = str_contains($e->getMessage(), 'Duplicate') ? '이미 존재하는 직급입니다.' : '오류: '.$e->getMessage();
            }
        }
    }

    if ($action === 'update_grade') {
        $gradeId = (int)($_POST['grade_id'] ?? 0);
        $newName = trim($_POST['grade_name'] ?? '');
        $oldName = trim($_POST['old_grade_name'] ?? '');
        $order = (int)($_POST['sort_order'] ?? 0);
        if ($gradeId && $newName) {
            try {
                $db->prepare("UPDATE grade_master SET grade_name=?, sort_order=? WHERE grade_id=?")->execute([$newName, $order, $gradeId]);
                if ($oldName && $oldName !== $newName) {
                    $db->prepare("UPDATE staff SET grade=? WHERE grade=?")->execute([$newName, $oldName]);
                }
                $message = "직급이 수정되었습니다.";
            } catch (PDOException $e) {
                $message = str_contains($e->getMessage(), 'Duplicate') ? '이미 존재하는 직급입니다.' : '오류: '.$e->getMessage();
            }
        }
    }

    if ($action === 'delete_grade') {
        $gradeId = (int)($_POST['grade_id'] ?? 0);
        $gradeName = trim($_POST['grade_name'] ?? '');
        if ($gradeId) {
            $cnt = $db->prepare("SELECT COUNT(*) FROM staff WHERE grade=?"); $cnt->execute([$gradeName]);
            if ($cnt->fetchColumn() > 0) {
                $message = "'{$gradeName}' 직급을 사용 중인 직원이 있어 삭제할 수 없습니다.";
            } else {
                $db->prepare("DELETE FROM grade_master WHERE grade_id=?")->execute([$gradeId]);
                $message = "'{$gradeName}' 직급이 삭제되었습니다.";
            }
        }
    }
}

// 데이터 조회
$teams = $db->query("
    SELECT tm.*,
        (SELECT COUNT(*) FROM staff s WHERE s.team = tm.team_name AND s.is_active=1) AS member_count,
        (SELECT GROUP_CONCAT(s.name ORDER BY s.name SEPARATOR ', ') FROM staff s WHERE s.team = tm.team_name AND s.is_active=1 LIMIT 10) AS members,
        sl.name AS leader_name
    FROM team_master tm
    LEFT JOIN staff sl ON tm.leader_staff_id = sl.staff_id
    ORDER BY tm.is_active DESC, tm.team_name
")->fetchAll();

// 후보 테이블 보장
$db->exec("CREATE TABLE IF NOT EXISTS team_leader_candidate (
    cand_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT NOT NULL,
    nominated_by INT, reason VARCHAR(300) DEFAULT '',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uk_staff (staff_id))");

// 팀별 후보 목록
$candidatesByTeam = [];
$allCandidates = $db->query("
    SELECT c.staff_id, c.reason, s.name, s.team, u.user_id, u.user_role
    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
    WHERE s.is_active=1
    ORDER BY s.name
")->fetchAll();
foreach ($allCandidates as $ac) {
    if ($ac['team']) $candidatesByTeam[$ac['team']][] = $ac;
}

$grades = $db->query("SELECT gm.*, (SELECT COUNT(*) FROM staff s WHERE s.grade=gm.grade_name) AS staff_count FROM grade_master gm ORDER BY gm.sort_order, gm.grade_name")->fetchAll();

// ── 팀장 선정/해제 이력 테이블 ──
$db->exec("CREATE TABLE IF NOT EXISTS team_leader_log (
    log_id INT AUTO_INCREMENT PRIMARY KEY,
    team_id INT NOT NULL,
    team_name VARCHAR(100) DEFAULT '',
    staff_id INT DEFAULT NULL,
    staff_name VARCHAR(50) DEFAULT '',
    action_type VARCHAR(20) NOT NULL,
    changed_by INT NOT NULL,
    changed_by_name VARCHAR(50) DEFAULT '',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

// 팀장 이력 조회
$llPage = max(1, (int)($_GET['llp'] ?? 1));
$llPerPage = 15;
$llTotal = (int)$db->query("SELECT COUNT(*) FROM team_leader_log")->fetchColumn();
$llTotalPages = max(1, ceil($llTotal / $llPerPage));
$llOffset = ($llPage - 1) * $llPerPage;
$leaderLogs = $db->query("SELECT * FROM team_leader_log ORDER BY log_id DESC LIMIT $llPerPage OFFSET $llOffset")->fetchAll();

$activeTab = $_GET['tab'] ?? 'team';
?>

<div class="page-header">
    <h2>👥 인사관리</h2>
    <div class="breadcrumb">팀 관리 · 직급 관리</div>
</div>

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

<!-- 탭 전환 -->
<div style="display:flex;gap:0;margin-bottom:1.25rem;">
    <a href="?tab=team" class="btn <?= $activeTab==='team'?'btn-primary':'btn-outline' ?>" style="border-radius:var(--radius-sm) 0 0 var(--radius-sm);font-size:var(--fs-sm);">🏢 팀 관리</a>
    <a href="?tab=grade" class="btn <?= $activeTab==='grade'?'btn-primary':'btn-outline' ?>" style="border-radius:0;font-size:var(--fs-sm);">🎖️ 직급 관리</a>
    <a href="?tab=admin" class="btn <?= $activeTab==='admin'?'btn-primary':'btn-outline' ?>" style="border-radius:0 var(--radius-sm) var(--radius-sm) 0;font-size:var(--fs-sm);">🔑 관리자 선정</a>
</div>

<?php if ($activeTab === 'team'): ?>
<!-- ═══ 팀 관리 ═══ -->
<div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header"><h3>➕ 새 팀 생성</h3></div>
    <form method="POST" style="padding:1rem;display:flex;gap:0.75rem;align-items:flex-end;flex-wrap:wrap;">
        <input type="hidden" name="action" value="create_team">
        <div class="form-group" style="margin:0;flex:1;min-width:8rem;">
            <label style="font-size:var(--fs-xs);color:var(--text-tertiary);">팀 이름 *</label>
            <input type="text" name="team_name" required placeholder="예: 전략기획4팀" style="font-size:var(--fs-sm);">
        </div>
        <div class="form-group" style="margin:0;flex:2;min-width:10rem;">
            <label style="font-size:var(--fs-xs);color:var(--text-tertiary);">설명</label>
            <input type="text" name="description" placeholder="팀 설명 (선택)" style="font-size:var(--fs-sm);">
        </div>
        <button type="submit" class="btn btn-primary" style="height:2.25rem;">생성</button>
    </form>
</div>

<div class="card">
    <div class="card-header"><h3>📋 팀 목록 (<?= count($teams) ?>)</h3></div>
    <div class="table-wrap">
    <table>
        <thead>
            <tr><th style="width:3rem;">No</th><th>팀 이름</th><th>팀장</th><th>설명</th><th style="">인원</th><th>소속 직원</th><th style="">상태</th><th style="">관리</th></tr>
        </thead>
        <tbody>
        <?php foreach ($teams as $_ti => $t): ?>
        <tr style="<?= !$t['is_active']?'opacity:0.5;':'' ?>">
            <td style="color:var(--text-tertiary);font-size:var(--fs-xs);"><?= $_ti + 1 ?></td>
            <td><strong style="color:var(--text-primary);"><?= htmlspecialchars($t['team_name']) ?></strong></td>
            <td>
                <?php if ($t['leader_staff_id']): ?>
                    <span style="font-size:var(--fs-xs);font-weight:600;color:var(--accent-text);">👑 <?= htmlspecialchars($t['leader_name'] ?? '') ?></span>
                <?php else: ?>
                    <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">팀장 미배정</span>
                <?php endif; ?>
            </td>
            <td style="font-size:var(--fs-xs);color:var(--text-secondary);"><?= htmlspecialchars($t['description']) ?></td>
            <td style=""><span class="badge badge-info"><?= $t['member_count'] ?>명</span></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);max-width:15rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= htmlspecialchars($t['members'] ?? '-') ?></td>
            <td style="">
                <form method="POST" style="display:inline;">
                    <input type="hidden" name="action" value="toggle_team">
                    <input type="hidden" name="team_id" value="<?= $t['team_id'] ?>">
                    <button type="submit" class="btn btn-sm <?= $t['is_active']?'btn-success':'btn-outline' ?>" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;"><?= $t['is_active']?'활성':'비활성' ?></button>
                </form>
            </td>
            <td style="">
                <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;"
                    onclick='openTeamEdit(<?= json_encode(["team_id"=>$t["team_id"],"team_name"=>$t["team_name"],"description"=>$t["description"]],JSON_UNESCAPED_UNICODE) ?>)'>✏️</button>
                <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;"
                    onclick="openMemberManage('<?= htmlspecialchars($t['team_name'], ENT_QUOTES) ?>')">👥</button>
                <form method="POST" style="display:inline;" onsubmit="return confirm('정말 삭제하시겠습니까? 소속 직원에게 알림이 전송됩니다.')">
                    <input type="hidden" name="action" value="delete_team">
                    <input type="hidden" name="team_id" value="<?= $t['team_id'] ?>">
                    <input type="hidden" name="team_name" value="<?= htmlspecialchars($t['team_name']) ?>">
                    <button type="submit" class="btn btn-sm" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;color:var(--accent);">🗑️</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($teams)): ?>
        <tr><td colspan="8" style="padding:2rem;color:var(--text-tertiary);">등록된 팀이 없습니다</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>

<!-- 팀 수정 모달 -->
<div class="modal-overlay" id="teamEditModal">
    <div class="modal">
        <div class="modal-header">
            <h3>✏️ 팀 수정</h3>
            <button class="modal-close" onclick="document.getElementById('teamEditModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="update_team">
            <input type="hidden" name="team_id" id="te_id">
            <input type="hidden" name="old_name" id="te_old">
            <div class="form-group">
                <label>팀 이름</label>
                <input type="text" name="team_name" id="te_name" required>
            </div>
            <div class="form-group">
                <label>설명</label>
                <input type="text" name="description" id="te_desc">
            </div>
            <div class="alert alert-info" style="font-size:var(--fs-xs);margin-bottom:0.75rem;">ℹ 팀 이름 변경 시 해당 팀 소속 직원의 팀명도 자동으로 변경됩니다.</div>
            <button type="submit" class="btn btn-primary">수정 저장</button>
        </form>
    </div>
</div>

<!-- 팀원 관리 모달 (닫기 버튼 + 중복 숨김) -->
<div class="modal-overlay" id="memberModal">
    <div class="modal" style="max-width:700px;max-height:80vh;overflow-y:auto;">
        <div class="modal-header">
            <h3>👥 <span id="mm_team_name"></span> — 팀원 관리</h3>
            <button class="modal-close" onclick="closeMemberModal()">&times;</button>
        </div>
        <div id="mm_content" style="padding:1rem;">
            <div style="color:var(--text-tertiary);padding:2rem;">로딩 중...</div>
        </div>
        <div style="padding:0 1rem 1rem;">
            <button class="btn btn-outline" onclick="closeMemberModal()">닫기</button>
        </div>
    </div>
</div>

<?php
// 팀원 관리 AJAX 데이터 준비
$allStaff = $db->query("SELECT staff_id, name, grade, team FROM staff WHERE is_active=1 ORDER BY name")->fetchAll();
// 팀장 선정용: 팀별 멤버
$teamLeaderMap = [];
foreach ($teams as $t) { $teamLeaderMap[$t['team_id']] = (int)($t['leader_staff_id'] ?? 0); }
?>
<script>
var allStaff = <?= json_encode($allStaff, JSON_UNESCAPED_UNICODE) ?>;
var candidatesByTeam = <?= json_encode($candidatesByTeam, JSON_UNESCAPED_UNICODE) ?>;

function openTeamEdit(d) {
    document.getElementById('te_id').value = d.team_id;
    document.getElementById('te_old').value = d.team_name;
    document.getElementById('te_name').value = d.team_name;
    document.getElementById('te_desc').value = d.description || '';
    document.getElementById('teamEditModal').classList.add('show');
}

function openLeaderModal(d) {
    document.getElementById('lm_team_id').value = d.team_id;
    document.getElementById('lm_team_name').textContent = d.team_name;
    var sel = document.getElementById('lm_staff_select');
    sel.innerHTML = '<option value="">— 해제 (팀장 없음) —</option>';
    var members = allStaff.filter(function(s) { return s.team === d.team_name; });
    var candIds = (candidatesByTeam[d.team_name] || []).map(function(c) { return c.staff_id; });
    // 후보 먼저, 나머지 후
    var sorted = members.sort(function(a, b) {
        var aC = candIds.includes(a.staff_id) ? 0 : 1;
        var bC = candIds.includes(b.staff_id) ? 0 : 1;
        return aC - bC || a.name.localeCompare(b.name);
    });
    sorted.forEach(function(m) {
        var opt = document.createElement('option');
        opt.value = m.staff_id;
        var isCand = candIds.includes(m.staff_id);
        opt.textContent = (isCand ? '⭐ ' : '') + m.name + ' (' + m.grade + ')' + (isCand ? ' — 후보' : '');
        if (d.leader_staff_id && m.staff_id == d.leader_staff_id) opt.selected = true;
        sel.appendChild(opt);
    });
    if (members.length === 0) {
        var opt = document.createElement('option');
        opt.disabled = true; opt.textContent = '소속 직원이 없습니다';
        sel.appendChild(opt);
    }
    document.getElementById('leaderModal').classList.add('show');
}

function openMemberManage(teamName) {
    document.getElementById('mm_team_name').textContent = teamName;
    var members = allStaff.filter(s => s.team === teamName);
    var available = allStaff.filter(s => s.team !== teamName);

    var html = '<div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">';

    // 현재 팀원
    html += '<div>';
    html += '<div style="font-size:var(--fs-xs);color:var(--text-tertiary);padding:0.5rem 0;font-weight:600;">현재 팀원 (' + members.length + '명)</div>';
    if (members.length === 0) {
        html += '<div style="padding:1rem;color:var(--text-tertiary);font-size:var(--fs-xs);">팀원 없음</div>';
    }
    members.forEach(function(m) {
        html += '<div style="display:flex;align-items:center;justify-content:space-between;padding:0.35rem 0.5rem;border-bottom:1px solid rgba(255,255,255,0.04);">';
        html += '<span><strong>' + m.name + '</strong> <span class="badge badge-info" style="font-size:var(--fs-xs);">' + m.grade + '</span></span>';
        html += '<form method="POST" style="display:inline;"><input type="hidden" name="action" value="remove_member"><input type="hidden" name="staff_id" value="' + m.staff_id + '">';
        html += '<button type="submit" class="btn btn-sm" style="font-size:var(--fs-xs);color:var(--accent);padding:0.1rem 0.3rem;">제외</button></form>';
        html += '</div>';
    });
    html += '</div>';

    // 배정 가능 (이미 이 팀에 속한 인원은 숨김)
    html += '<div>';
    html += '<div style="font-size:var(--fs-xs);color:var(--text-tertiary);padding:0.5rem 0;font-weight:600;">배정 가능 직원 (' + available.length + '명)</div>';
    available.forEach(function(a) {
        html += '<div style="display:flex;align-items:center;justify-content:space-between;padding:0.35rem 0.5rem;border-bottom:1px solid rgba(255,255,255,0.04);">';
        html += '<span>' + a.name + ' <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">' + a.grade + (a.team ? ' · ' + a.team : '') + '</span></span>';
        html += '<form method="POST" style="display:inline;"><input type="hidden" name="action" value="assign_member"><input type="hidden" name="team_name" value="' + teamName + '"><input type="hidden" name="staff_id" value="' + a.staff_id + '">';
        var hasTeam = a.team && a.team !== '';
        html += '<button type="submit" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.1rem 0.3rem;"' + (hasTeam ? ' onclick="return confirm(\'이 직원은 현재 ' + a.team + '에 소속되어 있습니다. 해당 팀에서 제외하고 배정하시겠습니까?\')"' : '') + '>+ 배정</button></form>';
        html += '</div>';
    });
    html += '</div></div>';

    document.getElementById('mm_content').innerHTML = html;
    document.getElementById('memberModal').classList.add('show');
}

function closeMemberModal() {
    document.getElementById('memberModal').classList.remove('show');
}
</script>

<!-- 팀장 선정/변경 모달 -->
<div class="modal-overlay" id="leaderModal">
    <div class="modal">
        <div class="modal-header">
            <h3>👑 팀장 선정 — <span id="lm_team_name"></span></h3>
            <button class="modal-close" onclick="document.getElementById('leaderModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="set_team_leader">
            <input type="hidden" name="team_id" id="lm_team_id">
            <div class="form-group">
                <label>팀장 선택</label>
                <select name="leader_staff_id" id="lm_staff_select" style="width:100%;font-size:var(--fs-sm);"></select>
            </div>
            <div class="alert alert-info" style="font-size:var(--fs-xs);margin-bottom:0.75rem;">ℹ 기존 팀장이 있는 경우 자동으로 해제됩니다. 해당 팀 소속 직원만 선택 가능합니다.</div>
            <button type="submit" class="btn btn-primary">👑 팀장 선정</button>
        </form>
    </div>
</div>

<!-- 팀장 선정/해제 이력 -->
<div class="card" style="margin-top:1.25rem;">
    <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
        <h3>📝 팀장 선정/해제 이력 (<?= $llTotal ?>건)</h3>
        <?php if ($llTotal > 0): ?>
        <form method="POST" style="display:inline;" onsubmit="return confirm('전체 이력을 삭제하시겠습니까?')">
            <input type="hidden" name="action" value="delete_all_leader_logs">
            <button type="submit" class="btn btn-sm" style="font-size:var(--fs-xs);padding:0.25rem 0.6rem;color:var(--danger);">🗑️ 전체 삭제</button>
        </form>
        <?php endif; ?>
    </div>
    <?php if ($leaderLogs): ?>
    <div class="table-wrap"><table>
        <thead><tr><th style="width:3rem;">NO</th><th>팀</th><th>대상자</th><th>구분</th><th>처리자</th><th>일시</th><th>삭제</th></tr></thead>
        <tbody>
        <?php $llStartNo = $llTotal - $llOffset; foreach ($leaderLogs as $li => $ll): $lno = $llStartNo - $li; ?>
        <tr>
            <td style="color:var(--text-tertiary);font-size:var(--fs-xs);"><?= $lno ?></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($ll['team_name'] ?? '') ?></td>
            <td><strong><?= htmlspecialchars($ll['staff_name'] ?? '') ?></strong></td>
            <td><span class="badge <?= ($ll['action_type'] ?? '')==='선정'?'badge-success':'badge-warning' ?>" style="font-size:var(--fs-xs);"><?= $ll['action_type'] ?? '' ?></span></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($ll['changed_by_name'] ?? '') ?></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);white-space:nowrap;"><?= isset($ll['created_at']) ? date('Y-m-d H:i', strtotime($ll['created_at'])) : '-' ?></td>
            <td>
                <form method="POST" style="display:inline;" onsubmit="return confirm('이 이력을 삭제하시겠습니까?')">
                    <input type="hidden" name="action" value="delete_leader_log">
                    <input type="hidden" name="log_id" value="<?= $ll['log_id'] ?>">
                    <button type="submit" class="btn btn-sm" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;color:var(--text-tertiary);">🗑️</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table></div>
    <?php if ($llTotalPages > 1): ?>
    <div style="display:flex;justify-content:center;align-items:center;gap:0.5rem;padding:0.75rem;">
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">총 <?= $llTotal ?>건 (<?= $llPage ?>/<?= $llTotalPages ?>)</span>
        <?php if ($llPage>1): ?><a href="?tab=team&llp=<?= $llPage-1 ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">‹</a><?php endif; ?>
        <?php for($p=max(1,$llPage-2);$p<=min($llTotalPages,$llPage+2);$p++): ?>
        <a href="?tab=team&llp=<?= $p ?>" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);border-radius:4px;text-decoration:none;<?= $p===$llPage?'background:var(--accent);color:var(--bg-color);font-weight:700;':'color:var(--text-secondary);' ?>"><?= $p ?></a>
        <?php endfor; ?>
        <?php if ($llPage<$llTotalPages): ?><a href="?tab=team&llp=<?= $llPage+1 ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">›</a><?php endif; ?>
    </div>
    <?php endif; ?>
    <?php else: ?>
    <div style="padding:2rem;color:var(--text-tertiary);font-size:var(--fs-sm);">이력이 없습니다.</div>
    <?php endif; ?>
</div>

<?php elseif ($activeTab === 'grade'): ?>
<!-- ═══ 직급 관리 ═══ -->
<div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header"><h3>➕ 새 직급 생성</h3></div>
    <form method="POST" style="padding:1rem;display:flex;gap:0.75rem;align-items:flex-end;flex-wrap:wrap;">
        <input type="hidden" name="action" value="create_grade">
        <div class="form-group" style="margin:0;flex:1;min-width:8rem;">
            <label style="font-size:var(--fs-xs);color:var(--text-tertiary);">직급 이름 *</label>
            <input type="text" name="grade_name" required placeholder="예: 부장, 과장" style="font-size:var(--fs-sm);">
        </div>
        <div class="form-group" style="margin:0;width:6rem;">
            <label style="font-size:var(--fs-xs);color:var(--text-tertiary);">정렬 순서</label>
            <input type="number" name="sort_order" value="0" style="font-size:var(--fs-sm);">
        </div>
        <button type="submit" class="btn btn-primary" style="height:2.25rem;">생성</button>
    </form>
</div>

<div class="card">
    <div class="card-header"><h3>📋 직급 목록 (<?= count($grades) ?>)</h3></div>
    <div class="table-wrap">
    <table>
        <thead>
            <tr><th style="width:3rem;">No</th><th>직급 이름</th><th style="">정렬</th><th style="">사용 인원</th><th style="">관리</th></tr>
        </thead>
        <tbody>
        <?php foreach ($grades as $_gi => $g): ?>
        <tr>
            <td style="color:var(--text-tertiary);font-size:var(--fs-xs);"><?= $_gi + 1 ?></td>
            <td><strong style="color:var(--text-primary);"><?= htmlspecialchars($g['grade_name']) ?></strong></td>
            <td style="color:var(--text-tertiary);"><?= $g['sort_order'] ?></td>
            <td style=""><span class="badge badge-info"><?= $g['staff_count'] ?>명</span></td>
            <td style="">
                <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;"
                    onclick='openGradeEdit(<?= json_encode(["grade_id"=>$g["grade_id"],"grade_name"=>$g["grade_name"],"sort_order"=>$g["sort_order"]],JSON_UNESCAPED_UNICODE) ?>)'>✏️</button>
                <form method="POST" style="display:inline;" onsubmit="return confirm('정말 삭제하시겠습니까?')">
                    <input type="hidden" name="action" value="delete_grade">
                    <input type="hidden" name="grade_id" value="<?= $g['grade_id'] ?>">
                    <input type="hidden" name="grade_name" value="<?= htmlspecialchars($g['grade_name']) ?>">
                    <button type="submit" class="btn btn-sm" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;color:var(--accent);">🗑️</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($grades)): ?>
        <tr><td colspan="5" style="padding:2rem;color:var(--text-tertiary);">등록된 직급이 없습니다</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>

<!-- 직급 수정 모달 -->
<div class="modal-overlay" id="gradeEditModal">
    <div class="modal">
        <div class="modal-header">
            <h3>✏️ 직급 수정</h3>
            <button class="modal-close" onclick="document.getElementById('gradeEditModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="update_grade">
            <input type="hidden" name="grade_id" id="ge_id">
            <input type="hidden" name="old_grade_name" id="ge_old">
            <div class="form-group">
                <label>직급 이름</label>
                <input type="text" name="grade_name" id="ge_name" required>
            </div>
            <div class="form-group">
                <label>정렬 순서</label>
                <input type="number" name="sort_order" id="ge_order">
            </div>
            <div class="alert alert-info" style="font-size:var(--fs-xs);margin-bottom:0.75rem;">ℹ 직급 이름 변경 시 해당 직급의 모든 직원 정보가 자동으로 변경됩니다.</div>
            <button type="submit" class="btn btn-primary">수정 저장</button>
        </form>
    </div>
</div>

<script>
function openGradeEdit(d) {
    document.getElementById('ge_id').value = d.grade_id;
    document.getElementById('ge_old').value = d.grade_name;
    document.getElementById('ge_name').value = d.grade_name;
    document.getElementById('ge_order').value = d.sort_order || 0;
    document.getElementById('gradeEditModal').classList.add('show');
}
</script>

<?php elseif ($activeTab === 'admin'): ?>
<!-- ═══ 직급 변경 + 관리자 선정 (분리) ═══ -->
<?php
$grades = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
if (!$grades) $grades = ['사원','선임','책임','수석','팀장'];

// POST: 직급 변경
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action']??'') === 'change_grade') {
    $targetStaffId = (int)($_POST['staff_id'] ?? 0);
    $newGrade = $_POST['new_grade'] ?? '';
    if ($targetStaffId && $newGrade) {
        $oldGrade = $db->query("SELECT grade FROM staff WHERE staff_id={$targetStaffId}")->fetchColumn();
        $db->prepare("UPDATE staff SET grade=? WHERE staff_id=?")->execute([$newGrade, $targetStaffId]);
        $targetName = $db->query("SELECT name FROM staff WHERE staff_id={$targetStaffId}")->fetchColumn() ?: '';
        writeAudit($db, 'staff', $targetStaffId, 'UPDATE', ['grade'=>$newGrade, 'target_name'=>$targetName], ['grade'=>$oldGrade]);
        $message = '직급이 변경되었습니다.';
    }
}
// POST: 관리자 선정 (직급과 별개)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action']??'') === 'set_manager') {
    $targetUserId = (int)($_POST['user_id'] ?? 0);
    $setAs = $_POST['set_as'] ?? '';
    if ($targetUserId && in_array($setAs, ['manager','ceo','sysadmin','staff'])) {
        $oldRole = $db->query("SELECT user_role FROM user_account WHERE user_id={$targetUserId}")->fetchColumn();
        $targetName = $db->query("SELECT s.name FROM user_account ua JOIN staff s ON ua.staff_id=s.staff_id WHERE ua.user_id={$targetUserId}")->fetchColumn() ?: '';
        $db->prepare("UPDATE user_account SET user_role=? WHERE user_id=?")->execute([$setAs, $targetUserId]);
        $targetStaffId = $db->query("SELECT staff_id FROM user_account WHERE user_id={$targetUserId}")->fetchColumn();
        syncTeamLeaderOnRoleChange($db, $targetStaffId, $oldRole, $setAs);
        writeAudit($db, 'user_account', $targetUserId, 'ROLE_CHANGE', ['new_role'=>$setAs, 'target_name'=>$targetName], ['old_role'=>$oldRole]);
        $message = ($setAs === 'staff') ? '관리자 해제되었습니다.' : '관리자로 선정되었습니다.';
    }
}

$allUsers = $db->query("SELECT ua.user_id, ua.login_id, ua.user_role, ua.staff_id, s.name, s.grade, s.team
    FROM user_account ua JOIN staff s ON ua.staff_id=s.staff_id
    ORDER BY FIELD(ua.user_role,'sysadmin','ceo','manager','team_leader','staff'), s.name")->fetchAll();
$managers = array_filter($allUsers, fn($u) => in_array($u['user_role'], ['manager','ceo','sysadmin']));
?>

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

<!-- 직급 변경 -->
<div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header"><h3>📋 직급 변경</h3><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">인사관리 직급관리의 직급 목록과 연동</div></div>
    <div class="table-wrap"><table>
        <thead><tr><th>No</th><th>이름</th><th>아이디</th><th>현재 직급</th><th>팀</th><th>역할</th><th>직급 변경</th></tr></thead>
        <tbody>
        <?php foreach ($allUsers as $ri => $u): ?>
        <tr>
            <td style="color:var(--text-tertiary);font-size:var(--fs-xs);"><?= $ri+1 ?></td>
            <td><strong><?= htmlspecialchars($u['name']) ?></strong></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($u['login_id']) ?></td>
            <td><span class="badge badge-info"><?= $u['grade'] ?></span></td>
            <td><?= htmlspecialchars($u['team']) ?></td>
            <td><span class="badge <?= getRoleBadgeClass($u['user_role']) ?>"><?= getRoleLabel($u['user_role']) ?></span></td>
            <td>
                <form method="POST" style="display:flex;gap:0.25rem;align-items:center;" onsubmit="return confirm('직급을 변경하시겠습니까?')">
                    <input type="hidden" name="action" value="change_grade">
                    <input type="hidden" name="staff_id" value="<?= $u['staff_id'] ?>">
                    <select name="new_grade" class="dash-filter" style="width:7rem;font-size:var(--fs-xs);">
                        <?php foreach ($grades as $g): ?>
                        <option value="<?= htmlspecialchars($g) ?>" <?= $u['grade']===$g?'selected':'' ?>><?= htmlspecialchars($g) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="btn btn-sm btn-primary" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;">변경</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table></div>
</div>

<!-- 관리자 선정 (직급과 별개) -->
<div class="card">
    <div class="card-header"><h3>🔑 관리자 선정</h3><div style="font-size:var(--fs-xs);color:var(--text-tertiary);">직급과 별개로 관리자/대표 권한 부여</div></div>
    
    <?php if ($managers): ?>
    <div style="padding:0.75rem 1rem;border-bottom:1px solid var(--border);">
        <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.5rem;">현재 관리자/대표</div>
        <div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
        <?php foreach ($managers as $mg): ?>
            <div style="display:flex;align-items:center;gap:0.35rem;background:rgba(var(--accent-rgb),0.06);padding:0.25rem 0.5rem;border-radius:var(--radius-sm);">
                <strong style="font-size:var(--fs-xs);"><?= htmlspecialchars($mg['name']) ?></strong>
                <span class="badge <?= $mg['user_role']==='ceo'?'badge-danger':'badge-warning' ?>" style="font-size:var(--fs-xs);"><?= getRoleLabel($mg['user_role']) ?></span>
                <span style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $mg['grade'] ?> · <?= $mg['team'] ?></span>
                <form method="POST" style="display:inline;" onsubmit="return confirm('관리자 해제하시겠습니까?')">
                    <input type="hidden" name="action" value="set_manager"><input type="hidden" name="user_id" value="<?= $mg['user_id'] ?>"><input type="hidden" name="set_as" value="staff">
                    <button type="submit" style="background:none;border:none;color:var(--danger);font-size:var(--fs-xs);cursor:pointer;padding:0 0.25rem;">해제</button>
                </form>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="table-wrap"><table>
        <thead><tr><th>No</th><th>이름</th><th>직급</th><th>팀</th><th>현재</th><th>관리자 선정</th></tr></thead>
        <tbody>
        <?php $mi=0; foreach ($allUsers as $u): if (in_array($u['user_role'],['manager','ceo','sysadmin'])) continue; $mi++; ?>
        <tr>
            <td style="color:var(--text-tertiary);font-size:var(--fs-xs);"><?= $mi ?></td>
            <td><strong><?= htmlspecialchars($u['name']) ?></strong></td>
            <td><span class="badge badge-info"><?= $u['grade'] ?></span></td>
            <td><?= htmlspecialchars($u['team']) ?></td>
            <td><span class="badge <?= getRoleBadgeClass($u['user_role']) ?>"><?= getRoleLabel($u['user_role']) ?></span></td>
            <td>
                <form method="POST" style="display:flex;gap:0.25rem;align-items:center;" onsubmit="return confirm('관리자로 선정하시겠습니까?')">
                    <input type="hidden" name="action" value="set_manager">
                    <input type="hidden" name="user_id" value="<?= $u['user_id'] ?>">
                    <select name="set_as" class="dash-filter" style="width:8rem;font-size:var(--fs-xs);">
                        <option value="manager">관리자</option>
                        <option value="ceo">대표</option>
                        <option value="sysadmin">시스템관리자</option>
                    </select>
                    <button type="submit" class="btn btn-sm btn-primary" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;">선정</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table></div>
</div>
<?php endif; ?>

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