<?php

$action = trim((string) ($_GET['action'] ?? 'list'));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAdminCsrfToken($action === 'delete');
    if ($action === 'save') {
        $id = intval($_POST['id'] ?? 0);
        $name = trim((string) ($_POST['role_name'] ?? ''));
        $description = trim((string) ($_POST['role_desc'] ?? ''));
        $allowed = [];
        foreach (cmsAdminPermissionCatalog() as $modules) {
            foreach (array_keys($modules) as $module) { $allowed[] = $module . '.view'; $allowed[] = $module . '.manage'; }
        }
        $allowed[] = 'article.publish';
        $permissions = array_values(array_intersect($allowed, array_map('strval', (array) ($_POST['permissions'] ?? []))));
        if ($name === '') {
            echo '<script>alert("请输入角色名称");history.back();</script>';
            exit;
        }
        $duplicate = $db->fetch("SELECT id FROM {$db->table('role')} WHERE role_name = ? AND id <> ? LIMIT 1", [$name, $id]);
        if ($duplicate) {
            echo '<script>alert("角色名称已存在");history.back();</script>';
            exit;
        }
        $data = [
            'role_name' => $name,
            'role_desc' => $description,
            'permissions' => json_encode(['modules' => $permissions], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ];
        if ($id > 0) {
            $db->update('role', $data, 'id = ?', [$id]);
            addLog('修改', '角色权限', '修改角色 ' . $name);
        } else {
            $data['is_default'] = 0;
            $data['create_time'] = time();
            $db->insert('role', $data);
            addLog('添加', '角色权限', '添加角色 ' . $name);
        }
        echo '<script>alert("保存成功");location.href="?act=role";</script>';
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        $used = $db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('admin')} WHERE role_id = ?", [$id]);
        if (intval($used['cnt'] ?? 0) > 0) {
            echo json_encode(['code' => 400, 'msg' => '该角色仍有管理员使用，不能删除'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $role = $db->fetch("SELECT role_name FROM {$db->table('role')} WHERE id = ?", [$id]);
        $db->delete('role', 'id = ?', [$id]);
        addLog('删除', '角色权限', '删除角色 ' . ($role['role_name'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功'], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

if ($action === 'add' || $action === 'edit') {
    $role = ['id' => 0, 'role_name' => '', 'role_desc' => '', 'permissions' => ''];
    if ($action === 'edit') {
        $role = $db->fetch("SELECT * FROM {$db->table('role')} WHERE id = ?", [intval($_GET['id'] ?? 0)]);
        if (!$role) { echo '<script>alert("角色不存在");location.href="?act=role";</script>'; exit; }
    }
    $selected = cmsNormalizeAdminPermissions($role['permissions'] ?? '');
    ?>
    <div class="page-container fade-in">
        <div class="page-header"><div class="page-title"><div><h1><?php echo $action === 'edit' ? '编辑角色' : '新增角色'; ?></h1><p>按模块分配后台访问和操作权限</p></div></div><div class="page-actions"><a href="?act=role" class="btn btn-secondary">返回</a></div></div>
        <form method="post" action="?act=role&action=save">
            <input type="hidden" name="id" value="<?php echo intval($role['id']); ?>">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken(), ENT_QUOTES, 'UTF-8'); ?>">
            <div class="form-section"><div class="form-section-header">角色信息</div><div class="form-section-body">
                <div class="form-row"><div class="form-group"><label>角色名称 <span class="required">*</span></label><input class="form-control" name="role_name" required maxlength="50" value="<?php echo htmlspecialchars($role['role_name'], ENT_QUOTES, 'UTF-8'); ?>"></div><div class="form-group"><label>角色说明</label><input class="form-control" name="role_desc" maxlength="255" value="<?php echo htmlspecialchars($role['role_desc'], ENT_QUOTES, 'UTF-8'); ?>"></div></div>
            </div></div>
            <div class="form-section"><div class="form-section-header">模块权限 <label style="margin-left:auto;font-weight:500;"><input type="checkbox" id="selectAll"> 全选</label></div><div class="form-section-body">
                <div class="rbac-grid">
                <?php foreach (cmsAdminPermissionCatalog() as $group => $modules): ?>
                    <section class="rbac-group"><div class="rbac-group-title"><?php echo htmlspecialchars($group); ?></div>
                    <?php foreach ($modules as $key => $label): $legacy = in_array($key, $selected, true); ?><div class="rbac-row"><span><?php echo htmlspecialchars($label); ?></span><label><input class="perm-view" type="checkbox" name="permissions[]" value="<?php echo $key; ?>.view" <?php echo ($legacy || in_array($key . '.view', $selected, true) || in_array($key . '.manage', $selected, true)) ? 'checked' : ''; ?>> 查看</label><label><input class="perm-manage" type="checkbox" name="permissions[]" value="<?php echo $key; ?>.manage" <?php echo ($legacy || in_array($key . '.manage', $selected, true)) ? 'checked' : ''; ?>> 管理</label></div><?php endforeach; ?>
                    <?php if (isset($modules['article'])): ?><div class="rbac-row"><span>文章审核</span><label style="grid-column:2/4"><input type="checkbox" name="permissions[]" value="article.publish" <?php echo in_array('article', $selected, true) || in_array('article.publish', $selected, true) ? 'checked' : ''; ?>> 审核并发布</label></div><?php endif; ?>
                    </section>
                <?php endforeach; ?>
                </div>
                <p style="margin:16px 0 0;color:#64748b;font-size:12px;">管理员、角色、数据库、授权与版本管理仅超级管理员可访问，不能下放。</p>
            </div></div>
            <div class="form-actions"><button class="btn btn-success btn-lg" type="submit">保存角色</button><a href="?act=role" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <style>.rbac-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.rbac-group{padding:18px;border:1px solid #e2e8f0;border-radius:14px;background:#fbfdff}.rbac-group-title{font-weight:700;margin-bottom:12px}.rbac-row{display:grid;grid-template-columns:minmax(120px,1fr) 70px 70px;align-items:center;gap:8px;padding:8px 0;border-bottom:1px solid #eef2f7;color:#475569}.rbac-row:last-child{border-bottom:0}.rbac-row label{cursor:pointer}@media(max-width:900px){.rbac-grid{grid-template-columns:1fr}}</style>
    <script>document.getElementById('selectAll').addEventListener('change',function(){document.querySelectorAll('input[name="permissions[]"]').forEach(function(input){input.checked=this.checked;},this);});document.querySelectorAll('.perm-manage').forEach(function(input){input.addEventListener('change',function(){if(this.checked)this.closest('.rbac-row').querySelector('.perm-view').checked=true;});});document.querySelectorAll('.perm-view').forEach(function(input){input.addEventListener('change',function(){if(!this.checked)this.closest('.rbac-row').querySelector('.perm-manage').checked=false;});});</script>
    <?php
    return;
}

$roles = $db->fetchAll("SELECT r.*, (SELECT COUNT(*) FROM {$db->table('admin')} a WHERE a.role_id = r.id) AS admin_count FROM {$db->table('role')} r ORDER BY r.id DESC");
?>
<div class="page-container fade-in">
    <div class="page-header"><div class="page-title"><div><h1>角色权限</h1><p>为普通管理员配置最小必要权限</p></div></div><div class="page-actions"><a href="?act=role&action=add" class="btn btn-primary">新增角色</a></div></div>
    <div class="content-card"><table class="data-table"><thead><tr><th>ID</th><th>角色名称</th><th>说明</th><th>权限数量</th><th>管理员</th><th>操作</th></tr></thead><tbody>
    <?php if (!$roles): ?><tr><td colspan="6" style="text-align:center;padding:48px;color:#94a3b8;">暂无普通角色，请先新增角色</td></tr><?php endif; ?>
    <?php foreach ($roles as $role): $permissions = cmsNormalizeAdminPermissions($role['permissions'] ?? ''); $moduleCount = count(array_unique(array_map(function($permission){ return explode('.', $permission)[0]; }, $permissions))); ?><tr><td><?php echo intval($role['id']); ?></td><td><strong><?php echo htmlspecialchars($role['role_name']); ?></strong></td><td><?php echo htmlspecialchars($role['role_desc'] ?: '-'); ?></td><td><?php echo $moduleCount; ?> 个模块</td><td><?php echo intval($role['admin_count']); ?> 人</td><td><div class="btn-group"><a class="btn btn-primary" href="?act=role&action=edit&id=<?php echo intval($role['id']); ?>">编辑</a><button class="btn btn-ghost" type="button" onclick="deleteRole(<?php echo intval($role['id']); ?>)">删除</button></div></td></tr><?php endforeach; ?>
    </tbody></table></div>
</div>
<script>function deleteRole(id){if(!confirm('确定删除该角色？'))return;fetch('?act=role&action=delete',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'}).then(function(r){return r.json();}).then(function(d){alert(d.msg);if(d.code===200)location.reload();});}</script>
