<?php

namespace App\Http\Controllers;

use App\Models\Plane;
use App\Models\Plantel;
use App\Models\Concepto;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

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

    public function index()
    {
        $planes=Plane::all();
        return view('plane.index',compact('planes'));
    }


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


    public function store(Request $request)
    {
        $request->validate([
            'name'=>'required'
        ]);

        $plane = Plane::create($request->all());

        return redirect()->route('plane.edit',$plane)->with('info','El plan se creo correctamente');

    }


    public function show(Plane $plane)
    {
        return view('plane.show',compact('plane'));
    }


    public function edit(Plane $plane)
    {  $planConceptos = $plane->conceptos;
        $plantels = Plantel::where('status','=','1')->get();
        $conceptos = Concepto::where('tipo','=','3')->get();

        return view('plane.edit',compact('plane','plantels','conceptos','planConceptos'));
    }

    public function update(Request $request,Plane $plane)
    {
          $request->validate([
            'name'=>'required'
        ]);

        $plane->update($request->except(['plantels']));

        $plane->planPlantel()->sync($request->plantels);

        return redirect()->route('plane.edit',$plane)->with('info','El plan se actualizo correctamente');
    }


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