<?php

namespace App\Http\Controllers;

use App\Models\Nivel;
use App\Models\Plantel;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

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

    public function index(): View
    {
        $plantels = Plantel::where('status','=','1')->get();
        $nivels = Nivel::all();
        return view('nivel.index',compact('nivels','plantels'));
    }

    public function create(): View
    {$plantels = Plantel::where('status','=','1')->get();
        return view('nivel.create',compact('plantels'));
    }

    public function store(Request $request)
    {
        $nivel = Nivel ::create($request->except(['plantels']));
        $nivel->nivelPlantel()->sync($request->plantels);
        return redirect()->route('nivel.edit',compact('nivel'))->with('info','Se creó el nivel correctamente');
    }

    public function edit(Nivel $nivel)
    {
        $plantels = Plantel::where('status','=','1')->get();
        return view('nivel.edit',compact('nivel','plantels'));
    }

    public function update(Request $request,Nivel $nivel )
    {
        $nivel ->update($request->except(['plantels']));
        $nivel->nivelPlantel()->sync($request->plantels);
        return redirect()->route('nivel.edit',compact('nivel'))->with('info','Se modificó el nivel correctamente');
    }

    public function show(Nivel $nivel )
    {
        return view('nivel.show',compact('nivel'));
    }

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