<?php

namespace App\Http\Controllers;

use App\Models\MenuPermission;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Filament\Facades\Filament;

class MenuVisibilityController extends Controller
{
    public function toggle(Request $request): JsonResponse
    {
        // 验证请求
        $validated = $request->validate([
            'menu_key' => 'required|string',
            'user_id' => 'required',
            'is_visible' => 'required|boolean',
        ]);

        // 获取当前用户（使用Laravel的auth辅助函数）
        $user = auth()->user();

        if (!$user) {
            return response()->json(['error' => '未登录'], 401);
        }

        // 检查是否是管理员
        $isAdmin = $user->role === 'admin' ||
                   $user->username === '17689974321';

        if (!$isAdmin) {
            return response()->json(['error' => '权限不足'], 403);
        }

        try {
            // 更新菜单可见性
            MenuPermission::setMenuVisibility(
                $validated['user_id'],
                $validated['menu_key'],
                $validated['is_visible']
            );

            return response()->json([
                'success' => true,
                'message' => '菜单已' . ($validated['is_visible'] ? '显示' : '隐藏')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => '操作失败: ' . $e->getMessage()
            ], 500);
        }
    }
}
