<?php

namespace App\Http\Controllers;

use App\Models\Garage;
use App\Models\GarageService;
use Illuminate\Http\Request;

class GarageServiceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $services = GarageService::all();
        return view('configuration.Types.Service.index',compact('services'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        return view('configuration.Types.Service.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        GarageService::create([
            'service'=>$request->service
        ]);
        return redirect()->route('GarageService.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\GarageService  $garageService
     * @return \Illuminate\Http\Response
     */
    public function asign(Request $request , $id)
    {
        $garage = Garage::whereId($id)->first();
        $this->authorize('update',Garage::class);

        if ($request->has('service')) {
            $garage->garageservice()->detach();
            foreach ($request->service as $c) {
            $service = GarageService::findOrFail($c);
            $garage->garageservice()->syncWithoutDetaching($service);
            }
        }
        else{
            $garage->garageservice()->wherePivot('garage_id','=',$id)->detach();
        }
        return redirect()->back();
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\GarageService  $garageService
     * @return \Illuminate\Http\Response
     */
    public function edit( $id)
    {
        $service = GarageService::whereId($id)->first();
        return view('configuration.Types.Service.edit',compact('service'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\GarageService  $garageService
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,  $id)
    {
        $service = GarageService::whereId($id)->first();
        $service->service = $request->service;
        $service->update();
        return redirect()->route('GarageService.index');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\GarageService  $garageService
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $service = GarageService::whereId($id)->first();
        // $service->delete();
        return redirect()->route('GarageService.index');
    }
}
