<?php

namespace App\Http\Controllers;

use App\Models\Sms;
use App\Models\Step;
use Illuminate\Http\Request;

class SmsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->authorize('viewAny',Sms::class);
        $smss = Sms::with('step')->get();
        return view('configuration.sms.index', compact('smss'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create',Sms::class);
        $steps = Step::whereDoesntHave('sms')->get();
        return view('configuration.sms.create',compact('steps'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->authorize('create',Sms::class);
        $this->validate($request, [
            'message' =>'required',
            'step'=>'required|unique:sms,step_id'
        ]);

        Sms::create([
            'message' => $request->message,
            'step_id'=>$request->step
        ]);

        return redirect()->route('SMS.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Sms  $sms
     * @return \Illuminate\Http\Response
     */
    public function show(Sms $sms)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Sms  $sms
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->authorize('update',Sms::class);
        $sms = Sms::whereId($id)->with('step')->firstOrFail();
        return view('configuration.sms.edit', compact('sms'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Sms  $sms
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->authorize('update',Sms::class);
        $sms = Sms::whereId($id)->firstOrFail();

        $this->validate($request, [
            'message' =>'required',

        ]);
        $sms->message = $request->message;
        $sms->update();
        return redirect()->route('SMS.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Sms  $sms
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authorize('delete',Sms::class);
        $sms = Sms::whereId($id)->firstOrFail();
        $sms->delete();
        return redirect()->route('SMS.index')->with('success','SMS Supprimé avec Succés');
    }
}
