<?php

namespace App\Http\Controllers;

use App\CustomClass\Helper;
use App\Models\ClientEvent;
use App\Models\ClientEventDetails;
use App\Models\ClientEventType;
use App\Models\ClientTimezone;
use App\Models\Rota;
use App\Models\UserGroup;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Session;
use Validator;
class EventsController extends Controller
{
    public function index(){
        $userGroup = UserGroup::where('client_id',Auth::user()->client_id)->pluck('title', 'id')->all();
        if($userGroup){
            foreach ($userGroup as $key =>$value){
                $defaultGroup= $key;
                break;
            }

            $eventType = ['' => 'Select Event type'] + ClientEventType::where('client_id',Auth::user()->client_id)->pluck('title', 'id')->all();
            $users= $this->getMembersByUserGroup('',$defaultGroup);
            return view('backend.events.index')->with('eventType',$eventType)->with('userGroup',$userGroup)->with('defaultGroup',$defaultGroup)->with('users',$users);
        }

    }

    public function saveEvent( Request $request){
        /* Serialize array to input value Start*/
        $userList= $request->user_list;
        $allVal= explode('&user_id=',$userList);
        $firstVal= explode('user_id=',$allVal[0]);
        $first=@$firstVal[1];
        $usersId=[];
            foreach ($allVal as $value){
                $usersId[]=$value;
            }
            unset($usersId[0]);
            if($first>0){
                $usersId[]=$first;
            }
        /* Serialize array to input value End*/
        if(count($usersId)<1){
            return json_encode(['error'=>'Please select user. If you think problem please refresh this page']);
        }
        if (($request->event_title==null)||($request->event_type==null)||($request->user_group_id==null)||($request->office_status==null)) {
            return json_encode(['error'=>'Please fill up event fields correctly !']);
        }
    try {
        $users = User::where('client_id',Auth::user()->client_id)->where('user_group_id',$request->user_group_id)->get();
        $usersArray= Helper::convertNumericArray($users,'id');
        $applicableUser= [];
        $notApplicableUser= [];
        foreach ($users as $user){
            foreach($usersId as $selected){
                if($user->id==$selected){
                    $applicableUser[]=$selected;
                }

            }
        }
        $notApplicableUser= array_diff($usersArray,$applicableUser);

        $event = new ClientEvent();
        $event->client_id = Auth::user()->client_id;
        $event->user_group_id = $request->user_group_id;
        $event->applicable_users = json_encode($applicableUser);
        $event->not_applicable_users = json_encode($notApplicableUser);
        $event->client_event_type_id = $request->event_type;
        $event->title = $request->event_title;
        $event->details = $request->details;
        $event->office_status = $request->office_status;
        $event->created_by = Auth::id();
        $event->updated_by = Auth::id();
        $event->save();
        if(count($request->selectedDate)>0) {
            foreach ($request->selectedDate as $date) {
                $eventDetails = new ClientEventDetails;
                $eventDetails->client_id = Auth::user()->client_id;
                $eventDetails->client_event_id = $event->id;
                $eventDetails->start = $date;
                $eventDetails->created_by = Auth::id();
                $eventDetails->updated_by = Auth::id();
                $eventDetails->save();
            }
        }else{
            return json_encode(['error'=>'Please pick a date from calendar!']);
        }
        Session::flash('currentMonth',$date);
        Session::flash('success','Successfully created !');
        return json_encode(['success'=>true]);
    }
        catch (\Exception $e){
            return json_encode(['error'=>'Something wrong. Please try again !']);
        }
    }
    public function getEvent( $userGroupId,$yearMonth){
        $result= DB::table('client_events as ce')->select('ce.title','ce.details','ce.office_status','ced.start','ced.id as client_event_detail_id')
            ->join('client_event_details as ced','ce.id','ced.client_event_id')
            ->where('ce.client_id',Auth::user()->client_id)
            ->where('ce.user_group_id',$userGroupId)
            ->where('ced.start','like',"$yearMonth%")
            ->get()
            ->toJson();
        return $result;
    }
    public function loadCalendar( $userGroupId){
        $result= DB::table('client_events as ce')->select('ce.title','ce.details','ce.office_status','ced.start')
            ->join('client_event_details as ced','ce.id','ced.client_event_id')
            ->where('ce.client_id',Auth::user()->client_id)
            ->where('ce.user_group_id',$userGroupId)
            ->get()
            ->toJson();
        return view('backend.events.loadCalendar')->with('result',$result);
    }
    public function deleteEvent( $client_event_detail_id){
        try{
            $eventDetails= ClientEventDetails::where('client_id',Auth::user()->client_id)->where('id',$client_event_detail_id)->first();
            if($eventDetails){
                $eventId=$eventDetails->client_event_id;
                $cal= ClientEventDetails::where('client_id',Auth::user()->client_id)->where('id',$client_event_detail_id)->delete();
                if($cal){
                    $remain=ClientEventDetails::where('client_event_id',$eventId)->count();
                    if($remain<1){
                        ClientEvent::destroy($eventId);
                    }
                    return json_encode(['success'=>'Event Deleted Successfully!']);
                }
            }
            else{
                return json_encode(['error'=>'Something wrong!']);
            }
        }
        catch (\Exception $e){
            return json_encode(['error'=>'Something wrong!']);
        }


    }
    public function getMembersByUserGroup($userGroupId){
        $users = User::where('client_id',Auth::user()->client_id)->where('user_group_id',$userGroupId)->where('status',1)->get();
        $new=[];
        foreach ($users as $user){
            $new[]=['id'=>$user->id,'name'=>$user->first_name." ".$user->last_name, 'email'=>$user->email];
        }
        return $new;
    }
    public function getEventByMonth( $userGroupId,$year,$month){
        $date= $year."-".$month;
        //DB::table()
        $eventDetails = ClientEventDetails::with('events')->with('events.type')
            ->where('client_id',Auth::user()->client_id)
            ->where('start','LIKE',"$date%")
            ->whereHas('events', function($query) use ($userGroupId) {
                $query->where('user_group_id', $userGroupId);
            })
            ->get();
        $results=[];
        foreach ($eventDetails as $val){
            $results[]=['date'=>$val->start,'title'=>$val->events->title,'type'=>$val->events->type->title];
        }
        return $results;
        $new=[];
        foreach ($users as $user){
            $new[]=['id'=>$user->id,'name'=>$user->first_name." ".$user->last_name, 'email'=>$user->email];
        }
        return $new;
    }
    public function selectEventType( $eventTypeId=null){
        if($eventTypeId==null){
            return json_encode(['error'=>'true']);
        }
        $res= ClientEventType::where('id',$eventTypeId)->where('client_id',Auth::user()->client_id)->first();
        if($res){
            return json_encode($res);
        }
    }

}
