<?php

namespace App\Http\Controllers\API\v1\Employee;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\RoleUser;
use App\Models\Role;
use App\Models\GiftCard;
use App\Models\UserProfile;
use App\Models\ChallengeCategory;
use App\Models\Challenge;
use App\Models\CompanyEmployeeLocation;
use App\Models\CompanyLocationAdmin;
use App\Models\ChallengeQuestionAnswer;
use App\Models\ChallengeEmployeeAnswer;
use App\Models\UserCreditPoint;
use App\Models\Message;
use App\Models\WeeklyTip;
use Validator;
use DB, Hash, Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;
use Exception;
use App\Traits\ApiResponseTrait;
use App\Traits\CommonTrait;
use App\Traits\ApiEmployeeTrait;
use App\Services\DefaultServices;

class ChallengeController extends Controller {

    use ApiResponseTrait, CommonTrait, ApiEmployeeTrait;

    protected $defaultServices;

    public function __construct(DefaultServices $defaultServices)
    {
        $this->defaultServices = $defaultServices;
    }

    public function getchallengeCategory($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';

        try
        {
            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end
            $status_code = 1;
            $allChallengeCategory  =  ChallengeCategory::all();
            foreach ($allChallengeCategory as $key => $challengeCategory) {
                $category_image_url = '';
                if($challengeCategory->image){
                    $rootFolderPath = 'challenge/categories/app_icon';
                    $whiterootFolderPath = 'challenge/categories';
                    $category_image_url = $this->defaultServices->getImgPath($rootFolderPath, $challengeCategory->image, 'blue_app_icon');
                    $category_white_image_url = $this->defaultServices->getImgPath($whiterootFolderPath, $challengeCategory->app_icon, 'app_icon');
                }
                
                $challengeArr[$key]['challenge_id']              = $challengeCategory->id;
                $challengeArr[$key]['challenge_image_url']       = $category_image_url;
                $challengeArr[$key]['challenge_image_url_white'] = $category_white_image_url;
                $challengeArr[$key]['challenge_name']            = $challengeCategory->name;
                $challengeArr[$key]['isComingSoon']              = ($challengeCategory->id == 3) ? true : false;
            }

            $date = Carbon::createFromFormat('Y-m-d',date('Y-m-d'));
            $day = $date->format('d');
            Carbon::setWeekStartsAt(Carbon::SUNDAY);
            Carbon::setWeekEndsAt(Carbon::SATURDAY);
            $date->startOfWeek(Carbon::SUNDAY);
            $date->endOfWeek(Carbon::SATURDAY);
            $weekNumber = $date->weekOfMonth;
            if($weekNumber == 1 && $day > 20) {
                $weekNumber = 5;
            }

            $weeklytip = WeeklyTip::where('week_no',$weekNumber)->where('is_active',1)->first();
           // if($weeklytip->count() > 0){
           if(count($weeklytip)> 0){
                $weeklytips = $weeklytip->tips_description;
            }else{
                $weeklytips = '';
            }
            $success['weeknumber'] = $weekNumber;
            $success['tips_text'] =  $weeklytips;
            $success['user_id'] = $userDetails->id;            
            $success['home_challenge_list'] = $challengeArr;



            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }

    public function getEmployeeChallenges($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';

        try
        {
            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end

            $messages = [
                'page_count.required' => 'Please enter page count',
                'page_size.required' => 'Please enter page size',
                'device_type.required' => 'Please enter device type',
            ];

            $validator = Validator::make($inputs,[
                "page_count" => "required",
                "page_size" => "required",
                "device_type" => 'required|in:ios,ioS,iOS,Android,android',
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $companyDetails = $userDetails->employeeCompany;
            $activeCompanyLocation = $userDetails->employeeCompanyActiveLocation;
            $extraParam['current_company_id'] = $companyDetails->id;
            $extraParam['current_location_id'] = $activeCompanyLocation->id;

            // update user profile
            if($inputs['time_zone']){
                $userDetails->userProfile->time_zone = $inputs['time_zone'];
                $userDetails->userProfile->save();
            }


            $current_datetime = date('Y-m-d H:i:s', $inputs['current_local_timestamp']);
            $extraParam['current_datetime'] = $current_datetime;
            
            //dd($current_datetime);
            $filterArr['is_active'] = 1;
            $filterOtherArr['current_datetime'] = $current_datetime;
            $filterOtherArr['current_date'] = date("Y-m-d", strtotime($current_datetime));
            $filterOtherArr['current_time'] = date("H:i:s", strtotime($current_datetime));
            $filterOtherArr['current_company_id'] = $companyDetails->id;
            $filterOtherArr['current_location_id'] = $activeCompanyLocation->id;
            $filterOtherArr['user_id'] = $userDetails->id;

            $allChallenges = Challenge::where($filterArr)->with('getAssignedCompany')
                            ->where(function($query) use($filterOtherArr) {
                                // super admin challenges
                                $query->where(function($query) use($filterOtherArr) {
                                    $query->where("created_by_admin_type", 1)
                                    ->where(function($query) use($filterOtherArr) {
                                        // daily challenges
                                        $query->where(function($query) use($filterOtherArr) {
                                            $query->where("challenge_type", 2);
                                            $query->where(DB::raw('CONCAT(challenges.start_date, \' \', challenges.start_time)'), "<=", $filterOtherArr['current_datetime']);
                                            $query->where(DB::raw('CONCAT(challenges.end_date, \' \', challenges.end_time)'), ">", $filterOtherArr['current_datetime']);

                                            // checking has no employee answer and has employee answer of same day or not
                                            $query->whereDoesntHave("employeeLatestAnswer", function($query) use($filterOtherArr) {
                                                $query->where("user_id", $filterOtherArr['user_id']);
                                                $query->where('company_id', $filterOtherArr['current_company_id']);
                                                $query->where('company_location_id', $filterOtherArr['current_location_id']);
                                                $query->whereDate("submission_datetime", $filterOtherArr['current_date']);
                                            });

                                            $query->where(function($query) use($filterOtherArr) {
                                                // global challenge
                                                $query->where(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_super_admin", 1);
                                                })
                                                // company specific challenge
                                                ->orWhere(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_super_admin", 2);

                                                    $query->where(function($query) use($filterOtherArr) {
                                                        // All locations
                                                        $query->whereHas('assignedCompany', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('approve_status', 1);
                                                            $query->where('location_type', 1);
                                                        });
                                                        // location specific
                                                        $query->orWhereHas('assignedCompanyLocation', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('company_location_id', $filterOtherArr['current_location_id']);
                                                            $query->where('approve_status', 1);
                                                        });
                                                    });
                                                });
                                            });
                                        })
                                        // normal challenges
                                        ->orWhere(function($query) use($filterOtherArr) {
                                            $query->where("challenge_type",  1);
                                            $query->where(DB::raw('CONCAT(challenges.start_date, \' \', challenges.start_time)'), "<=", $filterOtherArr['current_datetime']);
                                            $query->where(DB::raw('CONCAT(challenges.end_date, \' \', challenges.end_time)'), ">", $filterOtherArr['current_datetime']);

                                            // checking has no employee answer and has employee answer of same day or not
                                            $query->whereDoesntHave("employeeLatestAnswer", function($query) use($filterOtherArr) {
                                                $query->where("user_id", $filterOtherArr['user_id']);
                                                $query->where('company_id', $filterOtherArr['current_company_id']);
                                                $query->where('company_location_id', $filterOtherArr['current_location_id']);

                                                $query->where(function($query) use($filterOtherArr) {
                                                    // Questionnaire Challenge
                                                    $query->where(function($query) use($filterOtherArr) {
                                                        $query->where("challenge_taking_type_id", 1);

                                                        $query->where(function($query) use($filterOtherArr) {
                                                            // correct answer
                                                            $query->where("is_correct_answer", 1);
                                                            // wrong answer and wait 48 hours
                                                            $query->orWhere(function($query) use($filterOtherArr) {
                                                                $query->where("is_correct_answer", 0);
                                                                $query->where("submission_datetime", ">", date('Y-m-d H:i:s', strtotime($filterOtherArr['current_datetime']." -2 days")));
                                                            });
                                                        });                                                        
                                                    });
                                                    // Photo Taken Challenge
                                                    $query->orWhere(function($query) use($filterOtherArr) {
                                                        $query->where("challenge_taking_type_id", 2);

                                                        $query->where(function($query) use($filterOtherArr) {
                                                            // correct or pending answer
                                                            $query->whereIn("is_approved", [0, 1]);
                                                            // wrong answer and wait 48 hours
                                                            $query->orWhere(function($query) use($filterOtherArr) {
                                                                $query->where("is_approved", 2);
                                                                $query->where("rejection_datetime", ">", date('Y-m-d H:i:s', strtotime($filterOtherArr['current_datetime']." -2 days")));
                                                            });
                                                        });
                                                    });
                                                });
                                            });

                                            $query->where(function($query) use($filterOtherArr) {
                                                // global challenge
                                                $query->where(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_super_admin", 1);
                                                })
                                                // company specific challenge
                                                ->orWhere(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_super_admin", 2);

                                                    $query->where(function($query) use($filterOtherArr) {
                                                        // All locations
                                                        $query->whereHas('assignedCompany', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('approve_status', 1);
                                                            $query->where('location_type', 1);
                                                        });
                                                        // location specific
                                                        $query->orWhereHas('assignedCompanyLocation', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('company_location_id', $filterOtherArr['current_location_id']);
                                                            $query->where('approve_status', 1);
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    });
                                })
                                // company admin challenges
                                ->orWhere(function($query) use($filterOtherArr) {
                                    $query->where("created_by_admin_type", 2);

                                    // respective company challenges
                                    $query->whereHas('assignedCompany', function ($query) use($filterOtherArr) {
                                        $query->where('company_id', $filterOtherArr['current_company_id']);
                                        $query->where('approve_status', 1);
                                    })

                                    ->where(function($query) use($filterOtherArr) {
                                        // daily challenges
                                        $query->where(function($query) use($filterOtherArr) {
                                            $query->where("challenge_type", 2);
                                            $query->where(DB::raw('CONCAT(challenges.start_date, \' \', challenges.start_time)'), "<=", $filterOtherArr['current_datetime']);
                                            $query->where(DB::raw('CONCAT(challenges.end_date, \' \', challenges.end_time)'), ">", $filterOtherArr['current_datetime']);

                                            // checking has no employee answer and has employee answer of same day or not
                                            $query->whereDoesntHave("employeeLatestAnswer", function($query) use($filterOtherArr) {
                                                $query->where("user_id", $filterOtherArr['user_id']);
                                                $query->where('company_id', $filterOtherArr['current_company_id']);
                                                $query->where('company_location_id', $filterOtherArr['current_location_id']);
                                                $query->whereDate("submission_datetime", $filterOtherArr['current_date']);
                                            });

                                            $query->where(function($query) use($filterOtherArr) {
                                                // global/all locations
                                                $query->where(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_company", 1);
                                                })
                                                // locations specific
                                                ->orWhere(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_company", 2);

                                                    $query->where(function($query) use($filterOtherArr) {
                                                        // check location type
                                                        $query->whereHas('assignedCompany', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('approve_status', 1);
                                                            $query->where('location_type', 0);
                                                        });
                                                        // find respective location
                                                        $query->whereHas('assignedCompanyLocation', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('company_location_id', $filterOtherArr['current_location_id']);
                                                            $query->where('approve_status', 1);
                                                        });
                                                    });
                                                });
                                            });
                                        })

                                        // normal challenges
                                        ->orWhere(function($query) use($filterOtherArr) {
                                            $query->where("challenge_type",  1);
                                            $query->where(DB::raw('CONCAT(challenges.start_date, \' \', challenges.start_time)'), "<=", $filterOtherArr['current_datetime']);
                                            $query->where(DB::raw('CONCAT(challenges.end_date, \' \', challenges.end_time)'), ">", $filterOtherArr['current_datetime']);

                                            // checking has no employee answer and has employee answer of same day or not
                                            $query->whereDoesntHave("employeeLatestAnswer", function($query) use($filterOtherArr) {
                                                $query->where("user_id", $filterOtherArr['user_id']);
                                                $query->where('company_id', $filterOtherArr['current_company_id']);
                                                $query->where('company_location_id', $filterOtherArr['current_location_id']);

                                                $query->where(function($query) use($filterOtherArr) {
                                                    // Questionnaire Challenge
                                                    $query->where(function($query) use($filterOtherArr) {
                                                        $query->where("challenge_taking_type_id", 1);

                                                        $query->where(function($query) use($filterOtherArr) {
                                                            // correct answer
                                                            $query->where("is_correct_answer", 1);
                                                            // wrong answer and wait 48 hours
                                                            $query->orWhere(function($query) use($filterOtherArr) {
                                                                $query->where("is_correct_answer", 0);
                                                                $query->where("submission_datetime", ">", date('Y-m-d H:i:s', strtotime($filterOtherArr['current_datetime']." -2 days")));
                                                            });
                                                        });                                                        
                                                    });
                                                    // Photo Taken Challenge
                                                    $query->orWhere(function($query) use($filterOtherArr) {
                                                        $query->where("challenge_taking_type_id", 2);

                                                        $query->where(function($query) use($filterOtherArr) {
                                                            // correct or pending answer
                                                            $query->whereIn("is_approved", [0, 1]);
                                                            // wrong answer and wait 48 hours
                                                            $query->orWhere(function($query) use($filterOtherArr) {
                                                                $query->where("is_approved", 2);
                                                                $query->where("rejection_datetime", ">", date('Y-m-d H:i:s', strtotime($filterOtherArr['current_datetime']." -2 days")));
                                                            });
                                                        });
                                                    });
                                                });
                                            });

                                            $query->where(function($query) use($filterOtherArr) {
                                                // global/all locations
                                                $query->where(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_company", 1);
                                                })
                                                // locations specific
                                                ->orWhere(function($query) use($filterOtherArr) {
                                                    $query->where("type_by_company", 2);

                                                    $query->where(function($query) use($filterOtherArr) {
                                                        // check location type
                                                        $query->whereHas('assignedCompany', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('approve_status', 1);
                                                            $query->where('location_type', 0);
                                                        });
                                                        // find respective location
                                                        $query->whereHas('assignedCompanyLocation', function ($query) use($filterOtherArr) {
                                                            $query->where('company_id', $filterOtherArr['current_company_id']);
                                                            $query->where('company_location_id', $filterOtherArr['current_location_id']);
                                                            $query->where('approve_status', 1);
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    });
                                })
                                // location admin challenges
                                ->orWhere(function($query) use($filterOtherArr) {
                                    $query->where("created_by_admin_type", 3)
                                    ->where(function($query) use($filterOtherArr) {
                                    });
                                });
                            })
                            ->where('challenge_category_id', $inputs['challenge_category_id'])
                            ->where('is_active', 1)
                            ->whereIn('created_by_admin_type', [1, 2])//need to remove
                            ->orderBy('id', 'desc');


            $success['user_id'] = $userDetails->id;
            $success['total_count'] = $allChallenges->count();
            $success['available_challenges_list'] = [];

            $limit  = ($inputs['page_size'] <= 0) ? 10 : $inputs['page_size'];
            $offset = ($inputs['page_count'] <= 0) ? 1 : $inputs['page_count'];
            $offset = ($limit * $offset) - $limit;

            $allChallenges = $allChallenges->offset($offset)->limit($limit);
            $status_code = 1;

            if($allChallenges->get()->count()) {
                foreach ($allChallenges->cursor() as $key => $challenge) {
                    $challengeArr = [];
                   // dd($challenge);
                    $challengeArr['challenge_id'] = $challenge->id??0;
                    $challengeArr['start_date'] = $challenge->start_date??'';
                    $challengeArr['start_time'] = $challenge->start_time??'';
                    $challengeArr['end_date'] = $challenge->end_date??'';
                    $challengeArr['end_time'] = $challenge->end_time??'';
                    $challengeArr['challenge_type_name'] = strtoupper($challenge->getChallengeTakingType->name??'');
                    $challengeArr['challenge_type_id'] = $challenge->getChallengeTakingType->id??0;
                    $challengeArr['challenge_expiry_date'] = strtotime($challenge->end_date);
                    $challengeArr['challenge_type'] = $challenge->challenge_type==1?"Normal Challenge":"Daily Challenge";
                    $challengeArr['challenge_title'] = ($challenge->challenge_taking_type==1) ? $challenge->challenge_question : $challenge->challenge_name;

                    array_push($success['available_challenges_list'], $challengeArr);
                }
            }

            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }

    
    public function submitQuestionnaire($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';

        try
        {
            $messages = [
                'questionnaire_challenge_id.required' => 'Please enter challenge id',
                'answer_id.required' => 'Please enter answer id'
            ];

            $validator = Validator::make($inputs,[
                "questionnaire_challenge_id" => "required",
                "answer_id"                  => "required"
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end
            $status_code = 1;
            $whereArr = array(
                            'user_id'         =>$userDetails->id,
                            'active_location' => 1
                            );
            $userActiveLocation       = CompanyEmployeeLocation::where($whereArr)->first();
            $answerDetails            = ChallengeQuestionAnswer::where('id',$inputs['answer_id'])->first();
            $challengeDetails         = Challenge::where('id',$inputs['questionnaire_challenge_id'])->first();
            $challengeCategoryDetails = ChallengeCategory::where('id',$challengeDetails->challenge_category_id)->first();
            
            // $categoryFolderPath = 'challenge/categories';
            // $category_image_url = $this->defaultServices->getImgPath($categoryFolderPath, $challengeCategoryDetails->image, 'api');
            $categoryFolderPath = 'challenge/categories/app_icon';
            $category_image_url = $this->defaultServices->getImgPath($categoryFolderPath, $challengeCategoryDetails->image, 'blue_app_icon');
            $correctAnswerDetails = ChallengeQuestionAnswer::where('challenge_id',$inputs['questionnaire_challenge_id'])->where('is_correct',1)->first();

            $insert_emp_ans_arr     = array(
                                        'challenge_taking_type_id'=>1,
                                        'challenge_id'=>$answerDetails->challenge_id,
                                        'challenge_question_answer_id'=>$answerDetails->id,
                                        'is_correct_answer'=>($answerDetails->is_correct == 1) ?  1 :    0,
                                        'is_approved'=> 1,
                                        'user_id'=> $userDetails->id,
                                        'company_id'=> $userActiveLocation->company_id,
                                        'company_location_id'=> $userActiveLocation->location_id,
                                        'submission_datetime'=> date('Y-m-d H:i:s'),
                                        'is_point_credited'=> ($answerDetails->is_correct == 1 ) ?  1 :   0
                                    );
            $insert_emp_ans     = ChallengeEmployeeAnswer::create($insert_emp_ans_arr);
                
            if($answerDetails->is_correct == 1){ 
                $insert_credit_point_arr = array(
                                        'challenge_id'                => $answerDetails->challenge_id,
                                        'user_id'                     => $userDetails->id,
                                        'challenge_employee_answer_id'=> $insert_emp_ans->id,
                                        'earned_point'                => $challengeDetails->point_value,
                                        'point_earning_type'          => 1,
                                        'company_id'                  => $userActiveLocation->company_id,
                                        'location_id'                 => $userActiveLocation->location_id,
                                        'is_approved_point'           => 1,
                                        'point_given_by_user_id'      => $challengeDetails->user_id
                                    );
                    
                $insert_credit_point       = UserCreditPoint::create($insert_credit_point_arr);
            }
            $insert_msg_arr = array(
                'type' => 1,
                'challenge_id' => $challengeDetails->id,
                'message_type' => 0,
                'reply_id' => 0,
                'message' => '',
                'sender_id' => $userDetails->id,
                'employee_ans_id' => $insert_emp_ans->id
            );
            $insert_msg     = Message::create($insert_msg_arr);
            
            $success['is_correct']     = ($answerDetails->is_correct == 1) ? true : false;
            $success['correct_answer'] = substr($correctAnswerDetails->answer, 0, 150);
            $success['description']    = substr($challengeDetails->modal_desc_true, 0, 150);
            $success['questionnaire_category_image'] = $category_image_url;
            


            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }
    
    public function getQuestionnaireDetails($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';

        try
        {
            $messages = [
                'challenge_id.required' => 'Please enter challenge id'
            ];

            $validator = Validator::make($inputs,[
                "challenge_id" => "required"
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end

            $challengeDetails  = Challenge::where('id',$inputs['challenge_id'])->first();
            $challengeCategoryDetails = ChallengeCategory::where('id',$challengeDetails->challenge_category_id)->first();

            $rootFolderPath = 'challenge/categories';
            $category_image_url = $this->defaultServices->getImgPath($rootFolderPath, $challengeCategoryDetails->app_icon, 'app_icon');
            $answerDetails     = ChallengeQuestionAnswer::where('challenge_id',$inputs['challenge_id'])->get();
            $answer_arr        = [];
            $status_code       = 1;
            
             $success['challenge_question_id']        = $challengeDetails->id;
             $success['challenge_question_name']      = $challengeDetails->challenge_question;
             $success['points']                       = $challengeDetails->point_value;
             $success['expiry_date']                  = strtotime($challengeDetails->end_date);
             $success['expiry_time']                  = strtotime($challengeDetails->end_time);
             $success['questionnaire_category_image'] = $category_image_url;

             foreach($answerDetails as $key=>$answer){
                 $answer_arr[$key]['option_id'] = $answer->id;
                 $answer_arr[$key]['option_name'] = $answer->answer;
             }
             $success['option_list']                = $answer_arr;


            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }


    
    public function challengeHistory($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';
        $completeChallenge  = [];
        $pendingChallenge   = [];

        $limit  = ($inputs['page_size'] <= 0) ? 10 : $inputs['page_size'];
        $offset = ($inputs['page_count'] <= 0) ? 1 : $inputs['page_count'];
        $offset = ($limit * $offset) - $limit;

        try
        {
            $messages = [
                'category_id.required' => 'Please enter challenge category id',
                'page_count.required' => 'Please enter page count',
                'page_size.required' => 'Please enter page size'
            ];

            $validator = Validator::make($inputs,[
                "category_id" => "required",
                "page_count" => "required",
                "page_size" => "required"
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end

            $status_code = 1;
            //===============================Completed challenge section========================//
                $completeChallengeHistory = Challenge :: leftJoin('challenge_employee_answers', function ($join) {
                    $join->on('challenges.id', '=', 'challenge_employee_answers.challenge_id');
                    })
                    ->leftJoin('challenge_taking_types', function ($join) {
                        $join->on('challenges.challenge_taking_type', '=', 'challenge_taking_types.id');
                    })
                    ->select(
                        'challenges.id as challenge_id',
                        'challenges.challenge_name as challenge_name',
                        'challenges.challenge_question as challenge_question',
                        'challenge_taking_types.name as challenge_type_name',
                        'challenge_taking_types.id as challenge_taking_type_id',
                        'challenge_employee_answers.submission_datetime as submission_date',
                        'challenges.point_value as point_value',
                        'challenge_employee_answers.is_approved as is_approved',
                        'challenge_employee_answers.challenge_question_answer_id  as question_answer_id',
                        'challenge_employee_answers.id  as answer_id',
                        'challenge_employee_answers.is_correct_answer as is_correct',
                    )
                    ->where('challenges.challenge_category_id',$inputs['category_id'])
                    ->where('challenge_employee_answers.is_approved',1)
                    ->where('challenge_employee_answers.user_id',$userDetails->id)
                    ->orderBy('challenge_employee_answers.id', 'desc');
                    
                    
                    
                    $count_complete_challenge     = $completeChallengeHistory->count();
                    $completeChallengeHistory     = $completeChallengeHistory->skip($offset)->take($limit)->get();

                    foreach($completeChallengeHistory as $key=>$history){
                        if($history->challenge_taking_type_id==1 && $history->is_correct==1){
                            $point_value = $history->point_value;
                        }
                        if($history->challenge_taking_type_id==1 && $history->is_correct==0){
                            $point_value = 0;
                        }
                        if($history->challenge_taking_type_id==2 && $history->is_correct== NULL){
                            $point_value = $history->point_value;
                        }
                        $completeChallenge[$key]['completed_challenge_id'] = $history->challenge_id;
                        $completeChallenge[$key]['challenge_type']         = strtoupper($history->challenge_type_name);
                        $completeChallenge[$key]['challenge_type_id']      = $history->challenge_taking_type_id;
                        $completeChallenge[$key]['challenge_submit_date']  = strtotime($history->submission_date);
                        $completeChallenge[$key]['challenge_points']       = $point_value;
                        $completeChallenge[$key]['challenge_title']        = ($history->challenge_taking_type_id==1) ? $history->challenge_question : $history->challenge_name;
                        $completeChallenge[$key]['question_answer_id']     = $history->question_answer_id;
                        $completeChallenge[$key]['answer_id']              = $history->answer_id;
                        $completeChallenge[$key]['is_correct']             = $history->is_correct;
                    }
            //===============================Completed challenge section========================//

            //===============================Pending challenge section========================//
                $pendingChallengeHistory = Challenge :: leftJoin('challenge_employee_answers', function ($join) {
                        $join->on('challenges.id', '=', 'challenge_employee_answers.challenge_id');
                        })
                        ->leftJoin('challenge_taking_types', function ($join) {
                            $join->on('challenges.challenge_taking_type', '=', 'challenge_taking_types.id');
                        })
                        ->select(
                            'challenges.id as challenge_id',
                            'challenges.challenge_name as challenge_name',
                            'challenges.challenge_question as challenge_question',
                            'challenge_taking_types.name as challenge_type_name',
                            'challenge_taking_types.id as challenge_taking_type_id',
                            'challenge_employee_answers.submission_datetime as submission_date',
                            'challenges.point_value as point_value',
                            'challenge_employee_answers.is_approved as is_approved',
                            'challenge_employee_answers.challenge_question_answer_id as question_answer_id',
                            'challenge_employee_answers.id as answer_id'
                        )
                        ->where('challenges.challenge_category_id',$inputs['category_id'])
                        ->where('challenge_employee_answers.is_approved',0)
                        ->where('challenge_employee_answers.user_id',$userDetails->id)
                        ->orderBy('challenge_employee_answers.id', 'desc');
                      
                        
                        $count_pending_challenge     = $pendingChallengeHistory->count();
                        $pendingChallengeHistory     = $pendingChallengeHistory->skip($offset)->take($limit)->get();

                        foreach($pendingChallengeHistory as $key=>$history){
                            $pendingChallenge[$key]['pending_challenge_id'] = $history->challenge_id;
                            $pendingChallenge[$key]['challenge_type'] = strtoupper($history->challenge_type_name);
                            $pendingChallenge[$key]['challenge_type_id'] = $history->challenge_taking_type_id;
                            $pendingChallenge[$key]['challenge_submit_date'] = strtotime($history->submission_date);
                            $pendingChallenge[$key]['challenge_points'] = $history->point_value;
                            $pendingChallenge[$key]['challenge_title'] = ($history->challenge_taking_type_id==1) ? $history->challenge_question : $history->challenge_name;
                            $pendingChallenge[$key]['question_answer_id'] = $history->question_answer_id??0;
                            $pendingChallenge[$key]['answer_id'] = $history->answer_id;
                        }
            //===============================Pending challenge section========================//
            $success['user_id'] = $userDetails->id;
            $success['completed_challenge_list'] = $completeChallenge;
            $success['pending_challenge_list'] = $pendingChallenge;
            $success['total_count_completed_challenge'] = $count_complete_challenge ?? 0;
            $success['total_count_pending_challenge']    = $count_pending_challenge;
            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }

    public function submitPhototaking($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';
        $inputs['photo'] = $request->file('photo');

        try
        {
            $messages = [
                'photo.mimes'           => 'Please enter a image type of jpeg/jpg/png',
                'challenge_id.required' => 'Please enter challenge category id'
            ];

            $validator = Validator::make($inputs,[
                "challenge_id" => "required",
                "photo"        => "required"
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end

            $status_code = 1;

            $whereArr = array(
                        'user_id'         =>$userDetails->id,
                        'active_location' => 1
                         );

            $userActiveLocation       = CompanyEmployeeLocation::where($whereArr)->first();
            $challengeDetails         = Challenge::where('id',$inputs['challenge_id'])->first();
            $challengeCategoryDetails = ChallengeCategory::where('id',$challengeDetails->challenge_category_id)->first();
            
            $categoryFolderPath = 'challenge/categories/app_icon';
            $category_image_url = $this->defaultServices->getImgPath($categoryFolderPath, $challengeCategoryDetails->image, 'blue_app_icon');

            $rootFolderPath      = public_path('/storage/images/challenge/phototaking');
            $photoTakingImage    = $this->defaultServices->imgUpload($rootFolderPath, $inputs['photo']);
           
            $insert_emp_ans_arr     = array(
                'challenge_taking_type_id' => 2,
                'challenge_id'             => $challengeDetails->id,
                'is_approved'              => 0,
                'user_id'                  => $userDetails->id,
                'company_id'               => $userActiveLocation->company_id,
                'company_location_id'      => $userActiveLocation->location_id,
                'challenge_image'          => $photoTakingImage,
                'submission_datetime'      => date('Y-m-d H:i:s'),
                'is_point_credited'        =>  0
            );
            $insert_emp_ans     = ChallengeEmployeeAnswer::create($insert_emp_ans_arr);

            //$challenge_submit_message = $challengeDetails->challenge_name.' - '.$challengeDetails->challenge_desc;

            $insert_msg_arr = array(
                                    'type' => 1,
                                    'challenge_id' => $challengeDetails->id,
                                    'message_type' => 0,
                                    'reply_id' => 0,
                                    'message' => '',
                                    'sender_id' => $userDetails->id,
                                    'employee_ans_id' => $insert_emp_ans->id
                                );
            $insert_msg     = Message::create($insert_msg_arr);

            $success['after_submit_msg'] = "Your points will be approved in the next 72 hours.";
            $success['photo_taking_category_image'] = $category_image_url;
            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }
    
    public function getPhototakingDetails($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';

        try
        {
            $messages = [
                'challenge_id.required' => 'Please enter challenge category id'
            ];

            $validator = Validator::make($inputs,[
                "challenge_id" => "required"
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end

            $status_code = 1;

            
            $challengeDetails         = Challenge::where('id',$inputs['challenge_id'])->first();
            $challengeCategoryDetails = ChallengeCategory::where('id',$challengeDetails->challenge_category_id)->first();

            $rootFolderPath = 'challenge/categories';
            $category_image_url = $this->defaultServices->getImgPath($rootFolderPath, $challengeCategoryDetails->app_icon, 'app_icon');
            $success['photo_taking_id'] = $challengeDetails->id;
            $success['photo_taking_category_image'] = $category_image_url;
            $success['points'] = $challengeDetails->point_value;
            $success['expire_date'] = strtotime($challengeDetails->end_date);
            $success['expire_time'] = strtotime($challengeDetails->end_time);
            $success['photo_taking_tagline'] =  $challengeDetails->challenge_name;
            $success['photo_taking_description'] = $challengeDetails->challenge_desc;
            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }

    public function questionnaireHistoryDetails($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';

        try
        {
            $messages = [
                'questionnaire_challenge_id.required' => 'Please enter challenge id',
                'question_answer_id.required'         => 'Please enter question answer id'
            ];

            $validator = Validator::make($inputs,[
                "questionnaire_challenge_id" => "required",
                "question_answer_id"         => "required"
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end

            $challengeDetails = Challenge :: leftJoin('challenge_employee_answers', function ($join) {
                                $join->on('challenges.id', '=', 'challenge_employee_answers.challenge_id');
                                })
                                ->select(
                                    'challenges.id as challenge_id',
                                    'challenges.challenge_name as challenge_name',
                                    'challenges.challenge_question as challenge_question',
                                    'challenges.modal_desc_true as ture_justification',
                                    'challenges.modal_desc_false as false_justification',
                                    'challenge_employee_answers.submission_datetime as submission_date',
                                    'challenges.point_value as point_value',
                                    'challenges.challenge_desc as challenge_desc',
                                    'challenge_employee_answers.challenge_image as challenge_image',
                                    'challenge_employee_answers.is_approved as is_approved'
                                )
                                ->where('challenges.id',$inputs['questionnaire_challenge_id'])
                                ->where('challenge_employee_answers.id',$inputs['answer_id'])
                                ->first();
            //dd($challengeDetails);

            $answerDetails     = ChallengeQuestionAnswer::where('challenge_id',$inputs['questionnaire_challenge_id'])->get();
            $empAnsDetails     = ChallengeQuestionAnswer::where('challenge_id',$inputs['questionnaire_challenge_id'])->where('id',$inputs['question_answer_id'])->first();

            $answer_arr        = [];
            $status_code       = 1;
             //dd($challengeDetails);
             $success['user_id']                               = $userDetails->id;
             $success['details']['challenge_question_name']    = (!empty($challengeDetails))?$challengeDetails->challenge_question : '';
             $success['details']['challenge_answer']           = (!empty($empAnsDetails))?substr($empAnsDetails->answer, 0 , 150) : '';
             $success['details']['answer_justification']       = (!empty($challengeDetails))?substr($challengeDetails->ture_justification, 0, 150): '';

             foreach($answerDetails as $key=>$answer){
                 $answer_arr[$key]['option_name'] = $answer->answer;
                 $answer_arr[$key]['is_correct']  = ($answer->is_correct == 1) ? true : false;
                 $answer_arr[$key]['is_selected']  = ($answer->id == $empAnsDetails->id) ? true : false;
                 if($answer->is_correct == 1){
                    $success['details']['correct_option']   = $answer->answer;
                }
             }
             $success['details']['option_list']   = $answer_arr;
             $success['details']['points']        = (!empty($challengeDetails))?$challengeDetails->point_value:'';


            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }

    public function getPhototakingHistoryDetails($flag, Request $request)
    {
        $status_code = 0;
        $success = [];
        $inputs = getTrimmedValue($request->all());
        $extraParam = [];
        $messageArr['input'] = $inputs;
        $userType = 'employee';

        try
        {
            $messages = [
                'challenge_id.required' => 'Please enter challenge id',
                'answer_id.required' => 'Please enter answer id'
                
            ];

            $validator = Validator::make($inputs,[
                "challenge_id" => "required",
                "answer_id" => "required"
            ], $messages);

            if($validator->fails()) {
                return $this->sendEmployeeResponse($status_code, $success, $validator->errors()->first(), 200, $messageArr, $extraParam);
                exit(0);
            }

            $userDetails = Auth::user();
            $extraParam['user_id'] = $userDetails->id;

            // use it as default code - start
            $employeeDataArr = $this->checkEmployeeValidation();

            if($employeeDataArr['status'] != 1) {
                return $this->sendEmployeeResponse($status_code, $success, $employeeDataArr['message'], 200, $messageArr, $extraParam);
                exit(0);
            }
            // use it as default code - end

            $status_code = 1;

            
            $photoChallengeHistory = Challenge :: leftJoin('challenge_employee_answers', function ($join) {
                $join->on('challenges.id', '=', 'challenge_employee_answers.challenge_id');
                })
                ->select(
                    'challenges.id as challenge_id',
                    'challenges.challenge_name as challenge_name',
                    'challenges.challenge_question as challenge_question',
                    'challenge_employee_answers.submission_datetime as submission_date',
                    'challenges.point_value as point_value',
                    'challenges.challenge_desc as challenge_desc',
                    'challenge_employee_answers.challenge_image as challenge_image',
                    'challenge_employee_answers.is_approved as is_approved'
                )
                ->where('challenges.id',$inputs['challenge_id'])
                ->where('challenge_employee_answers.id',$inputs['answer_id'])
                ->first();
                

                  
            $rootFolderPath = 'challenge/phototaking';
            $challenge_image_url = $this->defaultServices->getImgPath($rootFolderPath, $photoChallengeHistory->challenge_image, 'api');
           
            $phototakingHistoryDetails['image_description'] = $photoChallengeHistory->challenge_desc;
            $phototakingHistoryDetails['image_url'] = $challenge_image_url;
            $phototakingHistoryDetails['isPending'] = ($photoChallengeHistory->is_approved) ? false : true;
                

            $success['user_id'] = $userDetails->id;
            $success['details'] = $phototakingHistoryDetails;
            $success['points']  = $photoChallengeHistory->point_value;

            $this->device_token($inputs, $userType, $userDetails->id, 1);
            return $this->sendEmployeeResponse($status_code, $success, 'success', 200, $messageArr, $extraParam);

        } catch (Exception $e) {
            return $this->sendEmployeeResponse(0, [], $e->getMessage(), 200, $messageArr??[]);
        }
    }

    
    
    
}