<?php
// pages/menu_manage.php — 메뉴 권한 관리 (독립 메뉴)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();

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

// ── 메뉴별 권한 설정 테이블 ──
$db->exec("CREATE TABLE IF NOT EXISTS menu_role_permission (
    mrp_id INT AUTO_INCREMENT PRIMARY KEY,
    menu_key VARCHAR(30) NOT NULL,
    role_key VARCHAR(20) NOT NULL,
    view_scope ENUM('none','own','team','all') DEFAULT 'own',
    can_create TINYINT(1) DEFAULT 0,
    can_edit TINYINT(1) DEFAULT 0,
    can_delete TINYINT(1) DEFAULT 0,
    need_ceo_approval TINYINT(1) DEFAULT 0,
    need_sysadmin_approval TINYINT(1) DEFAULT 0,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_menu_role(menu_key, role_key)
)");

// 초기 데이터 삽입 (없을 경우)
$mrpCount = $db->query("SELECT COUNT(*) FROM menu_role_permission")->fetchColumn();
if ($mrpCount == 0) {
    $allMenuKeys = $db->query("SELECT DISTINCT menu_key FROM menu_permission")->fetchAll(PDO::FETCH_COLUMN);
    $roleDefaults = [
        'sysadmin' => ['view_scope'=>'all','can_create'=>1,'can_edit'=>1,'can_delete'=>1,'need_ceo_approval'=>0,'need_sysadmin_approval'=>0],
        'ceo'      => ['view_scope'=>'all','can_create'=>1,'can_edit'=>1,'can_delete'=>1,'need_ceo_approval'=>0,'need_sysadmin_approval'=>0],
        'manager'  => ['view_scope'=>'team','can_create'=>0,'can_edit'=>0,'can_delete'=>0,'need_ceo_approval'=>0,'need_sysadmin_approval'=>0],
        'team_leader'=>['view_scope'=>'own','can_create'=>1,'can_edit'=>0,'can_delete'=>0,'need_ceo_approval'=>0,'need_sysadmin_approval'=>1],
        'staff'    => ['view_scope'=>'own','can_create'=>1,'can_edit'=>0,'can_delete'=>0,'need_ceo_approval'=>0,'need_sysadmin_approval'=>1],
    ];
    $ins = $db->prepare("INSERT IGNORE INTO menu_role_permission (menu_key,role_key,view_scope,can_create,can_edit,can_delete,need_ceo_approval,need_sysadmin_approval) VALUES(?,?,?,?,?,?,?,?)");
    foreach ($allMenuKeys as $mk) {
        foreach ($roleDefaults as $rk=>$rd) {
            $ins->execute([$mk,$rk,$rd['view_scope'],$rd['can_create'],$rd['can_edit'],$rd['can_delete'],$rd['need_ceo_approval'],$rd['need_sysadmin_approval']]);
        }
    }
}

// POST 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'bulk_menu') {
        $roleKey = $_POST['role_key'] ?? '';
        $visible = $_POST['visible'] ?? [];
        if ($roleKey && isset($managedRoles[$roleKey])) {
            $db->prepare("UPDATE menu_permission SET is_visible=0 WHERE user_role=?")->execute([$roleKey]);
            if ($visible) {
                $inPh = implode(',', array_fill(0, count($visible), '?'));
                $db->prepare("UPDATE menu_permission SET is_visible=1 WHERE perm_id IN ($inPh)")->execute($visible);
            }
            $message = $managedRoles[$roleKey] . ' 메뉴가 저장되었습니다.';
        }
    }
    if ($action === 'save_permissions') {
        $permData = $_POST['perm'] ?? [];
        $upd = $db->prepare("INSERT INTO menu_role_permission (menu_key,role_key,view_scope,can_create,can_edit,can_delete,need_ceo_approval,need_sysadmin_approval) VALUES(?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE view_scope=VALUES(view_scope),can_create=VALUES(can_create),can_edit=VALUES(can_edit),can_delete=VALUES(can_delete),need_ceo_approval=VALUES(need_ceo_approval),need_sysadmin_approval=VALUES(need_sysadmin_approval)");
        foreach ($permData as $mk => $roles) {
            foreach ($roles as $rk => $vals) {
                $upd->execute([
                    $mk, $rk,
                    $vals['view_scope'] ?? 'own',
                    isset($vals['can_create']) ? 1 : 0,
                    isset($vals['can_edit']) ? 1 : 0,
                    isset($vals['can_delete']) ? 1 : 0,
                    isset($vals['need_ceo_approval']) ? 1 : 0,
                    isset($vals['need_sysadmin_approval']) ? 1 : 0,
                ]);
            }
        }
        $message = '권한 설정이 저장되었습니다.';
    }
    if ($action === 'save_group_assign') {
        $grp = $_POST['menu_group'] ?? '';
        $assignedTeams = $_POST['assigned_teams'] ?? [];
        if ($grp) {
            $db->prepare("DELETE FROM team_menu_group_assign WHERE menu_group=?")->execute([$grp]);
            foreach ($assignedTeams as $at) {
                $db->prepare("INSERT INTO team_menu_group_assign (menu_group, assigned_team) VALUES(?,?)")->execute([$grp, $at]);
            }
            $message = htmlspecialchars($grp) . ' 그룹의 팀 분류가 저장되었습니다.';
        }
    }
}

// ── 사이드바 메뉴 구조와 자동 동기화 ──
$sidebarSync = [
    ['key'=>'home','label'=>'홈','icon'=>'🏠','group'=>'메인','url'=>BASE_URL.'pages/home.php','sort'=>0,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'notice','label'=>'공지사항','icon'=>'📌','group'=>'메인','url'=>BASE_URL.'pages/notice.php','sort'=>1,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'team_notice','label'=>'팀 공지사항','icon'=>'📢','group'=>'메인','url'=>BASE_URL.'pages/team_notice.php','sort'=>2,'roles'=>['team_leader','manager','ceo','sysadmin']],
    ['key'=>'team_status','label'=>'팀 현황','icon'=>'🏢','group'=>'메인','url'=>BASE_URL.'pages/team_status.php','sort'=>3,'roles'=>['team_leader','manager','ceo','sysadmin']],
    ['key'=>'dashboard','label'=>'대시보드','icon'=>'📈','group'=>'메인','url'=>BASE_URL.'pages/dashboard.php','sort'=>4,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'staff_mgmt','label'=>'조직 현황','icon'=>'👥','group'=>'운영','url'=>BASE_URL.'pages/staff.php','sort'=>10,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'exec_report','label'=>'경영 보고서','icon'=>'📑','group'=>'운영','url'=>BASE_URL.'pages/exec_report.php','sort'=>11,'roles'=>['ceo','sysadmin']],
    ['key'=>'policy','label'=>'규정 안내','icon'=>'📋','group'=>'영업','url'=>BASE_URL.'pages/policy.php','sort'=>20,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'sales_report','label'=>'실적 보고서','icon'=>'📝','group'=>'영업','url'=>BASE_URL.'pages/sales_report.php','sort'=>21,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'sales','label'=>'실적 검토','icon'=>'💰','group'=>'영업','url'=>BASE_URL.'pages/sales.php','sort'=>22,'roles'=>['team_leader','manager','ceo','sysadmin']],
    ['key'=>'profit','label'=>'영업 이익현황','icon'=>'📊','group'=>'영업','url'=>BASE_URL.'pages/profit.php','sort'=>23,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'kpi','label'=>'KPI 달성률','icon'=>'🎯','group'=>'영업','url'=>BASE_URL.'pages/kpi.php','sort'=>24,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'pipeline','label'=>'영업 단계 현황','icon'=>'🔄','group'=>'영업','url'=>BASE_URL.'pages/pipeline.php','sort'=>25,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'performance','label'=>'평가 점수','icon'=>'⭐','group'=>'인사','url'=>BASE_URL.'pages/performance.php','sort'=>30,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'admin_teams','label'=>'인사 관리','icon'=>'🏅','group'=>'인사','url'=>BASE_URL.'pages/admin_teams.php','sort'=>31,'roles'=>['ceo','sysadmin']],
    ['key'=>'evaluation','label'=>'인사 평가','icon'=>'📝','group'=>'인사','url'=>BASE_URL.'pages/evaluation.php','sort'=>32,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'team_assign','label'=>'팀장 선정','icon'=>'👑','group'=>'인사','url'=>BASE_URL.'pages/admin_team_assign.php','sort'=>33,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'incentive','label'=>'인센티브 산출','icon'=>'💎','group'=>'인사','url'=>BASE_URL.'pages/incentive.php','sort'=>34,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'approval','label'=>'인센티브 검토','icon'=>'✅','group'=>'인사','url'=>BASE_URL.'pages/approval.php','sort'=>35,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'campaign','label'=>'캠페인 관리','icon'=>'📢','group'=>'마케팅','url'=>BASE_URL.'pages/marketing/campaign.php','sort'=>50,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'mkt_performance','label'=>'마케팅 실적','icon'=>'📊','group'=>'마케팅','url'=>BASE_URL.'pages/marketing/mkt_performance.php','sort'=>51,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'roi_analysis','label'=>'ROI 분석','icon'=>'📈','group'=>'마케팅','url'=>BASE_URL.'pages/marketing/roi_analysis.php','sort'=>52,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'brand_strategy','label'=>'브랜드 전략','icon'=>'🎯','group'=>'마케팅','url'=>BASE_URL.'pages/marketing/brand_strategy.php','sort'=>53,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'content_pipeline','label'=>'콘텐츠 파이프라인','icon'=>'📝','group'=>'마케팅','url'=>BASE_URL.'pages/marketing/content_pipeline.php','sort'=>54,'roles'=>['staff','team_leader','manager','ceo','sysadmin']],
    ['key'=>'risk_control','label'=>'리스크 컨트롤','icon'=>'🛡️','group'=>'마케팅','url'=>BASE_URL.'pages/marketing/risk_control.php','sort'=>55,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'admin_sysinfo','label'=>'시스템 정보','icon'=>'🖥️','group'=>'시스템 설정','url'=>BASE_URL.'pages/admin_sysinfo.php','sort'=>60,'roles'=>['sysadmin']],
    ['key'=>'promotion','label'=>'프로모션','icon'=>'🎯','group'=>'시스템 설정','url'=>BASE_URL.'pages/promotion.php','sort'=>61,'roles'=>['manager','ceo','sysadmin']],
    ['key'=>'incentive_rate','label'=>'인센티브 비율','icon'=>'💹','group'=>'시스템 설정','url'=>BASE_URL.'pages/incentive_rate.php','sort'=>62,'roles'=>['ceo','sysadmin']],
    ['key'=>'admin_accounts','label'=>'계정 관리','icon'=>'🔑','group'=>'시스템 설정','url'=>BASE_URL.'pages/admin_accounts.php','sort'=>63,'roles'=>['sysadmin']],
    ['key'=>'admin_audit','label'=>'로그 추적','icon'=>'🔍','group'=>'시스템 설정','url'=>BASE_URL.'pages/admin_audit.php','sort'=>64,'roles'=>['sysadmin']],
    ['key'=>'menu_manage','label'=>'권한 관리','icon'=>'🛡️','group'=>'시스템 설정','url'=>BASE_URL.'pages/menu_manage.php','sort'=>65,'roles'=>['ceo','sysadmin']],
    ['key'=>'policy_settings','label'=>'정책 관리','icon'=>'⚙️','group'=>'시스템 설정','url'=>BASE_URL.'pages/policy_settings.php','sort'=>66,'roles'=>['ceo','sysadmin']],
];
$syncIns = $db->prepare("INSERT IGNORE INTO menu_permission (user_role,menu_key,menu_label,menu_icon,menu_group,menu_url,sort_order,is_visible) VALUES(?,?,?,?,?,?,?,1)");
$syncUpd = $db->prepare("UPDATE menu_permission SET menu_label=?,menu_icon=?,menu_group=?,menu_url=?,sort_order=? WHERE menu_key=? AND user_role=?");
foreach ($sidebarSync as $m) {
    foreach ($m['roles'] as $rk) {
        $syncIns->execute([$rk,$m['key'],$m['label'],$m['icon'],$m['group'],$m['url'],$m['sort']]);
        $syncUpd->execute([$m['label'],$m['icon'],$m['group'],$m['url'],$m['sort'],$m['key'],$rk]);
    }
}
// 삭제: 사이드바에 없는 메뉴 정리
try { $db->exec("DELETE FROM menu_permission WHERE menu_key='admin_settings'"); } catch(Exception $e) {}

// 역할별 메뉴 로드
$menusByRole = [];
foreach (array_keys($managedRoles) as $rk) {
    $stmt = $db->prepare("SELECT * FROM menu_permission WHERE user_role=? ORDER BY sort_order");
    $stmt->execute([$rk]);
    $menusByRole[$rk] = $stmt->fetchAll();
}

$selectedRole = $_GET['role'] ?? 'sysadmin';
if (!isset($managedRoles[$selectedRole])) $selectedRole = 'sysadmin';

// 팀 데이터
// 팀 목록은 team_master 테이블과 연동
$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 '', is_active TINYINT(1) DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
$allTeams = $db->query("SELECT team_name FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
$allMenuGroups = $db->query("SELECT menu_group, MIN(sort_order) AS so FROM menu_permission GROUP BY menu_group ORDER BY so")->fetchAll(PDO::FETCH_COLUMN);

// 팀 메뉴 분류
$db->exec("CREATE TABLE IF NOT EXISTS team_menu_group_assign (assign_id INT AUTO_INCREMENT PRIMARY KEY, menu_group VARCHAR(50) NOT NULL, assigned_team VARCHAR(50) NOT NULL, UNIQUE KEY uk_group_team(menu_group,assigned_team))");
$groupAssign = [];
try { $gaRows = $db->query("SELECT menu_group, assigned_team FROM team_menu_group_assign")->fetchAll();
    foreach ($gaRows as $ga) $groupAssign[$ga['menu_group']][] = $ga['assigned_team'];
} catch(Exception $e) {}

$menuMode = $_GET['mode'] ?? 'role';

$permRoleFilter = $_GET['prole'] ?? 'all';
?>

<div class="page-header"><h2>📋 메뉴 권한 관리</h2></div>

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

<!-- 모드 전환 -->
<div style="display:flex;gap:0.5rem;margin-bottom:1rem;">
    <a href="?mode=role" class="btn <?= $menuMode==='role'?'btn-primary':'btn-outline' ?>">👤 역할별 설정</a>
    <a href="?mode=team" class="btn <?= $menuMode==='team'?'btn-primary':'btn-outline' ?>">🏢 팀 메뉴 분류</a>
    <a href="?mode=perm" class="btn <?= $menuMode==='perm'?'btn-primary':'btn-outline' ?>">🔐 권한 설정</a>
</div>

<?php if ($menuMode === 'role'): ?>
<!-- 역할 선택 -->
<div style="display:flex;gap:4px;margin-bottom:1rem;flex-wrap:wrap;">
    <?php foreach ($managedRoles as $rk=>$rl): ?>
    <a href="?mode=role&role=<?= $rk ?>" class="btn btn-sm <?= $selectedRole === $rk ? 'btn-primary' : 'btn-outline' ?>"><?= $rl ?></a>
    <?php endforeach; ?>
</div>

<div class="card">
    <div class="card-header"><h3><?= $managedRoles[$selectedRole] ?> 메뉴 설정</h3></div>
    <form method="POST">
        <input type="hidden" name="action" value="bulk_menu">
        <input type="hidden" name="role_key" value="<?= $selectedRole ?>">
        <div style="overflow-x:auto;">
        <table class="data-table">
            <thead><tr><th style="width:50px;">표시</th><th>그룹</th><th>아이콘</th><th>메뉴명</th><th>URL</th></tr></thead>
            <tbody>
            <?php $lastGroup = '';
            foreach ($menusByRole[$selectedRole] as $m):
                $grpAssignedTeams = $groupAssign[$m['menu_group']] ?? [];
                if ($grpAssignedTeams) continue;
                if ($m['menu_group'] !== $lastGroup) {
                    $lastGroup = $m['menu_group'];
                    echo "<tr style='background:rgba(var(--accent-rgb),0.06);'><td colspan='5' style='font-weight:600;padding:0.5rem 0.75rem;'>{$lastGroup}</td></tr>";
                }
            ?>
            <tr style="<?= !$m['is_visible']?'opacity:0.5;':'' ?>">
                <td style=""><input type="checkbox" name="visible[]" value="<?= $m['perm_id'] ?>" <?= $m['is_visible']?'checked':'' ?> style="width:18px;height:18px;cursor:pointer;"></td>
                <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($m['menu_group']) ?></td>
                <td><?= $m['menu_icon'] ?></td>
                <td><strong><?= htmlspecialchars($m['menu_label']) ?></strong></td>
                <td style="font-size:var(--fs-xs);font-family:monospace;color:var(--text-tertiary);"><?= $m['menu_url'] ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <div style="padding:0.75rem 1rem;display:flex;gap:0.5rem;">
            <button type="submit" class="btn btn-primary">💾 저장</button>
            <button type="button" class="btn btn-outline btn-sm" onclick="document.querySelectorAll('[name=\'visible[]\']').forEach(c=>c.checked=true)">전체 선택</button>
            <button type="button" class="btn btn-outline btn-sm" onclick="document.querySelectorAll('[name=\'visible[]\']').forEach(c=>c.checked=false)">전체 해제</button>
        </div>
    </form>
</div>

<?php elseif ($menuMode === 'team'): ?>
<!-- 팀 메뉴 분류 -->
<div class="alert alert-info" style="margin-bottom:1rem;font-size:var(--fs-sm);">
    ℹ 메뉴 그룹을 특정 팀 전용으로 분류합니다. 팀이 지정되지 않은 그룹은 모든 팀에 표시됩니다.
</div>
<?php foreach ($allMenuGroups as $mg):
    $assigned = $groupAssign[$mg] ?? [];
?>
<div class="card" style="margin-bottom:0.5rem;padding:0.75rem 1rem;">
    <form method="POST" style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap;">
        <input type="hidden" name="action" value="save_group_assign">
        <input type="hidden" name="menu_group" value="<?= htmlspecialchars($mg) ?>">
        <strong style="min-width:8rem;font-size:var(--fs-sm);"><?= htmlspecialchars($mg) ?></strong>
        <div style="display:flex;gap:0.5rem;flex-wrap:wrap;flex:1;">
        <?php foreach ($allTeams as $tm): ?>
            <label style="font-size:var(--fs-xs);display:flex;align-items:center;gap:0.2rem;cursor:pointer;padding:0.2rem 0.5rem;border:1px solid var(--border);border-radius:4px;<?= in_array($tm,$assigned)?'background:rgba(var(--accent-rgb),0.1);border-color:var(--accent);':'' ?>">
                <input type="checkbox" name="assigned_teams[]" value="<?= htmlspecialchars($tm) ?>" <?= in_array($tm,$assigned)?'checked':'' ?> style="width:14px;height:14px;">
                <?= htmlspecialchars($tm) ?>
            </label>
        <?php endforeach; ?>
        </div>
        <button type="submit" class="btn btn-outline btn-sm" style="font-size:var(--fs-xs);">저장</button>
        <?php if($assigned): ?><span style="font-size:var(--fs-xs);color:var(--accent-text);"><?= implode(', ', $assigned) ?> 전용</span><?php else: ?><span style="font-size:var(--fs-xs);color:var(--text-tertiary);">전체 공개</span><?php endif; ?>
    </form>
</div>
<?php endforeach; ?>
<?php elseif ($menuMode === 'perm'): ?>
<!-- ═══ 게시판 권한 설정만 표시 ═══ -->

<h3 style="font-size:var(--fs-md);margin-bottom:1rem;">📋 게시판 권한 설정</h3>

<!-- ═══ 권한 설정 — 게시판 전용 ═══ -->
<?php
// 게시판 권한 테이블
$db->exec("CREATE TABLE IF NOT EXISTS board_permission (
    bp_id INT AUTO_INCREMENT PRIMARY KEY,
    board_key VARCHAR(30) NOT NULL,
    role_key VARCHAR(20) NOT NULL,
    can_view TINYINT(1) DEFAULT 1,
    can_create TINYINT(1) DEFAULT 0,
    can_edit TINYINT(1) DEFAULT 0,
    can_delete TINYINT(1) DEFAULT 0,
    can_copy TINYINT(1) DEFAULT 0,
    can_comment TINYINT(1) DEFAULT 0,
    can_comment_edit TINYINT(1) DEFAULT 0,
    can_comment_delete TINYINT(1) DEFAULT 0,
    can_reply TINYINT(1) DEFAULT 0,
    can_reply_edit TINYINT(1) DEFAULT 0,
    can_reply_delete TINYINT(1) DEFAULT 0,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_board_role(board_key, role_key)
)");

// 게시판 종류 정의
$boards = [
    'notice'      => ['label'=>'📌 공지사항', 'desc'=>'전체 공지사항 게시판'],
    'team_notice' => ['label'=>'📢 팀 공지사항', 'desc'=>'팀별 공지사항 게시판'],
];

// 초기 데이터 삽입
$bpCount = (int)$db->query("SELECT COUNT(*) FROM board_permission")->fetchColumn();
if ($bpCount === 0) {
    $bpIns = $db->prepare("INSERT IGNORE INTO board_permission (board_key,role_key,can_view,can_create,can_edit,can_delete,can_copy,can_comment,can_comment_edit,can_comment_delete,can_reply,can_reply_edit,can_reply_delete) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
    $roleDefaults = [
        'sysadmin'=>[1,1,1,1,1,1,1,1,1,1,1], 'ceo'=>[1,1,1,1,1,1,1,1,1,1,1],
        'manager'=>[1,1,1,0,1,1,1,0,1,1,0], 'team_leader'=>[1,1,0,0,0,1,1,0,1,1,0],
        'staff'=>[1,0,0,0,0,1,0,0,1,0,0],
    ];
    foreach ($boards as $bk=>$_) { foreach ($roleDefaults as $rk=>$d) { $bpIns->execute(array_merge([$bk,$rk],$d)); } }
}

// POST: 게시판 권한 저장
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action']??'') === 'save_board_perm') {
    $bpUpd = $db->prepare("INSERT INTO board_permission (board_key,role_key,can_view,can_create,can_edit,can_delete,can_copy,can_comment,can_comment_edit,can_comment_delete,can_reply,can_reply_edit,can_reply_delete) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE can_view=VALUES(can_view),can_create=VALUES(can_create),can_edit=VALUES(can_edit),can_delete=VALUES(can_delete),can_copy=VALUES(can_copy),can_comment=VALUES(can_comment),can_comment_edit=VALUES(can_comment_edit),can_comment_delete=VALUES(can_comment_delete),can_reply=VALUES(can_reply),can_reply_edit=VALUES(can_reply_edit),can_reply_delete=VALUES(can_reply_delete)");
    $bp = $_POST['bp'] ?? [];
    foreach ($bp as $bk => $roles) {
        foreach ($roles as $rk => $v) {
            $bpUpd->execute([$bk,$rk, isset($v['view'])?1:0, isset($v['create'])?1:0, isset($v['edit'])?1:0, isset($v['delete'])?1:0, isset($v['copy'])?1:0, isset($v['comment'])?1:0, isset($v['comment_edit'])?1:0, isset($v['comment_delete'])?1:0, isset($v['reply'])?1:0, isset($v['reply_edit'])?1:0, isset($v['reply_delete'])?1:0]);
        }
    }
    $message = '게시판 권한이 저장되었습니다.';
    echo "<div class='alert alert-success'>✓ {$message}</div>";
}

// 현재 권한 로드
$bpAll = [];
$bpRows = $db->query("SELECT * FROM board_permission")->fetchAll();
foreach ($bpRows as $r) $bpAll[$r['board_key']][$r['role_key']] = $r;

$permCols = ['view'=>'보기','create'=>'작성','edit'=>'수정','delete'=>'삭제','copy'=>'복사','comment'=>'댓글','comment_edit'=>'댓글 수정','comment_delete'=>'댓글 삭제','reply'=>'답변','reply_edit'=>'답변 수정','reply_delete'=>'답변 삭제'];
?>

<div class="alert alert-info" style="margin-bottom:1rem;font-size:var(--fs-sm);">
    🔐 게시판별 역할 권한을 설정합니다. 체크된 항목만 해당 역할에서 사용 가능합니다.
</div>

<form method="POST">
<input type="hidden" name="action" value="save_board_perm">

<?php foreach ($boards as $bk => $bInfo): ?>
<div class="card" style="margin-bottom:1rem;">
    <div class="card-header"><h3><?= $bInfo['label'] ?></h3><div style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= $bInfo['desc'] ?></div></div>
    <div style="overflow-x:auto;">
    <table class="data-table" style="font-size:var(--fs-xs);">
        <thead>
            <tr>
                <th style="min-width:6rem;">역할</th>
                <?php foreach ($permCols as $ck => $cl): ?>
                <th style="font-size:var(--fs-xs);padding:0.35rem 0.25rem;white-space:nowrap;"><?= $cl ?></th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($managedRoles as $rk => $rl):
            $p = $bpAll[$bk][$rk] ?? [];
        ?>
        <tr>
            <td><span class="badge <?= in_array($rk,['sysadmin','ceo'])?'badge-success':($rk==='manager'?'badge-info':($rk==='team_leader'?'badge-warning':'badge-gray')) ?>"><?= $rl ?></span></td>
            <?php foreach ($permCols as $ck => $cl):
                $dbCol = 'can_' . $ck;
                $checked = ($p[$dbCol] ?? 0) ? 'checked' : '';
            ?>
            <td style="">
                <input type="checkbox" name="bp[<?= $bk ?>][<?= $rk ?>][<?= $ck ?>]" value="1" <?= $checked ?> style="width:15px;height:15px;cursor:pointer;">
            </td>
            <?php endforeach; ?>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>
<?php endforeach; ?>

<div style="display:flex;gap:0.5rem;align-items:center;margin-bottom:1rem;">
    <button type="submit" class="btn btn-primary">💾 게시판 권한 저장</button>
    <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">변경 사항은 즉시 반영됩니다</span>
</div>
</form>

<div class="card" style="padding:1rem;">
    <h4 style="margin:0 0 0.5rem;font-size:var(--fs-sm);">📖 권한 항목 설명</h4>
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(14rem,1fr));gap:0.4rem;font-size:var(--fs-xs);color:var(--text-secondary);">
        <div><strong>보기</strong> — 게시물 목록/내용 조회</div>
        <div><strong>작성</strong> — 새 게시물 등록</div>
        <div><strong>수정</strong> — 게시물 수정</div>
        <div><strong>삭제</strong> — 게시물 삭제</div>
        <div><strong>복사</strong> — 게시물 복사/복제</div>
        <div><strong>댓글</strong> — 댓글 작성</div>
        <div><strong>댓글 수정</strong> — 본인 댓글 수정</div>
        <div><strong>댓글 삭제</strong> — 댓글 삭제</div>
        <div><strong>답변</strong> — 답변글 작성</div>
        <div><strong>답변 수정</strong> — 답변글 수정</div>
        <div><strong>답변 삭제</strong> — 답변글 삭제</div>
    </div>
</div>
<?php endif; ?>

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