<?php

function cmsAdminPermissionCatalog()
{
    return [
        '内容管理' => ['content' => '内容总览', 'data_import' => '数据导入', 'content_quality' => '内容质量', 'article' => '文章管理', 'product' => '产品管理', 'channel' => '栏目管理', 'page' => '单页管理', 'image' => '图册管理', 'download' => '下载管理', 'video' => '视频管理', 'recruit' => '招聘管理'],
        '用户互动' => ['member' => '会员管理', 'member_group' => '会员分组', 'message' => '站内消息', 'guestbook' => '留言管理', 'comment' => '评论管理', 'online_service' => '在线客服', 'vote' => '投票调查', 'contribute' => '投稿管理'],
        '资源装修' => ['media' => '媒体资源', 'slide' => '幻灯片', 'link' => '友情链接', 'ads' => '广告管理', 'template' => '模板中心', 'builder' => '页面装修', 'tag_help' => '标签帮助'],
        '站点运营' => ['notification' => '通知中心', 'task_center' => '后台任务', 'site' => '网站设置', 'redirect' => '404与跳转', 'system_status' => '系统状态', 'seo_tools' => 'SEO工具', 'custom_var' => '自定义变量', 'log' => '操作日志'],
        '商城管理' => ['shop' => '商城首页', 'order' => '订单管理', 'shipping' => '发货管理', 'refund' => '售后退款', 'review' => '商品评价', 'recharge' => '充值记录', 'payment' => '支付设置', 'shop_config' => '商城配置'],
    ];
}

function cmsAdminSuperOnlyModules()
{
    return ['admin_user', 'role', 'database', 'auth', 'version'];
}

function cmsNormalizeAdminPermissions($permissions)
{
    if (is_string($permissions)) {
        $permissions = json_decode($permissions, true);
    }
    if (!is_array($permissions)) {
        return [];
    }
    foreach (['modules', 'permissions', 'acts'] as $key) {
        if (isset($permissions[$key]) && is_array($permissions[$key])) {
            $permissions = $permissions[$key];
            break;
        }
    }
    $result = [];
    foreach ($permissions as $key => $value) {
        $permission = is_int($key) ? $value : ($value ? $key : '');
        $permission = strtolower(trim((string) $permission));
        if ($permission !== '' && preg_match('/^[a-z0-9_.]+$/', $permission)) {
            $result[$permission] = true;
        }
    }
    return array_keys($result);
}

function cmsLoadAdminAccess($db, $roleId)
{
    $roleId = intval($roleId);
    if ($roleId === 0) {
        return ['super' => true, 'role_id' => 0, 'role_name' => '超级管理员', 'permissions' => []];
    }
    $role = $db->fetch("SELECT id, role_name, permissions FROM {$db->table('role')} WHERE id = ? LIMIT 1", [$roleId]);
    if (!$role) {
        return ['super' => false, 'role_id' => $roleId, 'role_name' => '未配置角色', 'permissions' => []];
    }
    return [
        'super' => false,
        'role_id' => $roleId,
        'role_name' => trim((string) $role['role_name']),
        'permissions' => cmsNormalizeAdminPermissions($role['permissions'] ?? ''),
    ];
}

function cmsLoadCurrentAdminAccess($db)
{
    $adminId = intval($_SESSION['admin_id'] ?? 0);
    if ($adminId <= 0) {
        return ['super' => false, 'role_id' => -1, 'role_name' => '未登录', 'permissions' => [], 'active' => false];
    }
    $admin = $db->fetch("SELECT role_id, is_enabled FROM {$db->table('admin')} WHERE id = ? LIMIT 1", [$adminId]);
    if (!$admin || intval($admin['is_enabled'] ?? 0) !== 1) {
        return ['super' => false, 'role_id' => -1, 'role_name' => '账号已停用', 'permissions' => [], 'active' => false];
    }
    $_SESSION['admin_role'] = intval($admin['role_id']);
    $access = cmsLoadAdminAccess($db, $admin['role_id']);
    $access['active'] = true;
    return $access;
}

function cmsAdminCan($access, $module, $capability = 'view')
{
    if (isset($access['active']) && !$access['active']) {
        return false;
    }
    $module = strtolower(trim((string) $module));
    $capability = $capability === 'manage' ? 'manage' : 'view';
    if ($module === '' || in_array($module, ['dashboard', 'profile'], true)) {
        return true;
    }
    if (!empty($access['super'])) {
        return true;
    }
    if (in_array($module, cmsAdminSuperOnlyModules(), true)) {
        return false;
    }
    $aliases = ['content_list' => 'content', 'pay_order' => 'order', 'builder_api' => 'builder', 'builder_preview' => 'builder', 'upload' => 'upload'];
    $module = $aliases[$module] ?? $module;
    if ($module === 'upload') {
        foreach (['article', 'product', 'page', 'image', 'download', 'video', 'recruit', 'slide', 'link', 'ads', 'template', 'builder'] as $uploadModule) {
            if (cmsAdminCan($access, $uploadModule, 'manage')) { return true; }
        }
        return false;
    }
    $permissions = (array) ($access['permissions'] ?? []);
    if (in_array($module, $permissions, true) || in_array($module . '.manage', $permissions, true)) {
        return true;
    }
    return $capability === 'view' && in_array($module . '.view', $permissions, true);
}

function cmsAdminRequestCapability($method = null, $action = null)
{
    $method = strtoupper((string) ($method ?: ($_SERVER['REQUEST_METHOD'] ?? 'GET')));
    $action = strtolower(trim((string) ($action === null ? ($_REQUEST['action'] ?? '') : $action)));
    if ($method !== 'GET' && $method !== 'HEAD') {
        return 'manage';
    }
    return in_array($action, ['', 'list', 'view', 'detail', 'preview', 'search', 'config', 'permission', 'load'], true) ? 'view' : 'manage';
}

function cmsRequireAdminPermission($access, $module, $json = false, $capability = 'view')
{
    if (cmsAdminCan($access, $module, $capability)) {
        return true;
    }
    http_response_code(403);
    if ($json) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['code' => 403, 'msg' => $capability === 'manage' ? '当前角色只有查看权限，不能执行此操作' : '当前角色无权访问此模块'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    } else {
        echo '<div style="max-width:720px;margin:60px auto;padding:32px;border:1px solid #fecaca;border-radius:18px;background:#fff;color:#991b1b;text-align:center;"><h2 style="margin:0 0 12px;">无权访问</h2><p style="margin:0;color:#64748b;">当前管理员角色没有此模块权限，请联系超级管理员。</p></div>';
    }
    exit;
}
