<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use App\Models\Menu;

class MenuRoleController extends Controller
{
    public function menusByRole($id){
        $variable = DB::table('roles_has_menus')->where('id_role', $id)->get();
        return $variable;
    }
    
    public function syncData(Request $request){
        $roles = $request->roles;
        $totals = [];
            DB::table('roles_has_menus')->where('id_role', $roles)->delete();
            foreach ($request->get('menus') as $menu) {
                DB::table('roles_has_menus')->insert([
                    'id_menu' => $menu,
                    'id_role' => $roles,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
            }

        return response("success", 200);
    }

    public function listMenusByRol($id)
    {
        Role::resolveRelationUsing('menus', function ($model) {
            return $model->belongsToMany(Menu::class, 'roles_has_menus', 'id_role', 'id_menu');
        });
        $rol = Role::with(['menus'=>function($query){
            $query->where('activo', true);
          }])->findOrFail($id);
        if ($rol) {
            return $rol->menus;
        }
        return [];
    }
}
