<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Plantel;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{

    public function __construct() {
        $this->middleware('can:user.index')->only('index','show');
        $this->middleware('can:user.create')->only('create','store');
        $this->middleware('can:user.edit')->only('edit','update');
        $this->middleware('can:user.destroy')->only('destroy');
    }

    public function index()
    {
        $plantels=Plantel::all();
        $users=User::with('roles')->get();
        return view('user.index',compact('users','plantels'));
    }


    public function create()
    {
        $plantels = Plantel::where('status','=','1')->get();
        $codigos = DB::table('area_code')->get();
        $roles= Role::all();
        return view('user.create',compact('roles','plantels','codigos'));
    }

    public function store(Request $request,User $user)
    {
        $user= User::create($request->except(['plantels']));
        $user->roles()->sync($request->roles);

        $user->plantelUsuarios()->sync($request->plantels);

        return redirect()->route('user.edit',compact('user'))->with('info','Se creó el usuario correctamente');
    }

    public function show(User $user)
    {
        return view('user.show',compact('user'));
    }

    public function edit(User $user)
    {
        $plantels=Plantel::all();
        $codigos = DB::table('area_code')->get();
        $roles= Role::all();
        return view('user.edit',compact('user','roles','plantels','codigos'));
    }

    public function update(Request $request, User $user)
    {
        $user->update($request->except(['plantels']));
        $user->roles()->sync($request->roles);
        $user->plantelUsuarios()->sync($request->plantels);
        return redirect()->route('user.edit',compact('user'))->with('info','Se modifico el usuario correctamente');
    }


    public function destroy(User $user)
    {
        $user->plantelUsuarios()->detach();
        $user->delete();
        session()->flash('swal',[
            'icon'=>'success',
            'title'=>'Eliminado!',
            'text'=>'Se ha eliminado el registro correctamente'
        ]);
        return redirect()->route('user.index');
    }

    public function profile(){
        return view('profile.show');
    }
}
