<?php

namespace App\Http\Controllers;

use App\Models\Duration;
use App\Models\Plan;
use App\Models\Plantel;
use Illuminate\Http\Request;

use Illuminate\Routing\Controller;

class PlanController extends Controller
{

    public function __construct() {
        $this->middleware('can:plan.index')->only('index','show');
        $this->middleware('can:plan.create')->only('create','store');
        $this->middleware('can:plan.edit')->only('edit','update');
        $this->middleware('can:plan.destroy')->only('destroy');
    }
    public function index()
    {
        $plans = Plan::all();
        return view('plan.index',compact('plans'));
    }

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


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

        // dd($request);

        $plan = Plan::create($request->except(['plantels']));

        $plan->planesPlantel()->sync($request->plantels);

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


    public function show(Plan $plan)
    {
        return view('plan.show',compact('plan'));
    }


    public function edit(Plan $plan)
    {
        $plantels = Plantel::where('status','=','1')->get();
        $durations = Duration::all();
        return view('plan.edit',compact('plantels','durations','plan'));
    }


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

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

        $plan->planesPlantel()->sync($request->plantels);

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


    public function destroy(Plan $plan)
    {
        $plan->planesPlantel()->detach();
        $plan->delete();

        session()->flash('swal',[
            'icon'=>'success',
            'title'=>'Eliminado!',
            'text'=>'Se ha eliminado el registro correctamente'
        ]);
        return redirect()->route('plan.index');
    }
}
