<?php

namespace App\Http\Controllers\CompanyAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models;
use Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\Challenge;
use App\Models\Company;
use App\Models\CompanyAdmin;
use App\Models\CompanyLocationAdmin;
use App\Models\CompanyEmployeeLocation;
use App\Models\ChallengeCategory;
use App\Models\ChallengeTakingType;
use App\Models\ChallengeQuestionAnswer;
use App\Models\CompanyLocation;
use App\Models\CompanyChallengeLocations;
use App\Models\CompanyChallengeLocationEmployee;
use App\Models\Companychallenges;
use Carbon\Carbon;
use Yajra\Datatables\Datatables;
use App\Services\DefaultServices;
use App\Services\ChallengePushServices;
use DB;
use Session;
use Illuminate\Support\Facades\Validator;
use Input;
use Exception;
use Mail;

class ChallengeController extends Controller
{
  

    public function __construct(DefaultServices $defaultServices)
    {
        $this->defaultServices = $defaultServices;
    }

	public function index(Request $request) {
		$userDetails = Auth::guard('companyAdmin')->user(); 
		$companyDetails = $userDetails->getCompanies->first();
		//dd($companyDetails->id); //out put 5
	    if($request->ajax()) {            
	            $is_active = $request->checkstatus;
	            $filters   = [];
	            if($is_active != '') { 
	                $curent_date = date('Y-m-d H:i:s');
	                $curent_time = date('G:i');
	               // echo date('Y-m-d H:i:s');
	                if($is_active== 'active'){
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                     $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })               
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',   
	                        'challenges.type_by_super_admin as type_by_super_admin',                      
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type',
	                        //'challenges.start_time as start_time',
	                    )                    
	                    ->where('challenges.is_active',1)     
	                    ->where('challenges.created_by_admin_type',1) 	                    
	                    ->whereRaw('(challenges.type_by_super_admin = 1 OR company_challenges.company_id ='.$companyDetails->id.')')               
	                    //->whereDate('challenges.start_date','>=',)                   
	                    //->whereDate('challenges.end_date','<=',)
	                    //->where(DB::raw("CONCAT(`start_date`, ' ', `start_time`) <=".date('Y-m-d H:i:s')."'"))  
	                    ->whereRaw("CONCAT(`start_date`, ' ', `start_time`) <='".date('Y-m-d H:i:s')."'")                  
	                    //->whereRaw("CONCAT(`start_time`) <='".date('Y-m-d H:i:s')."'")                   
	                    ->whereRaw("CONCAT(`end_date`, ' ', `end_time`) >='".date('Y-m-d H:i:s')."'")                 
	                    ->where('challenges.is_delete',0)                    
	                    //->where('challenges.challenge_type',1)                    
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')                   
	                    ->get();  
	                    
	                }
	                else if($is_active== 'scheduled'){	                	
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })  
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                  
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',    
	                        'challenges.type_by_super_admin as type_by_super_admin',                     
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    ->where('challenges.is_active',1)  
	                    ->where('challenges.created_by_admin_type',1) 	                    
	                    ->whereRaw('(challenges.type_by_super_admin = 1 OR company_challenges.company_id ='.$companyDetails->id.')')
	                    ->whereRaw("CONCAT(`start_date`, ' ', `start_time`) >='".date('Y-m-d H:i:s')."'")                  
	                    ->where('challenges.is_delete',0) 
	                    //->where('challenges.challenge_type',1)                     
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get();  
	                }
	                else if($is_active== 'completed'){
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })  
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                  
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',  
	                        'challenges.type_by_super_admin as type_by_super_admin',                       
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    ->where('challenges.is_active',1)  
	                    ->where('challenges.created_by_admin_type',1) 	                    
	                    ->whereRaw('(challenges.type_by_super_admin = 1 OR company_challenges.company_id ='.$companyDetails->id.')')
	                    ->whereRaw("CONCAT(`end_date`, ' ', `end_time`) <='".date('Y-m-d H:i:s')."'")               
	                    ->where('challenges.is_delete',0)   
	                   // ->where('challenges.challenge_type',1)                   
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get();  
	                }
	                else if($is_active== 'deactivated'){
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })    
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',
	                        'challenges.type_by_super_admin as type_by_super_admin',                         
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    ->where('challenges.is_active',0)  
	                    ->where('challenges.created_by_admin_type',1) 	                    
	                    ->whereRaw('(challenges.type_by_super_admin = 1 OR company_challenges.company_id ='.$companyDetails->id.')')                  
	                    ->where('challenges.is_delete',0)    
	                    //->where('challenges.challenge_type',1)                  
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get();  
	                }
	            }else{

	                $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                    
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',  
	                        'challenges.type_by_super_admin as type_by_super_admin',                      
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    //->where('challenges.is_active',$is_active)                    
	                    ->where('challenges.is_delete',0)  
	                    //->where('challenges.challenge_type',1)                    
	                    ->where('challenges.created_by_admin_type',1) 	                    
	                    ->whereRaw('(challenges.type_by_super_admin = 1 OR company_challenges.company_id ='.$companyDetails->id.')')
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get(); 
	                                      
	            }
	            return Datatables::of($allChallenge)
	            ->addIndexColumn()
	            ->addColumn('image', function($row){
	                if($row->challenge_name != ''){
	                    $button = '<a href="'.url('companyadmin/challenge/challengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/challenge/categories/web/'.$row->image).'" alt=""></a>
	                            <a href="'.url('companyadmin/challenge/challengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'">'.$row->challenge_cat_name.' - '.substr($row->challenge_name, 0, 15).'...'.'</a>';
	                }
	                if($row->challenge_question != ''){
	                    $button = '<a href="'.url('companyadmin/challenge/challengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/challenge/categories/web/'.$row->image).'" alt=""></a>
	                            <a href="'.url('companyadmin/challenge/challengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'">'.$row->challenge_cat_name.' - '.substr($row->challenge_question, 0, 15).'...'.'</a>';
	                }
	                return $button;                
	                
	            })
				->addColumn('challenge_type', function($row){                
	                return $row->challenge_type;
	            })
	            ->addColumn('type_by_super_admin', function($row){
	                //if($row->type_by_super_admin==1){
	                    return  'Global';
	               // }
	                /*if($row->type_by_super_admin==2){
	                    return  'Company Specific';
	                }*/
	            })
	            ->addColumn('start_date', function($row){
	                return  date('d/m/Y', strtotime($row->start_date)).' | '.date('G:i', strtotime($row->start_time));
	            })
	            ->addColumn('end_date', function($row){
	                return  date('d/m/Y', strtotime($row->end_date));
	            })            
	            ->addColumn('id', function($row){                
	                return $row->id;
	            })
	            ->rawColumns(['image', 'type_by_super_admin','start_date', 'end_date', 'id'])
	            ->make(true);

	    }
	    return view('companyAdmin.challenge.assignedbyglobal.index');
	}

	public function challengeDetails(Request $request){
        try{
        	$userDetails = Auth::guard('companyAdmin')->user(); 
		    $companyDetails = $userDetails->getCompanies->first();		    
        	$request->id = encript_decript_data($request->id,'decript' ,2);
            $getchallengesDetails = Challenge::where('id', $request->id)->first();

            $assignEmployeeDetails = [];

            if($getchallengesDetails->type_by_super_admin == 2){
                
	                $companyChallengeLocations = CompanyChallengeLocations::where('challenge_id', $request->id )->where('company_id', $companyDetails->id)->orderBy('company_location_id', 'ASC')->get();
	                $assignEmployeeDetails['company_name'] = $companyDetails->company_name;
	                $assignEmployeeDetails['company_location'] = $companyChallengeLocations;
	                if(isset($companyChallengeLocations) && $companyChallengeLocations->count() > 0){
		                //foreach($companyChallengeLocations as $item_loc => $value){                	
		                   $companyChallengeLocationEmployee = CompanyChallengeLocationEmployee::where('challenge_id', $request->id )->where('company_id', $companyDetails->id)->orderBy('user_id', 'ASC')->get();
		                   
		     	           $assignEmployeeDetails['emp_name']   =  $companyChallengeLocationEmployee;                    
		                   
		               // }
	                }
	                
                
            }

            //dd( $assignEmployeeDetails);
            if($getchallengesDetails == null){
            	return redirect()->back();
            }

            $heading_1 = ChallengeCategory::where('id', $getchallengesDetails->challenge_category_id )->where('is_active', 1)->where('is_delete', 0)->first();
            
            /*if($getchallengesDetails->type_by_super_admin == 1){
                $heading_2 = 'Global Challenge';
            }else{
                $heading_2 = 'Specific Company Challenge';
            }*/
            $heading_2 = 'Global Challenge';
            if($getchallengesDetails->challenge_taking_type ){

                $heading_3 = ChallengeTakingType::where('id', $getchallengesDetails->challenge_taking_type )->where('is_active', 1)->where('is_delete', 0)->first();
            } 
             $heading = $heading_1->name.' - '.$heading_2.' - '.$heading_3->name;

            if($getchallengesDetails->challenge_taking_type == 1){
                 $getQuestionAnswerDetails = ChallengeQuestionAnswer::where('challenge_id', $request->id)->get();
                 return view('companyAdmin.challenge.assignedbyglobal.challengesDetails',compact('getchallengesDetails', 'getQuestionAnswerDetails', 'heading','assignEmployeeDetails'));
            }else{
                return view('companyAdmin.challenge.assignedbyglobal.challengesDetails',compact('getchallengesDetails', 'heading','assignEmployeeDetails'));
            }
        }catch(Exception $ex) {
            return response()->json(['success' => false, 'result' => [] ], 201);
        } 
    }

    public function companyChallenge(Request $request) {
		$userDetails = Auth::guard('companyAdmin')->user(); 
		$companyDetails = $userDetails->getCompanies->first();
		//dd($userDetails->id); //out put 5
	    if($request->ajax()) {            
	            $is_active = $request->checkstatus;
	            $filters   = [];
	            if($is_active != '') { 
	                $curent_date = date('Y-m-d H:i:s');
	                $curent_time = date('G:i');
	               // echo date('Y-m-d H:i:s');
	                if($is_active== 'active'){
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                     $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })               
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',   
	                        'challenges.type_by_company as type_by_company',                      
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type',
	                        //'challenges.start_time as start_time',
	                    )                    
	                    ->where('challenges.is_active',1)
	                    //->whereDate('challenges.start_date','>=',)                   
	                    //->whereDate('challenges.end_date','<=',)
	                    //->where(DB::raw("CONCAT(`start_date`, ' ', `start_time`) <=".date('Y-m-d H:i:s')."'"))  
	                    ->whereRaw("CONCAT(`start_date`, ' ', `start_time`) <='".date('Y-m-d H:i:s')."'")                  
	                    //->whereRaw("CONCAT(`start_time`) <='".date('Y-m-d H:i:s')."'")                   
	                    ->whereRaw("CONCAT(`end_date`, ' ', `end_time`) >='".date('Y-m-d H:i:s')."'")                 
	                    ->where('challenges.is_delete',0)                    
	                    ->where('challenges.created_by_admin_type',2)                    
	                    ->where('challenges.challenge_type',1)   
	                    ->where('challenges.user_id',$userDetails->id)              
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')                   
	                    ->get();  
	                    
	                }
	                else if($is_active== 'scheduled'){	                	
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })  
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                  
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',    
	                        'challenges.type_by_company as type_by_company',                      
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    ->where('challenges.is_active',1)  	                    
	                    ->whereRaw("CONCAT(`start_date`, ' ', `start_time`) >='".date('Y-m-d H:i:s')."'")                  
	                    ->where('challenges.is_delete',0) 
	                    ->where('challenges.created_by_admin_type',2)
	                    ->where('challenges.challenge_type',1) 
	                    ->where('challenges.user_id',$userDetails->id)                    
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get();  
	                }
	                else if($is_active== 'completed'){
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })  
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                  
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',  
	                        'challenges.type_by_company as type_by_company',                         
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    ->where('challenges.is_active',1)  	                    
	                    ->whereRaw("CONCAT(`end_date`, ' ', `end_time`) <='".date('Y-m-d H:i:s')."'")               
	                    ->where('challenges.is_delete',0)  
	                    ->where('challenges.created_by_admin_type',2)
	                    ->where('challenges.challenge_type',1)  
	                     ->where('challenges.user_id',$userDetails->id)                 
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get();  
	                }
	                else if($is_active== 'deactivated'){
	                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })    
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',
	                        'challenges.type_by_company as type_by_company',                           
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    ->where('challenges.is_active',0) 
	                    ->where('challenges.is_delete',0)    
	                    ->where('challenges.created_by_admin_type',2)
	                    ->where('challenges.challenge_type',1)    
	                    ->where('challenges.user_id',$userDetails->id)              
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get();  
	                }
	            }else{

	                $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
	                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
	                    })
	                    ->leftJoin('challenge_taking_types', function ($join) {
	                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
	                    })
	                    ->leftJoin('company_challenges', function ($join) {
	                        $join->on('company_challenges.challenge_id', '=', 'challenges.id');
	                    })                    
	                    ->select(
	                        'challenges.id as id',
	                        'challenges.start_date as start_date',
	                        'challenges.start_time as start_time',
	                        'challenges.end_date as end_date',
	                        'challenges.end_time as end_time',                        
	                        'challenges.challenge_name as challenge_name',
	                        'challenges.challenge_question as challenge_question',
	                        'challenges.is_active as is_active',  
	                       'challenges.type_by_company as type_by_company',                    
	                        'challenge_categories.name as challenge_cat_name',
	                        'challenge_categories.image as image',
	                        'challenge_taking_types.name as challenge_type' 
	                    )                    
	                    //->where('challenges.is_active',$is_active)                    
	                    ->where('challenges.is_delete',0)  
	                    ->where('challenges.created_by_admin_type',2)
	                    ->where('challenges.challenge_type',1)
	                    ->where('challenges.user_id',$userDetails->id)
	                    ->where('challenge_categories.is_active',1)
	                    ->where('challenge_categories.is_delete',0)
	                    ->where('challenge_taking_types.is_active',1)
	                    ->where('challenge_taking_types.is_delete',0)                    
	                    ->groupBy('challenges.id')
	                    ->get(); 
	                                      
	            }
	            return Datatables::of($allChallenge)
	            ->addIndexColumn()
	            ->addColumn('image', function($row){
	                if($row->challenge_name != ''){
	                    $button = '<a href="'.url('companyadmin/companychallenge/companyChallengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/challenge/categories/web/'.$row->image).'" alt=""></a>
	                            <a href="'.url('companyadmin/companychallenge/companyChallengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'">'.$row->challenge_cat_name.' - '.substr($row->challenge_name, 0, 15).'...'.'</a>';
	                }
	                if($row->challenge_question != ''){
	                    $button = '<a href="'.url('companyadmin/companychallenge/companyChallengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/challenge/categories/web/'.$row->image).'" alt=""></a>
	                            <a href="'.url('companyadmin/companychallenge/companyChallengeDetails/'.encript_decript_data($row->id,'encript' ,2)).'">'.$row->challenge_cat_name.' - '.substr($row->challenge_question, 0, 15).'...'.'</a>';
	                }
	                return $button;                
	                
	            })
				/*->addColumn('challenge_type', function($row){                
	                return $row->challenge_type;
	            })*/
	            ->addColumn('type_by_company', function($row){
	                if($row->type_by_company==1){
	                    return  'Company wide Challenge';
	                }
	                if($row->type_by_company==2){
	                    return  'Location Specific Challenge';
	                }
	            })
	            ->addColumn('start_date', function($row){
	                return  date('d/m/Y', strtotime($row->start_date)).' | '.date('G:i', strtotime($row->start_time));
	            })
	            ->addColumn('end_date', function($row){
	                return  date('d/m/Y', strtotime($row->end_date));
	            })  
	            ->addColumn('status', function($row){
	            	$status = '';
	                $current_date = date('Y-m-d H:i:s');                      
				    $start_date = $row->start_date;
				    $start_time = $row->start_time;
				    $challenge_start_date1 = $row->start_date.' '.$row->start_time;
				    $challenge_start_date = date('Y-m-d H:i:s', strtotime($challenge_start_date1 ));

				    $end_date = $row->end_date;
				    $end_time = $row->end_time;
				    $challenge_end_date1 = $row->end_date.' '.$row->end_time;
				    $challenge_end_date = date('Y-m-d H:i:s', strtotime($challenge_end_date1 ));
				    if($challenge_start_date > $current_date && $challenge_end_date > $current_date && $row->is_active == 1){
				    	return 'Scheduled';
				    }
				    else if($challenge_start_date < $current_date && $challenge_end_date > $current_date){
				    	return 'Active';
				    }
				    else if($challenge_start_date < $current_date && $challenge_end_date < $current_date){
				    	return 'Completed';
				    }
				    else if($row->is_active == '0'){
				    	return 'Deactivated';
				    }


	            })          
	            ->addColumn('id', function($row){                
	                return $row->id;
	            })
	            ->rawColumns(['image', 'type_by_company','start_date', 'end_date', 'status', 'id'])
	            ->make(true);

	    }
	    return view('companyAdmin.challenge.index');
	}


	public function addChallenge(Request $request) {
		$userDetails = Auth::guard('companyAdmin')->user(); 
		$companyDetails = $userDetails->getCompanies->first();		
        $challengeCategories = ChallengeCategory::where('is_active', 1)->where('is_delete', 0)->get();
        $challengetakingTypes = ChallengeTakingType::where('is_active', 1)->where('is_delete', 0)->get();
        $location_data = CompanyLocation::where('company_locations.company_id', $companyDetails->id )->where('company_locations.is_active',1)->get();                        
    	$challenge = $request->session()->get('challenge');
        return view('companyAdmin.challenge.addChallenge', compact('challenge', 'location_data', 'challengeCategories', 'challengetakingTypes'));
    }

    public function challengeCreateStep1(Request $request)
    {         	
        $validatedData = $request->validate([
            'challenge_category_id' => 'required',
           
        ]);
        $validator = new Validator;
        $errors = 0;
        if(empty($request->session()->get('challenge'))){
            $challenge = new Challenge();
            $challenge->fill($validatedData);
            $request->session()->put('challenge', $challenge);
            $request->session()->put('location_name', $request->input('location_name'));
            /*******************working***********************/
            $request->session()->put('challenge_category_id', $request->input('challenge_category_id'));            
            $request->session()->put('type_by_company', $request->input('type_by_company'));

            $request->session()->put('global_challenge_taking_type', $request->input('global_challenge_taking_type'));
            $selected_location_ids=$request->input('location_name');

            $selected_company_with_locations=[];
            /*if(!empty($selected_location_ids)){
                 foreach($selected_location_ids as $selected_location_id){  
                    $validator = Validator::make($request->all(), [
                        "employee_list_".$selected_location_id => "required",
                        "employee_list_".$selected_location_id.".*" => "required",
                        ]);

                    if($validator->fails()){ 
                        $errors = 1;
                    }
                    $selected_company_with_locations[$selected_location_id]=$request->input('employee_list_'.$selected_location_id);                  
                 }

            }*/   
            $request->session()->put('selected_company_with_locations', $selected_location_ids);                    
            //$request->session()->put('selected_company_with_locations', $selected_company_with_locations);   
            $request->session()->put('location_name', $request->input('location_name'));
            $request->session()->put('company_specific_challenge_taking_type', $request->input('company_specific_challenge_taking_type'));
            $request->session()->put('selectCompanylocation', $request->input('selectCompanylocation'));
            $request->session()->put('selectedemployee', $request->input('employee_list'));            
            $request->session()->put('employee_specific', $request->input('employee_specific'));  
        }else{
            //if(!empty($request->session()->get('challenge')) && null !==$request->session()->get('challenge')){
            //if(!empty($request->session()->get('challenge')) && isset(!empty($request->session()->get('challenge')))){
            $challenge = new Challenge();
            $challenge->fill($validatedData);
            $request->session()->put('challenge', $challenge);
            $request->session()->put('location_name', $request->input('location_name'));
            /*******************working***********************/
            $request->session()->put('challenge_category_id', $request->input('challenge_category_id'));            
            $request->session()->put('type_by_company', $request->input('type_by_company'));

            $request->session()->put('global_challenge_taking_type', $request->input('global_challenge_taking_type'));
            $selected_location_ids=$request->input('location_name');
            $selected_company_with_locations=[];
            /*if(!empty($selected_location_ids)){
                 foreach($selected_location_ids as $selected_location_id){  
                    $validator = Validator::make($request->all(), [
                        "employee_list_".$selected_location_id => "required",
                        "employee_list_".$selected_location_id.".*" => "required",
                        ]);

                    if($validator->fails()){                                          	
                        $errors = 1;
                    }
                    $selected_company_with_locations[$selected_location_id]=$request->input('employee_list_'.$selected_location_id);                  
                 }

            } */                      
            $request->session()->put('selected_company_with_locations', $selected_location_ids);   
            //$request->session()->put('selected_company_with_locations', $selected_company_with_locations);   
            $request->session()->put('location_name', $request->input('location_name'));
            $request->session()->put('company_specific_challenge_taking_type', $request->input('company_specific_challenge_taking_type'));
            $request->session()->put('selectCompanylocation', $request->input('selectCompanylocation'));
            $request->session()->put('selectedemployee', $request->input('employee_list'));            
            $request->session()->put('employee_specific', $request->input('employee_specific'));  
        }    
        //dd($request->input('company_specific_challenge_taking_type'));   
        return redirect()->route('companyAdmin.company.challengeCreateStep2');      
        /*if($request->input('type_by_company') == 1){
            return redirect()->route('companyAdmin.company.challengeCreateStep2');
        }else{
            if($errors == 1){
                return redirect()->back()->withErrors("please select Employee");
            }else{
                return redirect()->route('companyAdmin.company.challengeCreateStep2');
            }
        }*/
    }

    public function challengeCreateStep2(Request $request)
    {       

        try{
            $challenge = $request->session()->get('location_name');
            
            $global_challenge_taking_type = $request->session()->get('global_challenge_taking_type');
            $company_specific_challenge_taking_type = $request->session()->get('company_specific_challenge_taking_type');
            $type_by_company = $request->session()->get('type_by_company');
            $challenge_category_id = $request->session()->get('challenge_category_id');


            $heading_1 = ChallengeCategory::where('id', $challenge_category_id )->where('is_active', 1)->where('is_delete', 0)->first();
            
            if($type_by_company == 1){
                $heading_2 = 'Company wide Challenge';
            }else{
                $heading_2 = 'Location Specific Challenge';
            }
            if($global_challenge_taking_type ){

                $heading_3 = ChallengeTakingType::where('id', $global_challenge_taking_type )->where('is_active', 1)->where('is_delete', 0)->first();
            }else{
                $heading_3 = ChallengeTakingType::where('id', $company_specific_challenge_taking_type )->where('is_active', 1)->where('is_delete', 0)->first();
            }
            
            
             $heading = $heading_1->name.' - '.$heading_2.' - '.$heading_3->name;           
            return view('companyAdmin.challenge.questionnaire-challenge',compact('challenge','global_challenge_taking_type','company_specific_challenge_taking_type','heading'));
        }
        catch(Exception $e){           
            return redirect()->back()->withErrors(['error-messsage' => [$e->getMessage()]]);
        }
        
    }

    public function saveChallenge(Request $request)
    {   
    	$location = [];
        $employee = [];
        $company_employee = [];
        $i = 0;
        
       // dd($request->session()->get('selectedemployee'));
        if( null != $request->session()->get('selectedemployee')){
            $selectedemployee = $request->session()->get('selectedemployee');
            foreach($selectedemployee as $key => $value){
                $explode_value = explode('-',$value);
                array_push($employee, $explode_value[1]);
                array_push($location, $explode_value[0]);
                //array_push($company, $explode_value[0]);
                $company_employee[$i][$explode_value[0]] = $explode_value[1];
                $i++;
            }       
            $employee_specific = $request->session()->get('employee_specific');
        }
        try{            
            $user = Auth::guard('companyAdmin')->user();
            $companyDetails = $user->getCompanies->first();

            if($request->session()->get('global_challenge_taking_type') == 2 || $request->session()->get('company_specific_challenge_taking_type')==2){
                $photo_taken_challenge_rules = [
                    'point-value'    => 'required|numeric',
                    'challenge_name' => 'required',         
                    'challenge_description' => 'required',            
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $photo_taken_challenge_rules);
           }else{            
                $questionnaire_challenge_rules = [
                    'point-value' => 'required|numeric',
                    'challenge_question' => 'required',
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $questionnaire_challenge_rules);
            }

            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator->errors())->withInput(Input::all());
            }

            $location_name = $request->session()->get('location_name');
            $challenge_category_id = $request->session()->get('challenge_category_id');
            $type_by_company = $request->session()->get('type_by_company');

            $global_challenge_taking_type = $request->session()->get('global_challenge_taking_type');

            $company_specific_challenge_taking_type = $request->session()->get('company_specific_challenge_taking_type');

            $selectCompanylocation = $request->session()->get('selectCompanylocation');

            if($request->session()->get('global_challenge_taking_type') == 2 || $request->session()->get('company_specific_challenge_taking_type')==2){
              $challenge_name  = $request->input('challenge_name');
              $challenge_description  = $request->input('challenge_description');
              $modal_desc = $request->input('modal_desc'); 
              $challenge_question = '';
              $modal_desc_true = '';
              $modal_desc_false = '';
            }else{
                $challenge_name = '';
                $challenge_description = '';
                $modal_desc = '';
                $challenge_question = $request->input('challenge_question');                
                $modal_desc_true = $request->input('modal_desc_true');
                $modal_desc_false = $request->input('modal_desc_false');
            }

            if($type_by_company == 1){               
                $taken_type = $global_challenge_taking_type;
            }else{                
                $taken_type = $company_specific_challenge_taking_type;
            }            
            $pointvalue = $request->input('point-value');            
            $start_date = date('Y-m-d', strtotime($request->input('start_date')));                      
            $time = date("H:i", strtotime($request->input('start_time')));  
            $start_time = $time;          
            $end_date = date('Y-m-d', strtotime($request->input('end_date')));
            $end_time = '23:59';
            $modal_header = $request->input('modal_header');

            $challenge = new Challenge;
            $challenge->challenge_taking_type = $taken_type;
            $challenge->challenge_category_id = $challenge_category_id;
            $challenge->user_id = $user->id;
            $challenge->point_value = $pointvalue;
            $challenge->challenge_name = $challenge_name;
            $challenge->challenge_desc = $challenge_description;
            $challenge->start_date = $start_date;
            $challenge->start_time = $start_time;            
            $challenge->end_date = $end_date;
            $challenge->end_time = $end_time;
            $challenge->modal_header = $modal_header;
            $challenge->modal_desc = $modal_desc;
            $challenge->modal_desc_true = $modal_desc_true;
            $challenge->modal_desc_false = $modal_desc_false; 
            $challenge->challenge_question = $challenge_question;
            $challenge->created_by_admin_type = 2;
            $challenge->type_by_company = $type_by_company;            
            $challenge->challenge_type  = 1;
            $result = $challenge->save();            
            if($result){
                if($request->session()->get('global_challenge_taking_type') == 1 || $request->session()->get('company_specific_challenge_taking_type')== 1){
                    $option = $request->input('answer-option');
                    $insert_array = [
                        'challenge_id' => $challenge->id,
                        'is_correct' => ($option == 'option1')? 1 : 0 ,
                        //'answer' => 'option1' ,
                        'answer' => $request->input('answer-option1-value'),
                        //'answer' => ($option == 'option1')? 'option1' : 'option2' ,
                        'justification' => '',                
                        //'justification' => $request->input('answer-option1-value'), 
                    ];
                    ChallengeQuestionAnswer::create($insert_array);
                    $insert_array2 = [
                        'challenge_id' => $challenge->id,
                        'is_correct' => ($option == 'option2')? 1 : 0,
                        'answer' => $request->input('answer-option2-value') ,
                        //'answer' => 'option2' ,
                        'justification' => '',
                       // 'justification' => $request->input('answer-option2-value'),
                    ];
                    ChallengeQuestionAnswer::create($insert_array2);                    
                }
                if($type_by_company == 1){
                    	$location_type = 1;
                    }else{
                    	$location_type = 0;
                    }

                    $companychallenges = [
                       'challenge_id' =>$challenge->id,
                       'company_id' =>$companyDetails->id,  
                       'location_type' => $location_type,                    
                       'approve_status' => 1,  
                    ];
                    Companychallenges::create($companychallenges);

                if($type_by_company == 2 ){  
                                 
                    $selected_company_with_locations = $request->session()->get('selected_company_with_locations'); 
                    //dd($selected_company_with_locations);                   
                    /*if(!empty($selected_company_with_locations) && $selected_company_with_locations!= null){
                        foreach($selected_company_with_locations as $key=>$selected_company_with_location_row){                         
                             $companychallengelocations = [
                                   'challenge_id' =>$challenge->id,
                                   'company_id' =>$companyDetails->id,
                                   'company_location_id' =>$key,
                                   'approve_status' => 1,                       
                                ];
                            CompanyChallengeLocations::create($companychallengelocations);	                         
                        }
                    }*/

                if(!empty($selected_company_with_locations) && $selected_company_with_locations!= null){
                	//dd($selected_company_with_locations);
                    foreach($selected_company_with_locations as $key => $selected_company_with_location_row){ 
                        if(!empty($selected_company_with_location_row) && $selected_company_with_location_row!= null){ 
                            //dd($selected_company_with_location_row);  
	                        if( isset($employee_specific)){
	                          if(in_array($selected_company_with_location_row, $employee_specific)){
                        		$companychallengelocations = [
                                       'challenge_id' =>$challenge->id,
                                       'company_id' => $companyDetails->id,
                                       'company_location_id' =>$selected_company_with_location_row,
                                       'is_employee_specfic'=> 0,
                                       'approve_status' => 1,                       
                                    ];
                                CompanyChallengeLocations::create($companychallengelocations);
                                //insert in to company_challenge_location_employees this table
                                foreach($company_employee as $item){  
                                  foreach($item as $loc => $emp_id){ 
                                    if($selected_company_with_location_row == $loc){
                                        $challengeAssignEmployee = [
                                           'challenge_id' => $challenge->id,
                                           'company_id' => $companyDetails->id,
                                           'company_location_id' =>$loc,                                                
                                           'user_id'=> $emp_id,
                                           'approve_status' => 1,                       
                                        ];                                               
                                    CompanyChallengeLocationEmployee::create($challengeAssignEmployee);
                                    }
                                  }
                                }
                              }else{
                        		$companychallengelocations = [
                                   'challenge_id' =>$challenge->id,
                                   'company_id' => $companyDetails->id,
                                   'company_location_id' => $selected_company_with_location_row,
                                   'is_employee_specfic'=> 1,
                                   'approve_status' => 1,                       
                                ];
                               CompanyChallengeLocations::create($companychallengelocations);
	                        	}
	                        }else{
	                        	$companychallengelocations = [
                                   'challenge_id' => $challenge->id,
                                   'company_id' => $companyDetails->id,
                                   'company_location_id' =>  $selected_company_with_location_row,
                                   'approve_status' => 1,
                                   'is_employee_specfic'=> 1,                       
                                ];
	                            CompanyChallengeLocations::create($companychallengelocations);
	                        } 	   
                        }                      
                    }
                }
                    
              }
            }  
            //$this->sendPush($challenge->id);
            
            //$this->ChallengePushServices->sendPush($challenge->id);
            //=============push for company add challenge=====================//
	        $messageArr['title'] = get_notification_title('challenge-added-by-company-admin');
	        $messageArr['body']  = get_notification_text('challenge-added-by-company-admin');
	        $paramArr['type']    = 'company-admin-add-challenge';
	        $paramArr['challenge_id'] = $challenge->id;        
	        (new ChallengePushServices)->sendChallengePush($paramArr['challenge_id'], $messageArr, $paramArr);

	        //(new ChallengePushServices)->sendChallengePush(1);


            $request->session()->flash('success-message', 'Challenge Added Succeessfully');
            return redirect(route('companyAdmin.companyChallenge'));
        }
        catch(Exception $e){
            return redirect()->back()->withErrors(['error-messsage' => [$e->getMessage()]]);
        }
       
    }



    public function companyChallengeDetails(Request $request){
        try{
        	$request->id = encript_decript_data($request->id,'decript' ,2);
            $getchallengesDetails = Challenge::where('id', $request->id)->first();
            //dd($request->id);
            $userDetails = Auth::guard('companyAdmin')->user(); 
			$companyDetails = $userDetails->getCompanies->first();	
            if($getchallengesDetails == null){
            	return redirect()->back();
            }

            $heading_1 = ChallengeCategory::where('id', $getchallengesDetails->challenge_category_id )->where('is_active', 1)->where('is_delete', 0)->first();
            
            if($getchallengesDetails->type_by_company == 1){
                $heading_2 = 'Company wide Challenge';
            }else{
                $heading_2 = 'Location Specific Challenge';
            }
            if($getchallengesDetails->challenge_taking_type ){

                $heading_3 = ChallengeTakingType::where('id', $getchallengesDetails->challenge_taking_type )->where('is_active', 1)->where('is_delete', 0)->first();
            } 
             $heading = $heading_1->name.' - '.$heading_2.' - '.$heading_3->name;


            $assignEmployeeDetails = [];        
			if($getchallengesDetails->type_by_company == 2){	

				$companyChallengeLocations = CompanyChallengeLocations::where('challenge_id', $request->id )->where('company_id', $companyDetails->id)->orderBy('company_location_id', 'ASC')->get();
				//dd($companyChallengeLocations);
				//$assignEmployeeDetails['company_location'] = $companyChallengeLocations;

				    if(isset($companyChallengeLocations) && $companyChallengeLocations->count() > 0){
				        foreach($companyChallengeLocations as $item_loc => $value){  
				       // dd($value->getCompanyLocation->name);  
				           //$assignEmployeeDetails['location_name'] = $value->getCompanyLocation->name;            	
				           $companyChallengeLocationEmployee = CompanyChallengeLocationEmployee::where('challenge_id', $request->id )->where('company_id', $companyDetails->id)->where('company_location_id', $value->company_location_id)->orderBy('user_id', 'ASC')->get();
				           	   
					           $assignEmployeeDetails[$value->getCompanyLocation->name] =  $companyChallengeLocationEmployee;                    
				           
				        }
				    }	                
			                
			}
			//dd($assignEmployeeDetails);


            if($getchallengesDetails->challenge_taking_type == 1){
                 $getQuestionAnswerDetails = ChallengeQuestionAnswer::where('challenge_id', $request->id)->get();
                 return view('companyAdmin.challenge.challengesDetails',compact('getchallengesDetails', 'getQuestionAnswerDetails', 'heading','assignEmployeeDetails'));
            }else{
                return view('companyAdmin.challenge.challengesDetails',compact('getchallengesDetails', 'heading','assignEmployeeDetails'));
            }
	        
        }catch(Exception $ex) {
            return redirect()->back();
            //return redirect()->back()->withErrors(['error-messsage' => [$ex->getMessage()]]);
        } 
    }


    public function changeCompanychallengeStatus(Request $request){

        try{   

            $success = Challenge::where('id', $request->id)->update(['is_active' => $request->is_active]);
            return response()->json(['success' => true, 'result' => $success], 200);
        }
        catch(Exception $ex) {
            return response()->json(['success' => false, 'result' => [] ], 201);
        }

    }


    public function updateCompanyChallenge(Request $request){    	
    	try{
            $challenge_id = $request->input('challenge_id');            
            $user = Auth::guard('companyAdmin')->user();
            $companyDetails = $user->getCompanies->first();
            $getChallengeData = Challenge::where('id',$challenge_id)->first();
            if($getChallengeData->challenge_taking_type == 2 ){
                $photo_taken_challenge_rules = [
                    'point-value' => 'required|numeric',
                    'challenge_name' => 'required',
                    'challenge_description' => 'required',            
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $photo_taken_challenge_rules);
           }else{            
                $questionnaire_challenge_rules = [
                    'point-value' => 'required|numeric',
                    'challenge_question' => 'required',                    
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $questionnaire_challenge_rules);
            }
            if ($validator->fails()) {
                    return redirect()->back()->withErrors($validator->errors());
            }

             if($getChallengeData->challenge_taking_type == 2 ){
              $challenge_name  = $request->input('challenge_name');
              $challenge_description  = $request->input('challenge_description');
              $modal_desc = $request->input('modal_desc'); 
              $challenge_question = '';
              $modal_desc_true = '';
              $modal_desc_false = '';
            }else{
                $challenge_name = '';
                $challenge_description = '';
                $modal_desc = '';
                $challenge_question = $request->input('challenge_question');                
                $modal_desc_true = $request->input('modal_desc_true');
                $modal_desc_false = $request->input('modal_desc_false');
            }
            $pointvalue = $request->input('point-value');
            $start_date = date('Y-m-d', strtotime($request->input('start_date')));                         
            $start_time = date("H:i", strtotime($request->input('start_time')));
            $end_date = date('Y-m-d', strtotime($request->input('end_date')));
            $end_time = '23:59';
            $modal_header = $request->input('modal_header');
            $result = Challenge::where('id', $challenge_id)
                        ->update([
                            'point_value' => $pointvalue,
                            'challenge_name' =>$challenge_name,
                            'challenge_desc' =>$challenge_description,
                            'start_date' => $start_date,
                            'start_time' => $start_time,
                            'end_date' => $end_date,
                            'end_time' => $end_time,
                            'modal_header' =>$modal_header,
                            'modal_desc' => $modal_desc,
                            'modal_desc_true' => $modal_desc_true,
                            'modal_desc_false' => $modal_desc_false,
                            'challenge_question' => $challenge_question,

                        ]);

            if($result){
                if($getChallengeData->challenge_taking_type == 1 ){
                    $option = $request->input('answer-option');                    
                    ChallengeQuestionAnswer::where('challenge_id', $challenge_id)
                        ->where('id', $request->input('answer-option1-id'))
                        ->update([
                            'is_correct' => ($option == 'option1')? 1 : 0 ,
                            'answer' => $request->input('answer-option1-value')                         
                            ]);

                    ChallengeQuestionAnswer::where('challenge_id', $challenge_id)
                        ->where('id', $request->input('answer-option2-id'))
                        ->update([
                            'is_correct' => ($option == 'option2')? 1 : 0 ,
                            'answer' => $request->input('answer-option2-value')                         
                            ]);
                    
                }
            }
            $request->session()->flash('success-message', 'Challenge Updated Succeessfully');
            return redirect(route('companyAdmin.companyChallenge'));
        }
        catch(Exception $e){        
            return redirect()->back()->withErrors(['error-messsage' => [$e->getMessage()]]);
        }
    }

    public function getCompanyLocationEmployee(Request $request){    
        $secleted_location = $request->input('secleted_location');
        //dd($secleted_location);
        $userDetails = Auth::guard('companyAdmin')->user(); 
		$companyDetails = $userDetails->getCompanies->first();

        $company_location_employee_data=[];
        if(count($secleted_location) > 0){
            foreach($secleted_location as $secleted_location_id){
              if($secleted_location_id!=''){
                $location_data=CompanyLocation::where('id',$secleted_location_id)->first();                
                $employee_data = CompanyEmployeeLocation::where('company_employee_locations.company_id', $companyDetails->id )->where('company_employee_locations.location_id', $secleted_location_id )->where('company_employee_locations.is_active',1)->where('company_employee_locations.active_location', 1)->get();                
                if($employee_data->count() > 0){
                //if(!empty($employee_data)){
                    $data=['location_data'=>$location_data,'employee_data'=>$employee_data];
                    $company_location_employee_data[]=$data;
                }
              }
            }
        }  
        //dd($company_location_employee_data);     
       // return  $company_location_employee_data;
        return view('companyAdmin.challenge.getCompanyLocationEmployee', compact('company_location_employee_data'));
    } 

    public function companyDailyIndex(Request $request){

    	$userDetails = Auth::guard('companyAdmin')->user(); 
		$companyDetails = $userDetails->getCompanies->first();      
        if($request->ajax()) {            
            $is_active = $request->checkstatus;
            $filters   = [];
            if($is_active != '') { 
                $curent_date = date('Y-m-d H:i:s');
                $curent_time = date('G:i');
               // echo date('Y-m-d H:i:s');
                if($is_active== 'active'){
                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
                     $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
                    })
                    ->leftJoin('challenge_taking_types', function ($join) {
                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
                    })                    
                    ->select(
                        'challenges.id as id',
                        'challenges.start_date as start_date',
                        'challenges.start_time as start_time',
                        'challenges.end_date as end_date',
                        'challenges.end_time as end_time',                        
                        'challenges.challenge_name as challenge_name',
                        'challenges.challenge_question as challenge_question',
                        'challenges.is_active as is_active',   
                        'challenges.type_by_company as type_by_company',                     
                        'challenge_categories.name as challenge_cat_name',
                        'challenge_categories.image as image',
                        'challenge_taking_types.name as challenge_type',
                        //'challenges.start_time as start_time',
                    )                    
                    ->where('challenges.is_active',1)                    
                    //->whereDate('challenges.start_date','>=',)                   
                    //->whereDate('challenges.end_date','<=',)
                    //->where(DB::raw("CONCAT(`start_date`, ' ', `start_time`) <=".date('Y-m-d H:i:s')."'"))  
                    ->whereRaw("CONCAT(`start_date`, ' ', `start_time`) <='".date('Y-m-d H:i:s')."'")                  
                    //->whereRaw("CONCAT(`start_time`) <='".date('Y-m-d H:i:s')."'")                   
                    ->whereRaw("CONCAT(`end_date`, ' ', `end_time`) >='".date('Y-m-d H:i:s')."'")                 
                    ->where('challenges.is_delete',0)                    
                    ->where('challenges.created_by_admin_type',2)
	                ->where('challenges.challenge_type',2)  
	                ->where('challenges.user_id',$userDetails->id)                 
                    ->where('challenge_categories.is_active',1)
                    ->where('challenge_categories.is_delete',0)
                    ->where('challenge_taking_types.is_active',1)
                    ->where('challenge_taking_types.is_delete',0)                    
                    ->groupBy('challenges.id')                   
                    ->get();  
                    
                }
                else if($is_active== 'scheduled'){
                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
                    })
                    ->leftJoin('challenge_taking_types', function ($join) {
                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
                    })                    
                    ->select(
                        'challenges.id as id',
                        'challenges.start_date as start_date',
                        'challenges.start_time as start_time',
                        'challenges.end_date as end_date',
                        'challenges.end_time as end_time',                        
                        'challenges.challenge_name as challenge_name',
                        'challenges.challenge_question as challenge_question',
                        'challenges.is_active as is_active',    
                        'challenges.type_by_company as type_by_company',                     
                        'challenge_categories.name as challenge_cat_name',
                        'challenge_categories.image as image',
                        'challenge_taking_types.name as challenge_type' 
                    )                    
                    ->where('challenges.is_active',1)  
                    ->whereRaw("CONCAT(`start_date`, ' ', `start_time`) >='".date('Y-m-d H:i:s')."'")                  
                    ->where('challenges.is_delete',0) 
                    ->where('challenges.created_by_admin_type',2)
	                ->where('challenges.challenge_type',2)
	                ->where('challenges.user_id',$userDetails->id)                     
                    ->where('challenge_categories.is_active',1)
                    ->where('challenge_categories.is_delete',0)
                    ->where('challenge_taking_types.is_active',1)
                    ->where('challenge_taking_types.is_delete',0)                    
                    ->groupBy('challenges.id')
                    ->get();  
                }
                else if($is_active== 'completed'){
                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
                    })
                    ->leftJoin('challenge_taking_types', function ($join) {
                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
                    })                    
                    ->select(
                        'challenges.id as id',
                        'challenges.start_date as start_date',
                        'challenges.start_time as start_time',
                        'challenges.end_date as end_date',
                        'challenges.end_time as end_time',                        
                        'challenges.challenge_name as challenge_name',
                        'challenges.challenge_question as challenge_question',
                        'challenges.is_active as is_active',  
                        'challenges.type_by_company as type_by_company',                      
                        'challenge_categories.name as challenge_cat_name',
                        'challenge_categories.image as image',
                        'challenge_taking_types.name as challenge_type' 
                    )                    
                    ->where('challenges.is_active',1)  
                    ->whereRaw("CONCAT(`end_date`, ' ', `end_time`) <='".date('Y-m-d H:i:s')."'")               
                    ->where('challenges.is_delete',0)   
                    ->where('challenges.created_by_admin_type',2)
	                ->where('challenges.challenge_type',2)  
	                ->where('challenges.user_id',$userDetails->id)                    
                    ->where('challenge_categories.is_active',1)
                    ->where('challenge_categories.is_delete',0)
                    ->where('challenge_taking_types.is_active',1)
                    ->where('challenge_taking_types.is_delete',0)                    
                    ->groupBy('challenges.id')
                    ->get();  
                }
                else if($is_active== 'deactivated'){
                    $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
                    })
                    ->leftJoin('challenge_taking_types', function ($join) {
                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
                    })                    
                    ->select(
                        'challenges.id as id',
                        'challenges.start_date as start_date',
                        'challenges.start_time as start_time',
                        'challenges.end_date as end_date',
                        'challenges.end_time as end_time',                        
                        'challenges.challenge_name as challenge_name',
                        'challenges.challenge_question as challenge_question',
                        'challenges.is_active as is_active',
                        'challenges.type_by_company as type_by_company',                         
                        'challenge_categories.name as challenge_cat_name',
                        'challenge_categories.image as image',
                        'challenge_taking_types.name as challenge_type' 
                    )                    
                    ->where('challenges.is_active',0)                    
                    ->where('challenges.is_delete',0)    
                    ->where('challenges.created_by_admin_type',2)
	                ->where('challenges.challenge_type',2) 
	                ->where('challenges.user_id',$userDetails->id)                   
                    ->where('challenge_categories.is_active',1)
                    ->where('challenge_categories.is_delete',0)
                    ->where('challenge_taking_types.is_active',1)
                    ->where('challenge_taking_types.is_delete',0)                    
                    ->groupBy('challenges.id')
                    ->get();  
                }
            }else{

                $allChallenge = Challenge::leftJoin('challenge_categories', function ($join) {
                    $join->on('challenge_categories.id', '=', 'challenges.challenge_category_id');
                    })
                    ->leftJoin('challenge_taking_types', function ($join) {
                        $join->on('challenge_taking_types.id', '=', 'challenges.challenge_taking_type');
                    })                    
                    ->select(
                        'challenges.id as id',
                        'challenges.start_date as start_date',
                        'challenges.start_time as start_time',
                        'challenges.end_date as end_date',
                        'challenges.end_time as end_time',                        
                        'challenges.challenge_name as challenge_name',
                        'challenges.challenge_question as challenge_question',
                        'challenges.is_active as is_active',  
                        'challenges.type_by_company as type_by_company',              
                        'challenge_categories.name as challenge_cat_name',
                        'challenge_categories.image as image',
                        'challenge_taking_types.name as challenge_type' 
                    )                    
                    //->where('challenges.is_active',$is_active)                    
                    ->where('challenges.is_delete',0)  
                    ->where('challenges.created_by_admin_type',2)
	                ->where('challenges.challenge_type',2)   
	                ->where('challenges.user_id',$userDetails->id)                  
                    ->where('challenge_categories.is_active',1)
                    ->where('challenge_categories.is_delete',0)
                    ->where('challenge_taking_types.is_active',1)
                    ->where('challenge_taking_types.is_delete',0)                    
                    ->groupBy('challenges.id')
                    ->get();                   
            }
            return Datatables::of($allChallenge)
            ->addIndexColumn()
            ->addColumn('image', function($row){
                if($row->challenge_name != ''){
                    $button = '<a href="'.url('companyadmin/companydailychallenge/companydailychallengedetails/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/challenge/categories/web/'.$row->image).'" alt=""></a>
                               <a href="'.url('companyadmin/companydailychallenge/companydailychallengedetails/'.encript_decript_data($row->id,'encript' ,2)).'">'.$row->challenge_cat_name.' - '.substr($row->challenge_name, 0, 15).'...'.'</a>';
                }
                if($row->challenge_question != ''){
                    $button = '<a href="'.url('companyadmin/companydailychallenge/companydailychallengedetails/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/challenge/categories/web/'.$row->image).'" alt=""></a>
                               <a href="'.url('companyadmin/companydailychallenge/companydailychallengedetails/'.encript_decript_data($row->id,'encript' ,2)).'">'.$row->challenge_cat_name.' - '.substr($row->challenge_question, 0, 15).'...'.'</a>';
                }
                return $button;
            })
            ->addColumn('type_by_company', function($row){
                if($row->type_by_company==1){
                    return  'Company Wide';
                }
                if($row->type_by_company==2){
                    return  'Location Specific';
                }
            })
            ->addColumn('challenge_type', function($row){                
	                return $row->challenge_type;
	        })
            ->addColumn('start_date', function($row){
                return  date('d/m/Y', strtotime($row->start_date));
            })
            ->addColumn('start_time', function($row){
                return date('G:i', strtotime($row->start_time));
            })
            ->addColumn('end_date', function($row){
                return  date('d/m/Y', strtotime($row->end_date));
            })            
            ->addColumn('id', function($row){                
                return $row->id;
            })
            ->rawColumns(['image', 'type_by_company','challenge_type','start_date', 'start_time','end_date', 'id'])
            ->make(true);

        }
        return view('companyAdmin.challenge.dailychallenge.index');
    }


    public function addCompanyDailyChallenge(Request $request) {
		$userDetails = Auth::guard('companyAdmin')->user(); 
		$companyDetails = $userDetails->getCompanies->first();		
        $challengeCategories = ChallengeCategory::where('is_active', 1)->where('is_delete', 0)->get();
        $challengetakingTypes = ChallengeTakingType::where('is_active', 1)->where('is_delete', 0)->get();
        $location_data = CompanyLocation::where('company_locations.company_id', $companyDetails->id )->where('company_locations.is_active',1)->get();                        
    	$challenge = $request->session()->get('challenge');    	
        return view('companyAdmin.challenge.dailychallenge.addChallenge', compact('challenge', 'location_data', 'challengeCategories', 'challengetakingTypes'));
    }

    public function companyDailyChallengeCreateStep1(Request $request)
    {  

        $validatedData = $request->validate([
            'challenge_category_id' => 'required',
           
        ]);
        $validator = new Validator;
        $errors = 0;
        if(empty($request->session()->get('challenge'))){
            $challenge = new Challenge();
            $challenge->fill($validatedData);
            $request->session()->put('challenge', $challenge);
            $request->session()->put('location_name', $request->input('location_name'));
            /*******************working***********************/
            $request->session()->put('challenge_category_id', $request->input('challenge_category_id'));            
            $request->session()->put('type_by_company', $request->input('type_by_company'));

            $request->session()->put('global_challenge_taking_type', $request->input('global_challenge_taking_type'));
            $selected_location_ids=$request->input('location_name');
            $selected_company_with_locations=[];
            /*if(!empty($selected_location_ids)){
                 foreach($selected_location_ids as $selected_location_id){  
                    $validator = Validator::make($request->all(), [
                        "employee_list_".$selected_location_id => "required",
                        "employee_list_".$selected_location_id.".*" => "required",
                        ]);

                    if($validator->fails()){ 
                        $errors = 1;
                    }
                    $selected_company_with_locations[$selected_location_id]=$request->input('employee_list_'.$selected_location_id);                  
                 }

            }*/                       
            $request->session()->put('selected_company_with_locations', $selected_location_ids);   
            //$request->session()->put('selected_company_with_locations', $selected_company_with_locations);   
            $request->session()->put('location_name', $request->input('location_name'));
            $request->session()->put('company_specific_challenge_taking_type', $request->input('company_specific_challenge_taking_type'));
            $request->session()->put('selectCompanylocation', $request->input('selectCompanylocation'));
            $request->session()->put('selectCompanylocation', $request->input('selectCompanylocation'));
            $request->session()->put('selectedemployee', $request->input('employee_list'));            
            $request->session()->put('employee_specific', $request->input('employee_specific'));  
        }else{
            //if(!empty($request->session()->get('challenge')) && null !==$request->session()->get('challenge')){
            //if(!empty($request->session()->get('challenge')) && isset(!empty($request->session()->get('challenge')))){
            $challenge = new Challenge();
            $challenge->fill($validatedData);
            $request->session()->put('challenge', $challenge);
            $request->session()->put('location_name', $request->input('location_name'));
            /*******************working***********************/
            $request->session()->put('challenge_category_id', $request->input('challenge_category_id'));            
            $request->session()->put('type_by_company', $request->input('type_by_company'));

            $request->session()->put('global_challenge_taking_type', $request->input('global_challenge_taking_type'));
            $selected_location_ids=$request->input('location_name');
            $selected_company_with_locations=[];
            /*if(!empty($selected_location_ids)){
                 foreach($selected_location_ids as $selected_location_id){  
                    $validator = Validator::make($request->all(), [
                        "employee_list_".$selected_location_id => "required",
                        "employee_list_".$selected_location_id.".*" => "required",
                        ]);

                    if($validator->fails()){                                          	
                        $errors = 1;
                    }
                    $selected_company_with_locations[$selected_location_id]=$request->input('employee_list_'.$selected_location_id);                  
                 }

            }  */                     
            $request->session()->put('selected_company_with_locations', $selected_location_ids);   
            //$request->session()->put('selected_company_with_locations', $selected_company_with_locations);   
            $request->session()->put('location_name', $request->input('location_name'));
            $request->session()->put('company_specific_challenge_taking_type', $request->input('company_specific_challenge_taking_type'));
            $request->session()->put('selectCompanylocation', $request->input('selectCompanylocation'));
            $request->session()->put('selectCompanylocation', $request->input('selectCompanylocation'));
            $request->session()->put('selectedemployee', $request->input('employee_list'));            
            $request->session()->put('employee_specific', $request->input('employee_specific'));
        }    
        //dd($request->input('company_specific_challenge_taking_type'));  
        return redirect()->route('companyAdmin.company.daily.challengeCreateStep2');       
        /*if($request->input('type_by_company') == 1){
            return redirect()->route('companyAdmin.company.daily.challengeCreateStep2');
        }else{
            if($errors == 1){
                return redirect()->back()->withErrors("please select Employee");
            }else{
                return redirect()->route('companyAdmin.company.daily.challengeCreateStep2');
            }
        }*/
    }

    public function companyDailyChallengeCreateStep2(Request $request)
    { 

        try{
            $challenge = $request->session()->get('location_name');
            $global_challenge_taking_type = $request->session()->get('global_challenge_taking_type');
            $company_specific_challenge_taking_type = $request->session()->get('company_specific_challenge_taking_type');
            $type_by_company = $request->session()->get('type_by_company');
            $challenge_category_id = $request->session()->get('challenge_category_id');


            $heading_1 = ChallengeCategory::where('id', $challenge_category_id )->where('is_active', 1)->where('is_delete', 0)->first();
            
            if($type_by_company == 1){
                $heading_2 = 'Company wide Challenge';
            }else{
                $heading_2 = 'Location Specific Challenge';
            }
            if($global_challenge_taking_type ){

                $heading_3 = ChallengeTakingType::where('id', $global_challenge_taking_type )->where('is_active', 1)->where('is_delete', 0)->first();
            }else{
                $heading_3 = ChallengeTakingType::where('id', $company_specific_challenge_taking_type )->where('is_active', 1)->where('is_delete', 0)->first();
            }
            
            
            $heading = $heading_1->name.' - '.$heading_2.' - '.$heading_3->name;           
            return view('companyAdmin.challenge.dailychallenge.questionnaire-challenge',compact('challenge','global_challenge_taking_type','company_specific_challenge_taking_type','heading'));
        }
        catch(Exception $e){           
            return redirect()->back()->withErrors(['error-messsage' => [$e->getMessage()]]);
        }        
    }

    public function saveCompanyDailyChallenge(Request $request)
    {     
    	$location = [];
        $employee = [];
        $company_employee = [];
        $i = 0;
       // dd($request->session()->get('selectedemployee'));
        if( null != $request->session()->get('selectedemployee')){
            $selectedemployee = $request->session()->get('selectedemployee');
            foreach($selectedemployee as $key => $value){
                $explode_value = explode('-',$value);
                array_push($employee, $explode_value[1]);
                array_push($location, $explode_value[0]);
                //array_push($company, $explode_value[0]);
                $company_employee[$i][$explode_value[0]] = $explode_value[1];
                $i++;
            }       
            $employee_specific = $request->session()->get('employee_specific');
        }
       // dd($company_employee);
        try{            
            $user = Auth::guard('companyAdmin')->user();
            $companyDetails = $user->getCompanies->first();

            if($request->session()->get('global_challenge_taking_type') == 2 || $request->session()->get('company_specific_challenge_taking_type')==2){
                $photo_taken_challenge_rules = [
                    'point-value' => 'required|numeric',
                    'challenge_name' => 'required',           
                   // 'challenge_name' => 'required|unique:challenges,challenge_name',           
                    'challenge_description' => 'required',            
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $photo_taken_challenge_rules);
           }else{            
                $questionnaire_challenge_rules = [
                    'point-value' => 'required|numeric',
                    'challenge_question' => 'required',
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $questionnaire_challenge_rules);
            }

            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator->errors())->withInput(Input::all());
            }

            $location_name = $request->session()->get('location_name');
            $challenge_category_id = $request->session()->get('challenge_category_id');
            $type_by_company = $request->session()->get('type_by_company');

            $global_challenge_taking_type = $request->session()->get('global_challenge_taking_type');

            $company_specific_challenge_taking_type = $request->session()->get('company_specific_challenge_taking_type');

            $selectCompanylocation = $request->session()->get('selectCompanylocation');

            if($request->session()->get('global_challenge_taking_type') == 2 || $request->session()->get('company_specific_challenge_taking_type')==2){
              $challenge_name  = $request->input('challenge_name');
              $challenge_description  = $request->input('challenge_description');
              $modal_desc = $request->input('modal_desc'); 
              $challenge_question = '';
              $modal_desc_true = '';
              $modal_desc_false = '';
            }else{
                $challenge_name = '';
                $challenge_description = '';
                $modal_desc = '';
                $challenge_question = $request->input('challenge_question');                
                $modal_desc_true = $request->input('modal_desc_true');
                $modal_desc_false = $request->input('modal_desc_false');
            }

            if($type_by_company == 1){               
                $taken_type = $global_challenge_taking_type;
            }else{                
                $taken_type = $company_specific_challenge_taking_type;
            }            
            $pointvalue = $request->input('point-value');            
            $start_date = date('Y-m-d', strtotime($request->input('start_date')));                      
            $time = date("H:i", strtotime($request->input('start_time')));  
            $start_time = $time;          
            $end_date = date('Y-m-d', strtotime($request->input('end_date')));
            $end_time = '23:59';
            $modal_header = $request->input('modal_header');

            $challenge = new Challenge;
            $challenge->challenge_taking_type = $taken_type;
            $challenge->challenge_category_id = $challenge_category_id;
            $challenge->user_id = $user->id;
            $challenge->point_value = $pointvalue;
            $challenge->challenge_name = $challenge_name;
            $challenge->challenge_desc = $challenge_description;
            $challenge->start_date = $start_date;
            $challenge->start_time = $start_time;            
            $challenge->end_date = $end_date;
            $challenge->end_time = $end_time;
            $challenge->modal_header = $modal_header;
            $challenge->modal_desc = $modal_desc;
            $challenge->modal_desc_true = $modal_desc_true;
            $challenge->modal_desc_false = $modal_desc_false; 
            $challenge->challenge_question = $challenge_question;
            $challenge->created_by_admin_type = 2;
            $challenge->type_by_company = $type_by_company;            
            $challenge->challenge_type  = 2;
            $result = $challenge->save();            
            if($result){
                if($request->session()->get('global_challenge_taking_type') == 1 || $request->session()->get('company_specific_challenge_taking_type')== 1){
                    $option = $request->input('answer-option');
                    $insert_array = [
                        'challenge_id' => $challenge->id,
                        'is_correct' => ($option == 'option1')? 1 : 0 ,
                        //'answer' => 'option1' ,
                        'answer' => $request->input('answer-option1-value'),
                        //'answer' => ($option == 'option1')? 'option1' : 'option2' ,
                        'justification' => '',                
                        //'justification' => $request->input('answer-option1-value'), 
                    ];
                    ChallengeQuestionAnswer::create($insert_array);
                    $insert_array2 = [
                        'challenge_id' => $challenge->id,
                        'is_correct' => ($option == 'option2')? 1 : 0,
                        'answer' => $request->input('answer-option2-value') ,
                        //'answer' => 'option2' ,
                        'justification' => '',
                       // 'justification' => $request->input('answer-option2-value'),
                    ];
                    ChallengeQuestionAnswer::create($insert_array2);                    
                }
                if($type_by_company == 1){
                	$location_type = 1;
                }else{
                	$location_type = 0;
                }

                $companychallenges = [
                   'challenge_id' =>$challenge->id,
                   'company_id' =>$companyDetails->id,  
                   'location_type' => $location_type,                    
                   'approve_status' => 1,  
                ];
                Companychallenges::create($companychallenges);

                if($type_by_company == 2 ){                                   
                  $selected_company_with_locations = $request->session()->get('selected_company_with_locations');                   
                	if(!empty($selected_company_with_locations) && $selected_company_with_locations!= null){
                    
                    foreach($selected_company_with_locations as $key => $selected_company_with_location_row){ 
                        if(!empty($selected_company_with_location_row) && $selected_company_with_location_row!= null){ 
                            
                            if( isset($employee_specific)){
                              if(in_array($selected_company_with_location_row, $employee_specific)){
                                $companychallengelocations = [
                                       'challenge_id' =>$challenge->id,
                                       'company_id' => $companyDetails->id,
                                       'company_location_id' =>$selected_company_with_location_row,
                                       'is_employee_specfic'=> 0,
                                       'approve_status' => 1,                       
                                    ];
                                CompanyChallengeLocations::create($companychallengelocations);
                                //insert in to company_challenge_location_employees this table
                                foreach($company_employee as $item){  
                                  foreach($item as $loc => $emp_id){ 
                                    if($selected_company_with_location_row == $loc){
                                        $challengeAssignEmployee = [
                                           'challenge_id' => $challenge->id,
                                           'company_id' => $companyDetails->id,
                                           'company_location_id' =>$loc,                                                
                                           'user_id'=> $emp_id,
                                           'approve_status' => 1,                       
                                        ];                                               
                                    CompanyChallengeLocationEmployee::create($challengeAssignEmployee);
                                    }
                                  }
                                }
                              }else{
                                $companychallengelocations = [
                                   'challenge_id' =>$challenge->id,
                                   'company_id' => $companyDetails->id,
                                   'company_location_id' => $selected_company_with_location_row,
                                   'is_employee_specfic'=> 1,
                                   'approve_status' => 1,                       
                                ];
                               CompanyChallengeLocations::create($companychallengelocations);
                                }
                            }else{
                                $companychallengelocations = [
                                   'challenge_id' => $challenge->id,
                                   'company_id' => $companyDetails->id,
                                   'company_location_id' =>  $selected_company_with_location_row,
                                   'approve_status' => 1,
                                   'is_employee_specfic'=> 1,                       
                                ];
                                CompanyChallengeLocations::create($companychallengelocations);
                            }      
                        }                      
                    }
                }
                    
              }
            } 
            //=============push for company add challenge=====================//
	        $messageArr['title'] = get_notification_title('challenge-added-by-company-admin');
	        $messageArr['body']  = get_notification_text('challenge-added-by-company-admin');
	        $paramArr['type']    = 'company-admin-add-challenge';
	        $paramArr['challenge_id'] = $challenge->id;        
	        (new ChallengePushServices)->sendChallengePush($paramArr['challenge_id'], $messageArr, $paramArr);
 
            $request->session()->flash('success-message', 'Challenge Added Succeessfully');
            return redirect(route('companyAdmin.companyDailyChallenge'));
        }
        catch(Exception $e){
            return redirect()->back()->withErrors(['error-messsage' => [$e->getMessage()]]);
        }
       
    }

    public function companyDailyChallengeDetails(Request $request){
        try{
        	$userDetails = Auth::guard('companyAdmin')->user(); 
		    $companyDetails = $userDetails->getCompanies->first();	

        	$request->id = encript_decript_data($request->id,'decript' ,2);
            $getchallengesDetails = Challenge::where('id', $request->id)->first();

           
            if($getchallengesDetails == null){
            	return redirect()->back();
            }

            $heading_1 = ChallengeCategory::where('id', $getchallengesDetails->challenge_category_id )->where('is_active', 1)->where('is_delete', 0)->first();
            
            if($getchallengesDetails->type_by_company == 1){
                $heading_2 = 'Company wide Challenge';
            }else{
                $heading_2 = 'Location Specific Challenge';
            }
            if($getchallengesDetails->challenge_taking_type ){

                $heading_3 = ChallengeTakingType::where('id', $getchallengesDetails->challenge_taking_type )->where('is_active', 1)->where('is_delete', 0)->first();
            } 
             $heading = $heading_1->name.' - '.$heading_2.' - '.$heading_3->name;


             $assignEmployeeDetails = [];        
			if($getchallengesDetails->type_by_company == 2){	

				$companyChallengeLocations = CompanyChallengeLocations::where('challenge_id', $request->id )->where('company_id', $companyDetails->id)->orderBy('company_location_id', 'ASC')->get();
				//dd($companyChallengeLocations);
				//$assignEmployeeDetails['company_location'] = $companyChallengeLocations;

				    if(isset($companyChallengeLocations) && $companyChallengeLocations->count() > 0){
				        foreach($companyChallengeLocations as $item_loc => $value){  
				       // dd($value->getCompanyLocation->name);  
				           //$assignEmployeeDetails['location_name'] = $value->getCompanyLocation->name;            	
				           $companyChallengeLocationEmployee = CompanyChallengeLocationEmployee::where('challenge_id', $request->id )->where('company_id', $companyDetails->id)->where('company_location_id', $value->company_location_id)->orderBy('user_id', 'ASC')->get();
				           	   
					           $assignEmployeeDetails[$value->getCompanyLocation->name] =  $companyChallengeLocationEmployee;                    
				           
				        }
				    }	                
			                
			}

            if($getchallengesDetails->challenge_taking_type == 1){
                 $getQuestionAnswerDetails = ChallengeQuestionAnswer::where('challenge_id', $request->id)->get();
                 return view('companyAdmin.challenge.dailychallenge.challengesDetails',compact('getchallengesDetails', 'getQuestionAnswerDetails', 'heading','assignEmployeeDetails'));
            }else{
                return view('companyAdmin.challenge.dailychallenge.challengesDetails',compact('getchallengesDetails', 'heading','assignEmployeeDetails'));
            }
        }catch(Exception $ex) {
            return response()->json(['success' => false, 'result' => [] ], 201);
        } 
    }

    public function updateCompanyDailyChallenge(Request $request){    	
    	try{
            $challenge_id = $request->input('challenge_id');            
            $user = Auth::guard('companyAdmin')->user();
            $companyDetails = $user->getCompanies->first();
            $getChallengeData = Challenge::where('id',$challenge_id)->first();
            if($getChallengeData->challenge_taking_type == 2 ){
                $photo_taken_challenge_rules = [
                    'point-value' => 'required|numeric',
                    'challenge_name' => 'required',
                    'challenge_description' => 'required',            
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $photo_taken_challenge_rules);
           }else{            
                $questionnaire_challenge_rules = [
                    'point-value' => 'required|numeric',
                    'challenge_question' => 'required',                    
                    'start_date' => 'required',            
                    'start_time' => 'required',            
                    'end_date' => 'required',            
                ];
                $validator = Validator::make($request->all(), $questionnaire_challenge_rules);
            }
            if ($validator->fails()) {
                    return redirect()->back()->withErrors($validator->errors());
            }

             if($getChallengeData->challenge_taking_type == 2 ){
              $challenge_name  = $request->input('challenge_name');
              $challenge_description  = $request->input('challenge_description');
              $modal_desc = $request->input('modal_desc'); 
              $challenge_question = '';
              $modal_desc_true = '';
              $modal_desc_false = '';
            }else{
                $challenge_name = '';
                $challenge_description = '';
                $modal_desc = '';
                $challenge_question = $request->input('challenge_question');                
                $modal_desc_true = $request->input('modal_desc_true');
                $modal_desc_false = $request->input('modal_desc_false');
            }
            $pointvalue = $request->input('point-value');
            $start_date = date('Y-m-d', strtotime($request->input('start_date')));                         
            $start_time = date("H:i", strtotime($request->input('start_time')));
            $end_date = date('Y-m-d', strtotime($request->input('end_date')));
            $end_time = '23:59';
            $modal_header = $request->input('modal_header');
            $result = Challenge::where('id', $challenge_id)
                        ->update([
                            'point_value' => $pointvalue,
                            'challenge_name' =>$challenge_name,
                            'challenge_desc' =>$challenge_description,
                            'start_date' => $start_date,
                            'start_time' => $start_time,
                            'end_date' => $end_date,
                            'end_time' => $end_time,
                            'modal_header' =>$modal_header,
                            'modal_desc' => $modal_desc,
                            'modal_desc_true' => $modal_desc_true,
                            'modal_desc_false' => $modal_desc_false,
                            'challenge_question' => $challenge_question,

                        ]);

            if($result){
                if($getChallengeData->challenge_taking_type == 1 ){
                    $option = $request->input('answer-option');                    
                    ChallengeQuestionAnswer::where('challenge_id', $challenge_id)
                        ->where('id', $request->input('answer-option1-id'))
                        ->update([
                            'is_correct' => ($option == 'option1')? 1 : 0 ,
                            'answer' => $request->input('answer-option1-value')                         
                            ]);

                    ChallengeQuestionAnswer::where('challenge_id', $challenge_id)
                        ->where('id', $request->input('answer-option2-id'))
                        ->update([
                            'is_correct' => ($option == 'option2')? 1 : 0 ,
                            'answer' => $request->input('answer-option2-value')                         
                            ]);
                    
                }
            }
            $request->session()->flash('success-message', 'Challenge Updated Succeessfully');
            return redirect(route('companyAdmin.companyDailyChallenge'));
        }
        catch(Exception $e){        
            return redirect()->back()->withErrors(['error-messsage' => [$e->getMessage()]]);
        }
    }
    public function changeCompanyDailyChallengeStatus(Request $request){

        try{   

            $success = Challenge::where('id', $request->id)->update(['is_active' => $request->is_active]);
            return response()->json(['success' => true, 'result' => $success], 200);
        }
        catch(Exception $ex) {
            return response()->json(['success' => false, 'result' => [] ], 201);
        }

    }
}
