<?php

namespace App\Http\Controllers;

use App\Models\Substitute;
use App\Models\User;
use Illuminate\Http\Request;

class SubstituteController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

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

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'substitute_id'=>'required'
        ]);
        // Substitute::create([
        //     'user_id'=>$request->user_id,
        //     'substitute_id'=>$request->substitute_id
        // ]);
        
        $u = User::whereId($request->substitute_id)->first();
        if($u->name)
        {
            Substitute::updateOrCreate(['user_id'=>$request->user_id],
            [
                'substitute_id'=>$request->substitute_id
            ]);

        }

        return redirect()->route('user.show',$request->user_id);

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Substitute  $substitute
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = User::whereId($id)->with('substitute')->first();
        $substitutes = User::where('role_id',$user->role_id)->where('id','!=',$id)->get();
        if($user->substitute){
            $sub = User::whereId($user->substitute->substitute_id)->firstOrFail();
            $substitutes = User::where('role_id',$user->role_id)
            ->where('id','!=',$sub->id)
            ->where('id','!=',$id)->get();

        }
        else{
            $substitutes = User::where('role_id',$user->role_id)
            ->where('id','!=',$id)->get();
            $sub=null;
        }
        return view('configuration.user.subs',compact('user','substitutes','sub'));

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Substitute  $substitute
     * @return \Illuminate\Http\Response
     */
    public function edit(Substitute $substitute)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Substitute  $substitute
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Substitute $substitute)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Substitute  $substitute
     * @return \Illuminate\Http\Response
     */
    public function destroy(Substitute $substitute)
    {
        //
    }
}
