<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class MenuPermission extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'menu_key',
        'menu_label',
        'menu_group',
        'menu_url',
        'is_visible',
        'sort_order',
        'additional_data',
    ];

    protected $casts = [
        'is_visible' => 'boolean',
        'sort_order' => 'integer',
        'additional_data' => 'array',
    ];

    /**
     * 获取用户的菜单权限
     */
    public static function getUserMenus(string $userId, bool $onlyVisible = true)
    {
        $query = self::where('user_id', $userId);

        if ($onlyVisible) {
            $query->where('is_visible', true);
        }

        return $query->orderBy('sort_order')->get();
    }

    /**
     * 检查菜单是否可见
     */
    public static function isMenuVisible(string $userId, string $menuKey): bool
    {
        $permission = self::where('user_id', $userId)
            ->where('menu_key', $menuKey)
            ->first();

        return $permission ? $permission->is_visible : true; // 默认为可见
    }

    /**
     * 设置菜单可见性
     */
    public static function setMenuVisibility(string $userId, string $menuKey, bool $visible): void
    {
        self::updateOrCreate(
            [
                'user_id' => $userId,
                'menu_key' => $menuKey,
            ],
            [
                'is_visible' => $visible,
                'menu_label' => self::getDefaultMenuLabel($menuKey),
            ]
        );
    }

    /**
     * 获取默认菜单标签
     */
    private static function getDefaultMenuLabel(string $menuKey): string
    {
        $labels = [
            'dashboard' => '仪表盘',
            'exam-history' => '考试历史',
            'exam-analysis' => '考试分析',
            'ocr-paper-grading' => 'OCR试卷批改',
            'intelligent-exam-generation' => '智能出卷',
            'knowledge-graph' => '知识图谱',
            'student-management' => '学生管理',
            'teacher-management' => '老师管理',
        ];

        return $labels[$menuKey] ?? ucfirst($menuKey);
    }
}
