<?php

namespace App\Http\Controllers;

use App\CustomClass\Helper;
use App\Http\Requests\LeaveApplyRequest;
use App\Models\ClientEvent;
use App\Models\ClientEventDetails;
use App\Models\ClientLeaveType;
use App\Models\UserWiseExchange;
use App\Models\UserWiseLeave;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Validator;
class LeaveManagementController extends Controller
{
    public function  index(){
        $requests= UserWiseLeave::with('user','leaveType')->where('status','0')->where('client_id',Auth::user()->client_id)->get();
        $exchange= UserWiseExchange::with('user')->where('status','0')->where('client_id',Auth::user()->client_id)->get();
        return view('backend.leaveManage.index')->with('requests',$requests)->with('exchange',$exchange);
    }
    public function approvedOrDeny( Request $request){
        if($request->leaveId==null || $request->status==null){
            return "Wrong way trying...";
        }
        $leaveIdArray= explode(',',$request->leaveId);
        if(count($leaveIdArray)>0) {
            for ($i = 0; $i < count($leaveIdArray); $i++) {
                $leaveId = $leaveIdArray[$i];
                $leave = UserWiseLeave::where('id', $leaveId)->where('client_id', Auth::user()->client_id)->first();
                if ($leave) {
                    $leave->status = $request->status;
                    $leave->action_at = Carbon::now();
                    $leave->action_by = Auth::id();
                    $leave->save();
                    if ($request->status == 1) {
                        $duration = date_diff(date_create($leave->from_date), date_create($leave->to_date));
                        $t_duration = $duration->days + 1;
                        $user = User::where('id', $leave->user_id)->where('client_id', Auth::user()->client_id)->first();
                        $user->approved_leave = $user->approved_leave + $t_duration;
                        $user->save();
                        $request->session()->flash('success', 'Leave Approved Successfully!');
                    } else {
                        $request->session()->flash('error', 'Leave Denied Successfully!');
                    }
                } else {
                    $request->session()->flash('error', 'You are trying wrong way!');
                }
            }
        }


    }


    public function replyComment( Request $request){
        if($request->reply!=null){
            $leaveIdArray= explode(',',$request->leaveId);

            if(count($leaveIdArray)>0) {
                for ($i = 0; $i < count($leaveIdArray); $i++) {
                    $leaveId = $leaveIdArray[$i];
                    $new = UserWiseLeave::where('id', $leaveId)->where('client_id', Auth::user()->client_id)->first();
                    if($new){
                        $new->reply = $request->reply;
                        $new->save();
                    }
                }
            }
        }
    }
    public function myLeave(Request $request){
        if(isset($request->from_date) && isset($request->to_date)){
            $fromDate= $request->from_date;
            $toDate= $request->to_date;
            $queryData=['from_date'=>$fromDate,'to_date'=>$toDate];
            $leaves= UserWiseLeave::where(function ($query) use ($queryData) {
                    return $query->whereBetween('from_date',[$queryData['from_date'],$queryData['to_date']])
                        ->orWhereBetween('to_date',[$queryData['from_date'],$queryData['to_date']]);
                })
                ->where('user_id',Auth::id())->orderBy('from_date','DESC')->get();
        }else{
            $leaves= UserWiseLeave::with('leaveType')->where('user_id',Auth::id())->orderBy('from_date','DESC')->take(10)->get();
        }
        return view('backend.leaveManage.myLeave')->with('leaves',$leaves);
    }
    public function leaveApply(){
        $type= ClientLeaveType::where('client_id',Auth::user()->client_id)->pluck('title', 'id')->all();
        asort($type);
        $leaveType = [null => 'Select Leave Type'] +$type;
        return view('backend.leaveManage.leaveApplyModal')->with('leaveType',$leaveType);
    }
    public function leaveApplySave(Request $request){
        $error='';
        $clientId= Auth::user()->client_id;
        $userId= Auth::id();
        $fromDateArray= $request->from_date;
        $toDateArray= $request->to_date;
        $validator = Validator::make($request->all(),[
            'leave_type'=>'required',
            'message'=>'required',
            'from_date.*'=>'required|date_format:"Y-m-d"'
        ]);
        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $error){
                $error."<li>".$error."</li>";
            }
        }

        if(count($fromDateArray)==count($toDateArray)){
            for($i=0;$i<count($fromDateArray); $i++){
                $fromDate= $fromDateArray[$i];
                $toDate= $toDateArray[$i];
                if(($fromDate != null) && ($toDate != null)){
                    if(strtotime($toDate)<strtotime($fromDate)){
                        $error.="<li>FROM date is larger than TO date</li>";
                    }else{
                        $exists= DB::select("
                                        SELECT * FROM user_wise_leave WHERE
                                        (from_date BETWEEN '$fromDate' AND '$toDate' OR
                                        to_date BETWEEN '$fromDate' AND '$toDate' OR
                                        '$fromDate' BETWEEN from_date AND to_date) AND client_id='$clientId' AND user_id='$userId' AND status !='2' "
                                 );
                        //status: 0:pending,1:approved,2:deny
                        if(count($exists)>0){
                            $error.="<li>$fromDate &amp; $toDate Overlap with other leave!</li>";
                        }
                    }
                }
            }
            if(strlen($error)>4){
                return json_encode(['error'=>$error]);
            }else{
                for($i=0;$i<count($fromDateArray); $i++){
                    $fromDate= $fromDateArray[$i];
                    $toDate= $toDateArray[$i];
                    $duration= date_diff(date_create($fromDate),date_create($toDate));
                    $totalDuration= $duration->days+1;
                    $l= new UserWiseLeave();
                    $l->user_id= Auth::id();
                    $l->client_id= Auth::user()->client_id;
                    $l->client_leave_type_id=$request->leave_type;
                    $l->from_date= $fromDate;
                    $l->to_date= $toDate;
                    $l->duration= $totalDuration;
                    $l->message= $request->message;
                    $l->created_by= Auth::id();
                    $l->updated_by= Auth::id();
                    $l->save();
                }
                Session::flash('success','Leave application successful!');
                return json_encode(['success'=>'true']);
            }

        }else{
            return json_encode(['error'=>'Please don\'t try in wrong way']);
        }

    }
    public function leaveApplyDelete( $leaveId){
        $del = UserWiseLeave::where('id',$leaveId);

        $del->where('client_id',Auth::user()->client_id);
            if(!Helper::hasPermit('leave-manage')) {
                $del->where('status', '!=', 1)
                    ->where('user_id', Auth::id());
            }
        $del->delete();
        if($del){
            return redirect()->back()->with('success',"Application removed Successfully !");
        }else{
            return redirect()->back()->with('error',"You can't deleted approved leave !");
        }
    }
    public function leaveApplyEdit( $leaveId){
        $type= ClientLeaveType::where('client_id',Auth::user()->client_id)->pluck('title', 'id')->all();
        asort($type);
        $leaveType = [null => 'Select Leave Type'] +$type;
        $leave= UserWiseLeave::where('id',$leaveId)->where('user_id',Auth::id())->first();
        return view('backend.leaveManage.leaveApplyEdit')->with('leaveType',$leaveType)->with('leave',$leave);
    }
    public function leaveApplyUpdate( Request $request){
        $leave= UserWiseLeave::where('id',$request->leaveId)->where('status','!=','1')->where('client_id',Auth::user()->client_id)->first();
        $clientId= Auth::user()->client_id;
        $userId= Auth::id();
        if($leave){
            $error='';
            $fromDate= $request->from_date;
            $toDate= $request->to_date;
            $validator = Validator::make($request->all(),[
                'leave_type'=>'required',
                'edit_message'=>'required',
                'from_date'=>'required|date_format:"Y-m-d"',
                'to_date'=>'required|date_format:"Y-m-d"'
            ]);
            if ($validator->fails()) {
                foreach ($validator->errors()->all() as $error){
                    $error."<li>".$error."</li>";
                }
            }

                    if(($fromDate != null) && ($toDate != null)){
                        if(strtotime($toDate)<strtotime($fromDate)){
                            $error.="<li>FROM date is larger than TO date</li>";
                        }else{
                            $exists= DB::select("
                                        SELECT * FROM user_wise_leave WHERE
                                        ( from_date BETWEEN '$fromDate' AND '$toDate' OR
                                        to_date BETWEEN '$fromDate' AND '$toDate' OR
                                        '$fromDate' BETWEEN from_date AND to_date ) AND id != '$request->leaveId' AND client_id='$clientId' AND user_id='$userId' AND status !='2' "
                            );
                            if(count($exists)>0){
                                $error.="<li>$fromDate &amp; $toDate Overlap with other leave!</li>";
                            }
                        }
                    }

                if(strlen($error)>4){
                    return json_encode(['error'=>$error]);
                }else{
                        $duration= date_diff(date_create($fromDate),date_create($toDate));
                        $totalDuration= $duration->days+1;
                        $leave->client_leave_type_id = $request->leave_type;
                        $leave->from_date = $fromDate;
                        $leave->to_date = $toDate;
                        $leave->duration = $totalDuration;
                        $leave->message = $request->edit_message;
                        $leave->updated_by = Auth::id();
                        $leave->save();
                        Session::flash('success','Leave application updated successfully!');
                        return json_encode(['success'=>'true']);


                }


        }else{
            return json_encode(['error'=>'Please don\'t try in wrong way']);
        }
    }
    public function leaveNotificationUpdate($leaveId){
        $l =UserWiseLeave::where('id',$leaveId)->where('user_id',Auth::id())->update(['viewed'=>1]);
        if($l){
            return json_encode(['status'=>'success']);
        }
    }
    public function holidayExchange( Request $request){
        if(isset($request->from_date) && isset($request->to_date)){
            $fromDate= $request->from_date;
            $toDate= $request->to_date;
            $result= UserWiseExchange::whereBetween('holiday_date',[$fromDate,$toDate])->orWhereBetween('desire_date',[$fromDate,$toDate])->where('user_id',Auth::id())->where('client_id',Auth::user()->client_id)->orderBy('desire_date','DESC')->get();
        }else{
            $result= UserWiseExchange::where('user_id',Auth::id())->where('client_id',Auth::user()->client_id)->orderBy('desire_date','DESC')->take(10)->get();
        }
        return view('backend.holidayExchange.index')->with('results',$result);
    }
    public function exchangeApply(){
        return view('backend.holidayExchange.exchangeModal');
    }
    public function exchangeApplySave( Request $request){
        $error='';
        $holidayDate= $request->holiday_date;
        $desireDate= $request->desire_date;

        $validator = Validator::make($request->all(),[
            'desire_date'=>'required',
            'holiday_date'=>'required',
            'message'=>'required',
        ]);
        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $v_error){
                $error.="<li>".$v_error."</li>";
            }
        }
        if($desireDate==$holidayDate){
            $error.="<li>Both date are same!</li>";
        }
        if(strlen($error)>1){
            return json_encode(['error'=>$error]);
        }
            $dates= ['holiday'=>$holidayDate,'desire'=>$desireDate];
            /*Check holiday event for exchange*/
            $eventDetails= ClientEventDetails::with('events')
                            ->where('client_id',Auth::user()->client_id)
                            ->where('start',$holidayDate)
                            ->whereHas('events', function ($query) {
                                return $query->where('user_group_id',Auth::user()->user_group_id)
                                             ->where('office_status','0');
                            })->get();
            if($eventDetails){
                $found=0;
                foreach ($eventDetails as $detail){
                    $users = json_decode($detail->events->applicable_users);
                    if(in_array(Auth::id(),$users)){
                        $found=1; break;
                    }
                }

            }  /*End of holiday event check*/

            if($found==1){//holiday found
                $exists= UserWiseExchange::where('user_id',Auth::id())
                    ->where('client_id',Auth::user()->client_id)
                    ->where('status','!=','2') //deny
                    ->where(function ($query) use ($dates){
                            return $query->where('desire_date',$dates['holiday'])
                                ->orWhere('holiday_date',$dates['holiday'])
                                ->orWhere('holiday_date',$dates['desire'])
                                ->orWhere('desire_date',$dates['desire']);
                    })->count();
                if($exists>0){
                    $error.="<li>".$dates['holiday']." or ".$dates['desire']." Overlap with other days!</li>";
                    return json_encode(['error'=>$error]);
                }else{
                    $exchange= new UserWiseExchange();
                    $exchange->user_id = Auth::id();
                    $exchange->client_id = Auth::user()->client_id;
                    $exchange->holiday_date = $holidayDate;
                    $exchange->desire_date = $desireDate;
                    $exchange->message = $request->message;
                    $exchange->created_by= Auth::id();
                    $exchange->updated_by= Auth::id();
                    $exchange->save();
                    Session::flash('success','Holiday exchange applied successfully!');
                    return json_encode(['success'=>'true']);
                }
            }else{
                return json_encode(['error'=>"<li>Sorry ! ". $dates['holiday']." is not holiday!</li>"]);
            }
    }
    public function exchangeEdit( $userWiseExchangeId){
        $result= UserWiseExchange::where('id',$userWiseExchangeId)->where('user_id',Auth::id())->where('client_id',Auth::user()->client_id)->first();
        return view('backend.holidayExchange.exchangeEditModal')->with('result',$result);
    }
    public function  exchangeEditSave( Request $request){
        $error='';
        $holidayDate= $request->holiday_date;
        $desireDate= $request->desire_date;

        $validator = Validator::make($request->all(),[
            'desire_date'=>'required',
            'holiday_date'=>'required',
            'message'=>'required',
        ]);
        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $v_error){
                $error.="<li>".$v_error."</li>";
            }
        }
        if($desireDate==$holidayDate){
            $error.="<li>Both date are same!</li>";
        }
        if(strlen($error)>1){
            return json_encode(['error'=>$error]);
        }
        $exchange= UserWiseExchange::where('id',$request->exchangeId)->where('user_id',Auth::id())->where('client_id',Auth::user()->client_id)->first();
        if($exchange){
            if(($exchange->holiday_date==$request->holiday_date) && ($exchange->desire_date==$request->desire_date)){ //this is for preventing complexity
                $exchange->message= $request->message;
                $exchange->save();
                Session::flash('success','Holiday exchange updated successfully!');
                return json_encode(['success'=>'true']);
            }

            $dates= ['holiday'=>$holidayDate,'desire'=>$desireDate];
            /*Check holiday event for exchange*/
            $eventDetails= ClientEventDetails::with('events')
                ->where('client_id',Auth::user()->client_id)
                ->where('start',$holidayDate)
                ->whereHas('events', function ($query) {
                    return $query->where('user_group_id',Auth::user()->user_group_id)
                        ->where('office_status','0');
                })->get();
            if($eventDetails){
                $found=0;
                foreach ($eventDetails as $detail){
                    $users = json_decode($detail->events->applicable_users);
                    if(in_array(Auth::id(),$users)){
                        $found=1; break;
                    }
                }

            }  /*End of holiday event check*/

            if($found==1){//holiday found
                $exists= UserWiseExchange::where('user_id',Auth::id())
                    ->where('id','!=',$request->exchangeId)
                    ->where('client_id',Auth::user()->client_id)
                    ->where('status','!=','2') //deny
                    ->where(function ($query) use ($dates){
                        return $query->where('desire_date',$dates['holiday'])
                            ->orWhere('holiday_date',$dates['holiday'])
                            ->orWhere('holiday_date',$dates['desire'])
                            ->orWhere('desire_date',$dates['desire']);
                    })->count();
                if($exists>0){
                    $error.="<li>".$dates['holiday']." or ".$dates['desire']." Overlap with other days!</li>";
                    return json_encode(['error'=>$error]);
                }else{
                    $exchange->holiday_date = $holidayDate;
                    $exchange->desire_date = $desireDate;
                    $exchange->message = $request->message;
                    $exchange->updated_by= Auth::id();
                    $exchange->save();
                    Session::flash('success','Holiday exchange updated successfully!');
                    return json_encode(['success'=>'true']);
                }
            }else{
                return json_encode(['error'=>"<li>Sorry ! ". $dates['holiday']." is not holiday!</li>"]);
            }
        }
    }
    public function exchangeDelete( $exchangeId){
        $del = UserWiseExchange::where('id',$exchangeId)->where('status','!=',1)->where('client_id',Auth::user()->client_id)->where('user_id',Auth::id())->delete();
        if($del){
            return redirect()->back()->with('success',"Application removed Successfully !");
        }else{
            return redirect()->back()->with('error',"You can't deleted approved exchange !");
        }
    }
    public function exchangeNotificationUpdate($exchangeId){
        $e =UserWiseExchange::where('id',$exchangeId)->where('user_id',Auth::id())->update(['viewed'=>1]);
        if($e){
            return json_encode(['status'=>'success']);
        }
    }
    public function exchangeApprovedOrDeny( Request $request){
        if($request->exchangeId==null || $request->status==null){
            return "Wrong way trying...";
        }
        $exchangeIdArray= explode(',',$request->exchangeId);
        if(count($exchangeIdArray)>0) {
            for ($i = 0; $i < count($exchangeIdArray); $i++) {
                $exchangeId = $exchangeIdArray[$i];
                $leave = UserWiseExchange::where('id', $exchangeId)->where('client_id', Auth::user()->client_id)->first();
                if ($leave) {
                    $leave->status = $request->status;
                    $leave->action_at = Carbon::now();
                    $leave->action_by = Auth::id();
                    $leave->save();
                    if ($request->status == 1) {
                        $request->session()->flash('success', 'Exchange Approved Successfully!');
                    } else {
                        $request->session()->flash('error', 'Exchange Denied Successfully!');
                    }
                } else {
                    $request->session()->flash('error', 'You are trying wrong way!');
                }
            }
        }


    }
    public function replyExchangeComment( Request $request){
        if($request->reply!=null){
            $exchangeIdArray= explode(',',$request->exchangeId);

            if(count($exchangeIdArray)>0) {
                for ($i = 0; $i < count($exchangeIdArray); $i++) {
                    $exchangeId = $exchangeIdArray[$i];
                    $new = UserWiseExchange::where('id', $exchangeId)->where('client_id', Auth::user()->client_id)->first();
                    if($new){
                        $new->reply = $request->reply;
                        $new->save();
                    }
                }
            }
        }
    }
}
