<?php
// pages/admin_accounts.php — 계정 관리 (시스템관리자 전용)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/header.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $userId = (int)($_POST['user_id'] ?? 0);

    if ($action === 'approve_user') {
        $assignRole = $_POST['assign_role'] ?? 'staff';
        $db->prepare("UPDATE user_account SET approval_status='승인', is_active=1, user_role=?, approved_by=?, approved_at=NOW() WHERE user_id=?")
           ->execute([$assignRole, $user['user_id'], $userId]);
        $staffId = $db->query("SELECT staff_id FROM user_account WHERE user_id={$userId}")->fetchColumn();
        $staffRole = ['staff'=>'직원','team_leader'=>'팀장','manager'=>'관리자','ceo'=>'대표','sysadmin'=>'시스템관리자'][$assignRole] ?? '직원';
        $db->prepare("UPDATE staff SET is_active=1, role=?, memo='' WHERE staff_id=?")->execute([$staffRole, $staffId]);
        writeAudit($db, 'user_account', $userId, 'APPROVE', ['role' => $assignRole]);
        $message = '가입이 승인되었습니다.';
    }

    if ($action === 'reject_user') {
        $reason = trim($_POST['reject_reason'] ?? '');
        $db->prepare("UPDATE user_account SET approval_status='반려', reject_reason=? WHERE user_id=?")->execute([$reason, $userId]);
        writeAudit($db, 'user_account', $userId, 'REJECT', ['reason' => $reason]);
        $message = '가입이 반려되었습니다.';
    }

    if ($action === 'edit_account') {
        $newRole = $_POST['new_role'] ?? 'staff';
        $editActive = (int)($_POST['edit_active'] ?? 1);
        $editEmail = trim($_POST['edit_email'] ?? '');
        $editPhone = trim($_POST['edit_phone'] ?? '');
        $editLoginId = trim($_POST['edit_login_id'] ?? '');
        $editName = trim($_POST['edit_name'] ?? '');
        $editGrade = trim($_POST['edit_grade'] ?? '');
        $editTeam = trim($_POST['edit_team'] ?? '');
        $editHireDate = trim($_POST['edit_hire_date'] ?? '');

        $oldRole = $db->query("SELECT user_role FROM user_account WHERE user_id={$userId}")->fetchColumn();
        $staffId = $db->query("SELECT staff_id FROM user_account WHERE user_id={$userId}")->fetchColumn();

        // 아이디 변경 (중복 체크)
        if ($editLoginId) {
            $dup = $db->prepare("SELECT COUNT(*) FROM user_account WHERE login_id=? AND user_id!=?");
            $dup->execute([$editLoginId, $userId]);
            if ($dup->fetchColumn() > 0) {
                $error = '이미 사용 중인 아이디입니다.';
            } else {
                $db->prepare("UPDATE user_account SET login_id=? WHERE user_id=?")->execute([$editLoginId, $userId]);
            }
        }

        if (!$error) {
            // user_account 업데이트
            $db->prepare("UPDATE user_account SET user_role=?, is_active=? WHERE user_id=?")->execute([$newRole, $editActive, $userId]);
            syncTeamLeaderOnRoleChange($db, $staffId, $oldRole, $newRole);
            $staffRole = ['staff'=>'직원','team_leader'=>'팀장','manager'=>'관리자','ceo'=>'대표','sysadmin'=>'시스템관리자'][$newRole] ?? '직원';
            // staff 테이블 전체 업데이트
            $staffUpdate = "UPDATE staff SET role=?, email=?, phone=?";
            $staffParams = [$staffRole, $editEmail, $editPhone];
            if ($editName) { $staffUpdate .= ", name=?"; $staffParams[] = $editName; }
            if ($editGrade) { $staffUpdate .= ", grade=?"; $staffParams[] = $editGrade; }
            if ($editTeam) { $staffUpdate .= ", team=?"; $staffParams[] = $editTeam; }
            if ($editHireDate) { $staffUpdate .= ", hire_date=?"; $staffParams[] = $editHireDate; }
            $staffUpdate .= " WHERE staff_id=?";
            $staffParams[] = $staffId;
            $db->prepare($staffUpdate)->execute($staffParams);
            writeAudit($db, 'user_account', $userId, 'ACCOUNT_EDIT', ['new_role'=>$newRole,'is_active'=>$editActive,'login_id'=>$editLoginId,'name'=>$editName,'email'=>$editEmail,'phone'=>$editPhone,'grade'=>$editGrade,'team'=>$editTeam], ['old_role'=>$oldRole]);
            $message = '계정 정보가 수정되었습니다.';
        }
    }
    if ($action === 'change_role') {
        $newRole = $_POST['new_role'];
        $oldRole = $db->query("SELECT user_role FROM user_account WHERE user_id={$userId}")->fetchColumn();
        $db->prepare("UPDATE user_account SET user_role=? WHERE user_id=?")->execute([$newRole, $userId]);
        $staffId = $db->query("SELECT staff_id FROM user_account WHERE user_id={$userId}")->fetchColumn();
        syncTeamLeaderOnRoleChange($db, $staffId, $oldRole, $newRole);
        $staffRole = ['staff'=>'직원','team_leader'=>'팀장','manager'=>'관리자','ceo'=>'대표','sysadmin'=>'시스템관리자'][$newRole] ?? '직원';
        $db->prepare("UPDATE staff SET role=? WHERE staff_id=?")->execute([$staffRole, $staffId]);
        writeAudit($db, 'user_account', $userId, 'ROLE_CHANGE', ['new_role'=>$newRole], ['old_role'=>$oldRole]);
        $message = '역할이 변경되었습니다.';
    }

    if ($action === 'issue_temp_pw') {
        $tempPw = generateTempPassword();
        $hash = password_hash($tempPw, PASSWORD_DEFAULT);
        $db->prepare("UPDATE user_account SET password_hash=?, must_change_pw=1, temp_pw_issued_at=NOW(), temp_pw_issued_by=? WHERE user_id=?")
           ->execute([$hash, $user['user_id'], $userId]);
        writeAudit($db, 'user_account', $userId, 'PW_RESET', ['issued_by' => $user['name']]);
        $loginId = $db->query("SELECT login_id FROM user_account WHERE user_id={$userId}")->fetchColumn();
        $tempPwResult = ['login_id' => $loginId, 'temp_pw' => $tempPw];
    }

    if ($action === 'toggle_active') {
        $db->prepare("UPDATE user_account SET is_active = NOT is_active WHERE user_id=?")->execute([$userId]);
        $message = '계정 상태가 변경되었습니다.';
    }

    // 기존 직원에게 계정 발급
    if ($action === 'create_account') {
        $staffId = (int)($_POST['staff_id'] ?? 0);
        $newLoginId = trim($_POST['new_login_id'] ?? '');
        $assignRole = $_POST['assign_role'] ?? 'staff';

        if (!$newLoginId || strlen($newLoginId) < 3) {
            $error = '아이디는 3자 이상이어야 합니다.';
        } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $newLoginId)) {
            $error = '아이디는 영문/숫자/밑줄만 사용 가능합니다.';
        } else {
            $chk = $db->prepare("SELECT COUNT(*) FROM user_account WHERE login_id = ?");
            $chk->execute([$newLoginId]);
            if ($chk->fetchColumn() > 0) {
                $error = '이미 사용 중인 아이디입니다.';
            } else {
                $tempPw = generateTempPassword();
                $hash = password_hash($tempPw, PASSWORD_DEFAULT);
                $db->prepare("INSERT INTO user_account (staff_id, login_id, password_hash, user_role, is_active, approval_status, must_change_pw, approved_by, approved_at)
                    VALUES (?,?,?,?,1,'승인',1,?,NOW())")
                   ->execute([$staffId, $newLoginId, $hash, $assignRole, $user['user_id']]);
                // staff 테이블도 활성화 + 역할 갱신
                $staffRole = ['staff'=>'직원','team_leader'=>'팀장','manager'=>'관리자','ceo'=>'대표','sysadmin'=>'시스템관리자'][$assignRole] ?? '직원';
                $db->prepare("UPDATE staff SET is_active=1, role=? WHERE staff_id=?")->execute([$staffRole, $staffId]);
                writeAudit($db, 'user_account', $staffId, 'APPROVE', ['login_id'=>$newLoginId, 'role'=>$assignRole]);
                $tempPwResult = ['login_id' => $newLoginId, 'temp_pw' => $tempPw];
                $message = '계정이 생성되었습니다.';
            }
        }
    }

    // 계정 삭제 (시스템관리자 전용 — 본인 계정 삭제 불가, 모든 흔적 완전 삭제)
    if ($action === 'delete_account') {
        if ($userId == ($_SESSION['user_id'] ?? 0)) {
            $error = '본인 계정은 삭제할 수 없습니다.';
        } else {
            $delInfo = $db->prepare("SELECT u.login_id, s.name, u.staff_id FROM user_account u LEFT JOIN staff s ON u.staff_id=s.staff_id WHERE u.user_id=?");
            $delInfo->execute([$userId]); $delRow = $delInfo->fetch();
            if ($delRow) {
                $sid = $delRow['staff_id'];
                $uid = $userId;
                writeAudit($db, 'user_account', $uid, 'DELETE', ['login_id'=>$delRow['login_id'],'name'=>$delRow['name']??'']);

                // ── 모든 관련 데이터 완전 삭제 ──
                $delTables = [
                    "DELETE FROM sales WHERE staff_id=?",
                    "DELETE FROM kpi_target WHERE staff_id=?",
                    "DELETE FROM performance_score WHERE staff_id=?",
                    "DELETE FROM evaluation WHERE staff_id=?",
                    "DELETE FROM eval_notification WHERE staff_id=?",
                    "DELETE FROM incentive_review WHERE staff_id=?",
                    "DELETE FROM incentive_review_log WHERE staff_id=?",
                    "DELETE FROM approval_flow WHERE staff_id=?",
                    "DELETE FROM approval_review_log WHERE staff_id=?",
                    "DELETE FROM team_leader_candidate WHERE staff_id=?",
                    "DELETE FROM team_leader_log WHERE staff_id=?",
                    "DELETE FROM notifications WHERE staff_id=?",
                ];
                foreach ($delTables as $sql) {
                    try { $db->prepare($sql)->execute([$sid]); } catch(Exception $e) {}
                }
                // user_id 기반 삭제
                $delByUid = [
                    "DELETE FROM user_theme WHERE user_id=?",
                    "DELETE FROM user_images WHERE user_id=?",
                    "DELETE FROM audit_log WHERE target_id=?",
                ];
                foreach ($delByUid as $sql) {
                    try { $db->prepare($sql)->execute([$uid]); } catch(Exception $e) {}
                }
                // team_master 팀장 해제
                try { $db->prepare("UPDATE team_master SET leader_staff_id=NULL WHERE leader_staff_id=?")->execute([$sid]); } catch(Exception $e) {}
                // 프로필 이미지 폴더 삭제
                $themeDir = __DIR__ . '/../assets/theme/' . $uid;
                if (is_dir($themeDir)) {
                    array_map('unlink', glob($themeDir . '/*'));
                    @rmdir($themeDir);
                }
                // 최종: 계정 + 직원 레코드 삭제
                $db->prepare("DELETE FROM user_account WHERE user_id=?")->execute([$uid]);
                $db->prepare("DELETE FROM staff WHERE staff_id=?")->execute([$sid]);
                $message = ($delRow['name'] ?? $delRow['login_id']) . ' 계정 및 모든 관련 데이터가 완전 삭제되었습니다.';
            }
        }
    }

    // 직원 기록 완전 삭제 (계정 없는 고아 직원용)
    if ($action === 'delete_staff') {
        $staffId = (int)($_POST['staff_id'] ?? 0);
        if ($staffId) {
            $sInfo = $db->prepare("SELECT name FROM staff WHERE staff_id=?"); $sInfo->execute([$staffId]); $sName = $sInfo->fetchColumn();
            // 연관 데이터 전체 삭제
            $delTables = [
                "DELETE FROM sales WHERE staff_id=?",
                "DELETE FROM kpi_target WHERE staff_id=?",
                "DELETE FROM performance_score WHERE staff_id=?",
                "DELETE FROM evaluation WHERE target_staff_id=?",
                "DELETE FROM eval_notification WHERE target_staff_id=?",
                "DELETE FROM incentive_review WHERE staff_id=?",
                "DELETE FROM incentive_review_log WHERE staff_id=?",
                "DELETE FROM approval_flow WHERE staff_id=?",
                "DELETE FROM approval_review_log WHERE staff_id=?",
                "DELETE FROM team_leader_candidate WHERE staff_id=?",
                "DELETE FROM team_leader_log WHERE staff_id=?",
                "DELETE FROM notifications WHERE staff_id=?",
            ];
            foreach ($delTables as $sql) {
                try { $db->prepare($sql)->execute([$staffId]); } catch(Exception $e) {}
            }
            try { $db->prepare("UPDATE team_master SET leader_staff_id=NULL WHERE leader_staff_id=?")->execute([$staffId]); } catch(Exception $e) {}
            $db->prepare("DELETE FROM staff WHERE staff_id=?")->execute([$staffId]);
            $message = ($sName ?: "staff_id={$staffId}") . ' 직원 기록 및 모든 관련 데이터가 완전 삭제되었습니다.';
        }
    }
}

$pending = $db->query("
    SELECT u.*, s.name, s.grade, s.team, s.email, s.phone, s.hire_date
    FROM user_account u JOIN staff s ON u.staff_id = s.staff_id
    WHERE u.approval_status = '대기' ORDER BY u.created_at ASC
")->fetchAll();

// staff 테이블에 없는 계정(고아 계정) 자동 정리
$db->exec("DELETE FROM user_account WHERE staff_id NOT IN (SELECT staff_id FROM staff)");

// 계정 미발급 직원 조회 (자동 temp 생성 안 함 — 계정관리에서 수동 발급)
$unlinked = $db->query("
    SELECT s.* FROM staff s
    LEFT JOIN user_account u ON s.staff_id = u.staff_id
    WHERE u.user_id IS NULL
    ORDER BY s.team, s.name
")->fetchAll();

// 직급/팀 마스터
$gradeList = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
$teamList = $db->query("SELECT team_name FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
if (!$gradeList) $gradeList = [];
if (!$teamList) $teamList = [];

// 필터
$fGrade = $_GET['grade'] ?? '';
$fTeam = $_GET['team'] ?? '';
$fRole = $_GET['role'] ?? '';

$accSql = "SELECT u.*, s.name, s.grade, s.team, s.email, s.phone, s.hire_date
    FROM user_account u JOIN staff s ON u.staff_id = s.staff_id
    WHERE u.approval_status = '승인'";
$accParams = [];
if ($fGrade) { $accSql .= " AND s.grade = ?"; $accParams[] = $fGrade; }
if ($fTeam) { $accSql .= " AND s.team = ?"; $accParams[] = $fTeam; }
if ($fRole) { $accSql .= " AND u.user_role = ?"; $accParams[] = $fRole; }
$accSql .= " ORDER BY FIELD(u.user_role,'sysadmin','ceo','manager','team_leader','staff'), s.name";
$accStmt = $db->prepare($accSql); $accStmt->execute($accParams);
$accounts = $accStmt->fetchAll();

// 전체 계정 (필터 없이 — 통계용)
$allAccounts = $db->query("SELECT u.user_role, s.grade, s.team FROM user_account u JOIN staff s ON u.staff_id=s.staff_id WHERE u.approval_status='승인'")->fetchAll();
$teamStats = []; $gradeStats = []; $roleStats = [];
foreach ($allAccounts as $aa) {
    $t = $aa['team'] ?: '미배정'; $teamStats[$t] = ($teamStats[$t] ?? 0) + 1;
    $g = $aa['grade'] ?: '미지정'; $gradeStats[$g] = ($gradeStats[$g] ?? 0) + 1;
    $r = $aa['user_role']; $roleStats[$r] = ($roleStats[$r] ?? 0) + 1;
}
?>

<div class="page-header">
    <h2>🔑 계정 관리</h2>
    <div class="breadcrumb">가입 승인 · 역할 부여 · 비밀번호 관리</div>
</div>

<?php if ($message): ?><div class="alert alert-success"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<?php if ($tempPwResult): ?>
<div class="alert alert-warning" style="font-size:var(--fs-sm);">
    <div style="display:flex;align-items:center;gap:1.5rem;flex-wrap:wrap;">
        <strong>🔒 임시 비밀번호 발급 완료</strong>
        <span>아이디: <strong><?= htmlspecialchars($tempPwResult['login_id']) ?></strong></span>
        <span>임시 비밀번호: <strong style="font-family:monospace;font-size:1rem;color:var(--accent-text);letter-spacing:2px;background:rgba(0,0,0,0.15);padding:0.125rem 0.5rem;border-radius:4px;"><?= htmlspecialchars($tempPwResult['temp_pw']) ?></strong></span>
    </div>
    <div style="margin-top:0.375rem;font-size:var(--fs-xs);opacity:0.85;">⚠ 이 비밀번호는 이 화면에서만 확인 가능합니다. 사용자에게 전달 후 변경하도록 안내해주세요.</div>
</div>
<?php endif; ?>

<?php if (!empty($pending)): ?>
<div class="card" style="">
    <div class="card-header"><h3>⏳ 가입 승인 대기 (<?= count($pending) ?>건)</h3></div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>신청일</th><th>이름</th><th>아이디</th><th>직급</th><th>팀</th><th>이메일</th><th>연락처</th><th>처리</th></tr></thead>
            <tbody>
                <?php foreach ($pending as $p): ?>
                <tr>
                    <td style="font-size:var(--fs-xs);"><?= date('Y-m-d H:i', strtotime($p['created_at'])) ?></td>
                    <td><strong><?= htmlspecialchars($p['name']) ?></strong></td>
                    <td><?= htmlspecialchars($p['login_id']) ?></td>
                    <td><span class="badge badge-info"><?= $p['grade'] ?></span></td>
                    <td><?= htmlspecialchars($p['team']) ?></td>
                    <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($p['email']) ?></td>
                    <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($p['phone']) ?></td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-success" onclick="openApprove(<?= $p['user_id'] ?>,'<?= htmlspecialchars($p['name']) ?>')">승인</button>
                            <button class="btn btn-sm btn-danger" onclick="openReject(<?= $p['user_id'] ?>,'<?= htmlspecialchars($p['name']) ?>')">반려</button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<div class="stat-grid">
    <?php
    $rc = array_fill_keys(['sysadmin','ceo','manager','team_leader','staff'], 0);
    foreach ($accounts as $a) $rc[$a['user_role']]++;
    ?>
    <div class="stat-card red"><div class="stat-label">시스템관리자</div><div class="stat-value"><?= $rc['sysadmin'] ?></div></div>
    <div class="stat-card yellow"><div class="stat-label">대표</div><div class="stat-value"><?= $rc['ceo'] ?></div></div>
    <div class="stat-card green"><div class="stat-label">관리자</div><div class="stat-value"><?= $rc['manager'] ?></div></div>
    <div class="stat-card blue"><div class="stat-label">팀장</div><div class="stat-value"><?= $rc['team_leader'] ?></div></div>
    <div class="stat-card blue"><div class="stat-label">직원</div><div class="stat-value"><?= $rc['staff'] ?></div></div>
</div>

<?php if ($unlinked): ?>
<div class="card" style="border:1px solid rgba(255,152,0,0.2);margin-bottom:1.25rem;">
    <div class="card-header" style="background:rgba(255,152,0,0.06);"><h3>⚠ 계정 미발급 직원 (<?= count($unlinked) ?>명)</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></tr></thead>
        <tbody>
        <?php foreach ($unlinked as $ui => $ul): ?>
        <tr style="<?= $ul['is_active'] ? '' : 'opacity:0.5;' ?>">
            <td><?= $ui+1 ?></td>
            <td><strong><?= htmlspecialchars($ul['name']) ?></strong></td>
            <td><span class="badge badge-info"><?= htmlspecialchars($ul['grade']) ?></span></td>
            <td><?= htmlspecialchars($ul['team']) ?></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($ul['email'] ?? '-') ?></td>
            <td style="font-size:var(--fs-xs);"><?= $ul['hire_date'] ?? '-' ?></td>
            <td><span class="badge <?= $ul['is_active'] ? 'badge-warning' : 'badge-danger' ?>"><?= $ul['is_active'] ? '활성(계정없음)' : '비활성' ?></span></td>
            <td>
                <div class="btn-group">
                    <button class="btn btn-sm btn-primary" onclick="openCreate(<?= $ul['staff_id'] ?>,'<?= htmlspecialchars($ul['name'],ENT_QUOTES) ?>')">계정 발급</button>
                    <form method="POST" style="display:inline;">
                        <input type="hidden" name="action" value="delete_staff">
                        <input type="hidden" name="staff_id" value="<?= $ul['staff_id'] ?>">
                        <button type="submit" class="btn btn-sm btn-outline" style="color:var(--danger);border-color:var(--danger);"
                            onclick="return confirm('⚠ <?= htmlspecialchars($ul['name']) ?> 직원 기록을 완전 삭제하시겠습니까?\n\n매출·평가·인센티브 등 모든 관련 데이터가 삭제됩니다.\n이 작업은 되돌릴 수 없습니다.')">완전 삭제</button>
                    </form>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header"><h3>전체 계정 (<?= count($accounts) ?>개<?= ($fGrade||$fTeam||$fRole) ? ' · 필터 적용' : '' ?>)</h3></div>

    <!-- 필터 -->
    <div style="padding:0.75rem 1rem;border-bottom:1px solid var(--border);">
        <form method="GET" style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
            <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">직급:</span>
            <select name="grade" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
                <option value="">전체</option>
                <?php foreach ($gradeList as $g): ?><option value="<?= htmlspecialchars($g) ?>" <?= $fGrade===$g?'selected':'' ?>><?= htmlspecialchars($g) ?></option><?php endforeach; ?>
            </select>
            <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">팀:</span>
            <select name="team" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
                <option value="">전체</option>
                <?php foreach ($teamList as $t): ?><option value="<?= htmlspecialchars($t) ?>" <?= $fTeam===$t?'selected':'' ?>><?= htmlspecialchars($t) ?></option><?php endforeach; ?>
            </select>
            <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">역할:</span>
            <select name="role" onchange="this.form.submit()" class="dash-filter" style="width:9rem;">
                <option value="">전체</option>
                <option value="sysadmin" <?= $fRole==='sysadmin'?'selected':'' ?>>시스템관리자</option>
                <option value="ceo" <?= $fRole==='ceo'?'selected':'' ?>>대표</option>
                <option value="manager" <?= $fRole==='manager'?'selected':'' ?>>관리자</option>
                <option value="team_leader" <?= $fRole==='team_leader'?'selected':'' ?>>팀장</option>
                <option value="staff" <?= $fRole==='staff'?'selected':'' ?>>직원</option>
            </select>
            <?php if ($fGrade||$fTeam||$fRole): ?><a href="?<?= '' ?>" style="font-size:var(--fs-xs);color:var(--accent);">초기화</a><?php endif; ?>
            <span style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-left:auto;"><?= count($allAccounts) ?>명 중 <?= count($accounts) ?>명 표시</span>
        </form>
    </div>

    <!-- 통계: 팀별 원형 + 직급별 바 -->
    <div style="padding:1rem;border-bottom:1px solid var(--border);display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;">
        <div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.5rem;">👥 팀별 인원</div>
            <div style="display:flex;align-items:center;gap:1rem;">
                <div style="width:10rem;height:10rem;flex-shrink:0;"><canvas id="accTeamPie"></canvas></div>
                <div style="font-size:var(--fs-xs);color:var(--text-secondary);line-height:1.8;">
                    <?php foreach ($teamStats as $tn => $tc): ?>
                    <div><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-right:4px;"></span><?= htmlspecialchars($tn) ?>: <strong><?= $tc ?></strong>명</div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <div>
            <div style="font-size:var(--fs-xs);color:var(--text-tertiary);font-weight:600;margin-bottom:0.5rem;">📊 직급별 인원</div>
            <div style="max-height:10rem;"><canvas id="accGradeBar"></canvas></div>
        </div>
    </div>
    <div class="alert alert-info">ℹ 비밀번호는 암호화 저장 — 관리자도 확인 불가. 분실 시 "임시PW" 발급.</div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>아이디</th><th>이름</th><th>직급</th><th>팀</th><th>역할</th><th>상태</th><th>최종 로그인</th><th>액션</th></tr></thead>
            <tbody>
                <?php foreach ($accounts as $a): ?>
                <tr style="<?= !$a['is_active'] ? 'opacity:0.5;' : '' ?>">
                    <td><strong><?= htmlspecialchars($a['login_id']) ?></strong></td>
                    <td><?= htmlspecialchars($a['name']) ?></td>
                    <td><span class="badge badge-info"><?= $a['grade'] ?></span></td>
                    <td><?= htmlspecialchars($a['team']) ?></td>
                    <td><span class="badge <?= getRoleBadgeClass($a['user_role']) ?>"><?= getRoleLabel($a['user_role']) ?></span></td>
                    <td>
                        <?= $a['is_active'] ? '<span class="badge badge-success">활성</span>' : '<span class="badge badge-gray">비활성</span>' ?>
                        <?= $a['must_change_pw'] ? '<span class="badge badge-warning">임시PW</span>' : '' ?>
                    </td>
                    <td style="font-size:var(--fs-xs);"><?= $a['last_login'] ? date('m-d H:i', strtotime($a['last_login'])) : '-' ?></td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-primary" onclick="openEdit(<?= $a['user_id'] ?>,<?= htmlspecialchars(json_encode($a['name'])) ?>,<?= htmlspecialchars(json_encode($a['user_role'])) ?>,<?= htmlspecialchars(json_encode($a['login_id'])) ?>,<?= $a['is_active']?'true':'false' ?>,<?= htmlspecialchars(json_encode($a['email']??'')) ?>,<?= htmlspecialchars(json_encode($a['phone']??'')) ?>,<?= htmlspecialchars(json_encode($a['grade']??'')) ?>,<?= htmlspecialchars(json_encode($a['team']??'')) ?>,<?= htmlspecialchars(json_encode($a['hire_date']??'')) ?>)">수정</button>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="action" value="issue_temp_pw">
                                <input type="hidden" name="user_id" value="<?= $a['user_id'] ?>">
                                <button type="submit" class="btn btn-sm btn-outline" onclick="return confirm('임시 비밀번호를 발급하시겠습니까?')">임시PW</button>
                            </form>
                            <?php if ($a['user_id'] != ($_SESSION['user_id'] ?? 0)): ?>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="action" value="delete_account">
                                <input type="hidden" name="user_id" value="<?= $a['user_id'] ?>">
                                <button type="submit" class="btn btn-sm btn-outline" style="color:var(--danger);border-color:var(--danger);" onclick="return confirm('⚠ <?= htmlspecialchars($a['name']) ?> 계정을 삭제하시겠습니까?\n\n계정이 삭제되고 직원이 비활성화됩니다.\n이 작업은 되돌릴 수 없습니다.')">삭제</button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal-overlay" id="approveModal"><div class="modal">
    <div class="modal-header"><h3>✅ 가입 승인 — <span id="appN"></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="approve_user"><input type="hidden" name="user_id" id="appId">
    <div class="form-group"><label>역할 부여</label><select name="assign_role"><option value="staff">직원</option><option value="team_leader">팀장</option><option value="manager">관리자</option><option value="ceo">대표</option><option value="sysadmin">시스템관리자</option></select></div>
    <button type="submit" class="btn btn-success">승인</button></form></div></div>

<div class="modal-overlay" id="rejectModal"><div class="modal">
    <div class="modal-header"><h3>❌ 반려 — <span id="rejN"></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="reject_user"><input type="hidden" name="user_id" id="rejId">
    <div class="form-group"><label>반려 사유</label><textarea name="reject_reason" rows="3"></textarea></div>
    <button type="submit" class="btn btn-danger">반려</button></form></div></div>

<div class="modal-overlay" id="editModal"><div class="modal" style="max-width:520px;">
    <div class="modal-header"><h3>✏️ 계정 정보 수정 — <span id="editN"></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="edit_account">
    <input type="hidden" name="user_id" id="editId">
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;">
        <div class="form-group"><label>아이디</label><input type="text" name="edit_login_id" id="editLogin" required></div>
        <div class="form-group"><label>이름</label><input type="text" name="edit_name" id="editDispName" required></div>
        <div class="form-group"><label>이메일</label><input type="email" name="edit_email" id="editEmail" placeholder="이메일"></div>
        <div class="form-group"><label>연락처</label><input type="text" name="edit_phone" id="editPhone" placeholder="010-0000-0000"></div>
        <div class="form-group"><label>직급</label><select name="edit_grade" id="editGrade">
            <?php foreach ($gradeList as $g): ?><option value="<?= htmlspecialchars($g) ?>"><?= htmlspecialchars($g) ?></option><?php endforeach; ?>
        </select></div>
        <div class="form-group"><label>소속 팀</label><select name="edit_team" id="editTeam">
            <?php foreach ($teamList as $t): ?><option value="<?= htmlspecialchars($t) ?>"><?= htmlspecialchars($t) ?></option><?php endforeach; ?>
        </select></div>
        <div class="form-group"><label>입사일</label><input type="date" name="edit_hire_date" id="editHireDate"></div>
        <div class="form-group"><label>역할</label><select name="new_role" id="editRole"><option value="staff">직원</option><option value="team_leader">팀장</option><option value="manager">관리자</option><option value="ceo">대표</option><option value="sysadmin">시스템관리자</option></select></div>
    </div>
    <div style="border-top:1px solid var(--border);margin:0.75rem 0;padding-top:0.75rem;">
        <div class="form-group"><label>계정 상태</label><select name="edit_active" id="editActive"><option value="1">활성</option><option value="0">비활성</option></select></div>
    </div>
    <button type="submit" class="btn btn-primary" style="width:100%;">정보 저장</button>
    </form></div></div>

<div class="modal-overlay" id="createModal"><div class="modal">
    <div class="modal-header"><h3>➕ 계정 생성 — <span id="crtN"></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="create_account"><input type="hidden" name="staff_id" id="crtId">
    <div class="form-group"><label>로그인 아이디</label><input type="text" name="new_login_id" required minlength="3" pattern="[a-zA-Z0-9_]+" placeholder="영문/숫자/밑줄, 3자 이상"></div>
    <div class="form-group"><label>역할 부여</label><select name="assign_role"><option value="staff">직원</option><option value="team_leader">팀장</option><option value="manager">관리자</option><option value="ceo">대표</option><option value="sysadmin">시스템관리자</option></select></div>
    <div class="alert alert-info">ℹ 임시 비밀번호가 자동 발급됩니다. 첫 로그인 시 변경 필수.</div>
    <button type="submit" class="btn btn-primary">계정 생성</button></form></div></div>

<script>
function openApprove(id,n){document.getElementById('appId').value=id;document.getElementById('appN').textContent=n;document.getElementById('approveModal').classList.add('show');}
function openReject(id,n){document.getElementById('rejId').value=id;document.getElementById('rejN').textContent=n;document.getElementById('rejectModal').classList.add('show');}
function openEdit(id,n,r,login,active,email,phone,grade,team,hireDate){document.getElementById('editId').value=id;document.getElementById('editN').textContent=n;document.getElementById('editRole').value=r;document.getElementById('editLogin').value=login;document.getElementById('editActive').value=active?'1':'0';document.getElementById('editDispName').value=n;document.getElementById('editEmail').value=email||'';document.getElementById('editPhone').value=phone||'';
var gs=document.getElementById('editGrade');if(gs){gs.value=grade||'';if(!gs.value&&grade){var o=document.createElement('option');o.value=grade;o.textContent=grade;gs.appendChild(o);gs.value=grade;}}
var ts=document.getElementById('editTeam');if(ts){ts.value=team||'';if(!ts.value&&team){var o=document.createElement('option');o.value=team;o.textContent=team;ts.appendChild(o);ts.value=team;}}
document.getElementById('editHireDate').value=hireDate||'';
document.getElementById('editModal').classList.add('show');}
function openCreate(id,n){document.getElementById('crtId').value=id;document.getElementById('crtN').textContent=n;document.getElementById('createModal').classList.add('show');}
</script>

<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 tLabels=<?= json_encode(array_keys($teamStats)) ?>;
const tData=<?= json_encode(array_values($teamStats)) ?>;
const tTotal=tData.reduce((a,b)=>a+b,0);
new Chart(document.getElementById('accTeamPie'),{type:'doughnut',data:{labels:tLabels,datasets:[{data:tData,backgroundColor:palette.slice(0,tLabels.length),borderWidth:1,borderColor:'rgba(0,0,0,0.3)'}]},options:{responsive:true,maintainAspectRatio:false,cutout:'55%',plugins:{legend:{display:false},tooltip:{callbacks:{label:function(c){var p=tTotal>0?(c.raw/tTotal*100).toFixed(0):0;return c.label+': '+c.raw+'명 ('+p+'%)';}}}}},plugins:[{afterDraw:function(chart){var ctx=chart.ctx;ctx.save();ctx.font='600 11px 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;ctx.fillStyle='#fff';ctx.fillText(val,x,y);});ctx.restore();}}]});
const gLabels=<?= json_encode(array_keys($gradeStats)) ?>;
const gData=<?= json_encode(array_values($gradeStats)) ?>;
new Chart(document.getElementById('accGradeBar'),{type:'bar',data:{labels:gLabels,datasets:[{data:gData,backgroundColor:palette.slice(0,gLabels.length),borderWidth:0,borderRadius:4}]},options:{indexAxis:'y',responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false},tooltip:{callbacks:{label:function(c){return c.raw+'명';}}}},scales:{x:{grid:{color:'rgba(255,255,255,0.05)'},ticks:{color:'#aaa',font:{size:11}}},y:{grid:{display:false},ticks:{color:'#ccc',font:{size:11}}}}}});
}
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
