<?php

namespace App\Http\Controllers\Admin;

use App\DayOff;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\DayOffTypes;

class DaysOffController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::all();

        return view('admin.dayOff.index')->with([
            'users'=> $users
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function view(Request $request)
    {
        // dd($request->user_id);
        $users = User::all();
        $selectedUser = User::find($request->user_id);
        $daysOff = $selectedUser->daysOff;
        $types = DayOffTypes::all();
        
        // dd($selectedUser);
        
        return view('admin.dayOff.view')->with([
            'users'=> $users,
            'selectedUser'=> $selectedUser,
            'daysOff'=> $daysOff,
            'types'=> $types,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $selectedUser = User::find($request->user_id);
        $daysOff = $selectedUser->daysOff->where('date', $request->date);

        // if day off already exist
        if(count($daysOff) > 0) {
            // validate this
        }

        $dayOffType = new DayOffTypes;
        if (isset($request->new_type)) {
            $dayOffType->type = $request->new_type;
            $dayOffType->save();
        }

        $dayOff = DayOff::create([
            'user_id' => $request->user_id,
            'date' => $request->date,
            'day_off_type_id' => isset($request->new_type) ? $dayOffType->id : $request->type_id,
        ]);
      
        return redirect('/admin/daysOff/'. $request->user_id . '/manage')->with('success', 'Day Off Added');
    }


    public function refresh($id) {

        $users = User::all();
        $selectedUser = User::find($id);
        $daysOff = $selectedUser->daysOff;
        $types = DayOffTypes::all();
                
        return view('admin.dayOff.view')->with([
            'users'=> $users,
            'selectedUser'=> $selectedUser,
            'daysOff'=> $daysOff,
            'types'=> $types,
        ]);
    }

    public function delete(Request $request) {      
        DayOff::destroy($request->day_off_id);
        return redirect('/admin/daysOff/'. $request->user_id . '/manage')->with('success', 'Day Off Deleted');
    }
}
