<?php
/****************************
 * File : assessment.php
 * Author : Cygnusa
 * @2018
****************************/

//SECURITY 
if ( ! defined('APPLICATION_PATH')) exit('No direct script access allowed');
//FUNCTION LISTS

class assessment
{	 
	function __construct($parent)
	{
		//GET PAGE MESSAGE
		$this->page_data=globalfunc::getMessage($parent,$parent->lang,'assessment');		 
		if(count($parent->params)==0)
		{	
			$this->assessmentfunc($parent);
			
		}else
		{
			$qry_params=explode ("?",$parent->params[0]);
			$parameter_val=strtolower($qry_params[0]);
			
			if(strtolower($parent->device_type)=='app')
			{
				switch($parameter_val){
                    
					case "question":  
                    case "startexam":      
                    case "review": 
                    case "assessment_status": 
						$this->$parameter_val($parent );
					break;
					 
					default:
						 $this->assessmentfunc($parent);
					break;
				}	
                    
			}else if(strtolower($parent->device_type)=='web')
			{	
                switch($parameter_val){
                    
					case "question": 
                    case "startexam": 
                    case "review":   
                    case "assessment_status":     
						$this->$parameter_val($parent );
					break;
					 
					default:
						 $this->assessmentfunc($parent);
					break;
				}	
            }		
		}
		$parent->response(array('response'=>'failed', 'message' => 'PAGE NOT FOUND'), 404);
	}
                    
    
	/* /////////////////////////////// ASSESSMENT MAIN FUNCTION  //////////////////////////////////////////////// */
	private function assessmentfunc($parent){	 
		globalfunc::checkMethodType($parent,array('GET','POST'));	
		switch ($parent->get_request_method()){
			case "GET":            
                globalfunc::checkParamCount($parent,0);
                globalfunc::checkAuthrozation($parent,array('type'=>'user'));

                //USER COND
                $user_cond_arr=projectfunc::getUserAssessmentCond($parent);               
                $user_cond=" AND ".@implode(' AND ',$user_cond_arr);
                
                //NEW ROLE CONDITION
                //$user_cond.=($parent->current_user_role>7 && $parent->current_user_role<14)?" AND a.user_type=0 ":" AND a.user_type=1 ";
                //NEW MANANGER LEVEL 
                
                //ALTER TABLE `tbl__assessment` CHANGE `user_type` `user_type` TINYINT(1) NOT NULL DEFAULT '0' COMMENT '0- Normal DSE, 1-Super bike, 2-HO, 3-ZM, 4-Trainer, 5-RM, 6-AM, 7-Dealer, 8-Customer Experience';
                switch($parent->current_user_role)
                {
                    //NORMAL DSE
                    case '8':
                    case '9':
                    case '10':    
                    case '11':        
                    case '12':
                    case '13':
                        $user_cond.=" AND a.user_type=0 ";
                        break;
                    //International Bike Sales Executive
                    case '15':
                        $user_cond.=" AND a.user_type=1 ";
                        break;
                    //HO Manager
                    case '3':
                        $user_cond.=" AND a.user_type=2 ";
                        break;
                    //Zonal Manager
                    case '4':
                        $user_cond.=" AND a.user_type=3 ";
                        break;
                    //Trainer
                    case '5':
                        $user_cond.=" AND a.user_type=4 ";
                        break;
                    //Regional Manager
                    case '6':
                        $user_cond.=" AND a.user_type=5 ";
                        break;
                    //Area Manager
                    case '7':
                        $user_cond.=" AND a.user_type=6 ";
                        break;
                    //Dealer
                    case '14':
                        $user_cond.=" AND a.user_type=7 ";
                        break;
                    //Customer Experience
                     case '16':
                        $user_cond.=" AND a.user_type=8 ";
                        break;
					 //Customer Experience
                     case '17':
                        $user_cond.=" AND a.user_type=9 ";
                        break;	
                }
                //NEW SEGMENT CONDITION
                if($parent->current_user_role>7 && $parent->current_user_role<14)
                {            
                    $user_cond.=" AND (a.segment='0' OR a.segment='".$parent->current_user_data->segment."')";
                }
                
                $status_arr=array();                
                //TRAINING VALIDATION
               //$assessment_str = "SELECT a.*,au.attemptslimit,au.publisheddate,au.enddate FROM ".TABLE_ASSESSMENT_USER." as au JOIN ".TABLE_ASSESSMENT." as a ON au.assessmentid=a.assessmentid WHERE a.status='1' AND a.assettypeid='1' AND  au.status='1' AND au.userid='".$parent->current_user_id."'   AND au.publisheddate<='".NOW."' ".$user_cond;            
                $assessment_str = "SELECT a.*  FROM  ".TABLE_ASSESSMENT." as a WHERE a.status='1' AND a.assettypeid='1'  AND a.publisheddate<='".NOW."' ".$user_cond." ORDER BY a.publisheddate DESC";              
                $assessment_arr=$parent->getQueryValue($assessment_str);	
                
               //$parent->executeQuery("INSERT INTO `".TABLE_QUERY_LOG."`(  `query_str`, `query_type`, `created_on`) VALUES ('". escape_str($assessment_str)."', 'assessment', '".NOW."')");
                
                if(count($assessment_arr)>0)
                {
                    //GET ALL STATUS
                    $status_str = "SELECT * FROM ".TABLE_STATUS;						
                    $status_res_arr=$parent->getQueryValue($status_str);

                    //print_r($status_res_arr);
                    if(count($status_res_arr)>0)
                    {
                        foreach($status_res_arr  as $res)
                        {                            
                            $obj_key=$res->statusid;
                            $status_arr[$obj_key]=$res->status;
                        }
                    }

                    /*
                     *  1	Active
                            //2	Inactive
                        3	Completed
                            //4	In Progress
                            //5	Published
                            //6	Closed
                        7	Not started
                        8	Expired
                    * 
                    */ 

                    //S3 OBJECT
                    $s3=awsfileserver::connectS3();
                    //ADD EXTRA FIELDS
                    foreach($assessment_arr as $key=>$res_assessment)
                    {
                        //assessmenttype 0-Offline,1-Online
                        $assessment_arr[$key]->assessmenttype_str=($res_assessment->assessmenttype=='0')?'Offline':'Online';
                        $assessment_arr[$key]->is_expired ='0';

                        //CHECK ALREADY ATTENDTED
                        $assessment_result_str = "SELECT * FROM ".TABLE_ASSESSMENTRESULT." WHERE assessmentid='".$res_assessment->assessmentid."' AND userid='".$parent->current_user_id."' ORDER BY arid DESC";
                        $assessment_result_arr=$parent->getQueryValue($assessment_result_str);                        
                        if(count($assessment_result_arr)>0)
                        {
                            //  3-Completed , 4 - In Progress
                            $assessment_arr[$key]->status =($assessment_result_arr[0]->status=='1')?'3':'1';
                            $res_assessment->status = $assessment_arr[$key]->status;    
                        } else {
                            $assessment_arr[$key]->status ='7';
                            $res_assessment->status = $assessment_arr[$key]->status;   
                        }

                        //EXPIRED
                        if(strtotime($res_assessment->enddate)<strtotime(NOW) AND count($assessment_result_arr)==0 )
                        {
                            $assessment_arr[$key]->is_expired='1';
                            $assessment_arr[$key]->status = '8';
                            $res_assessment->status = '8'; 
                        }

                        //STATUS STRING
                        $assessment_arr[$key]->statusname=(isset($status_arr[$res_assessment->status]))?$status_arr[$res_assessment->status]:"";

            
                        //ATTEMPT TIME
                        $attempt_time_str = "SELECT  * FROM ".TABLE_ASSESSMENTRESULT."  WHERE assessmentid='".$res_assessment->assessmentid."' AND userid='".$parent->current_user_id."' ORDER by attempt_time DESC";
                        $attempt_time_arr=$parent->getQueryValue($attempt_time_str);
                        $assessment_arr[$key]->attempt_time=(count($attempt_time_arr)>0)?$attempt_time_arr[0]->attempt_time:0;

                        //IS ATTENDED
                        $assessment_arr[$key]->is_attended='0';
                        $assessment_arr[$key]->completed_time='';

                        //HIGHSCORE
                        $assessment_arr[$key]->highscore='0';
                        if(count($attempt_time_arr)>0)
                        {            
                            $user_assessment_score_arr=array_column($attempt_time_arr,'percentage_score');        
                            rsort( $user_assessment_score_arr);
                            $assessment_arr[$key]->highscore=(string)$user_assessment_score_arr[0];
                            $assessment_arr[$key]->is_attended='1';    
                            $assessment_arr[$key]->completed_time=$attempt_time_arr[0]->enddatetime;
                            
                        }

                    }
                }
                //LOG
                $logstr='ASSESSMENT LIST';
                globalfunc::insertUserLog($parent,$logstr);
                $parent->response(array('response'=>'success', 'data'=>$assessment_arr, 'message'=>$this->page_data['success1']),200);
            
			break;
			case "POST":
                
                //ASSESSMENT SUBMIT                
				globalfunc::checkParamCount($parent,1);
				globalfunc::checkAuthrozation($parent,array('type'=>'user')); 
				$userid=$parent->current_user_id; 
				$assessmentid = escape_str($parent->params['0']);
                    
				
                //USER ASSESSMENT CHECK                
                $assessment_user_str = "SELECT * FROM ".TABLE_ASSESSMENT_USER." WHERE assessmentid='".$assessmentid."' AND userid='".$parent->current_user_id."' AND status='1'   LIMIT 1";
                $assessment_user_arr=$parent->getQueryValue($assessment_user_str);
                
                //VALIDATE ASSESSMENT
                projectfunc::userAssessmentValid($parent,$parent->current_user_id,$assessmentid);            

                //ASSESSMENT VALIDATION 
                $assessment_str = "SELECT * FROM ".TABLE_ASSESSMENT." WHERE assessmentid='".$assessmentid."' AND status='1' AND assettypeid='1' ".$user_cond." AND enddate>='".NOW."' LIMIT 1";
                $assessment_arr=$parent->getQueryValue($assessment_str);            
                if(count($assessment_arr)!=1) $parent->response(array('response'=>'failed','message'=>$this->page_data["error2"]),406);
                
				//FIELDS VALIDATION
				$REQUEST_KEYS=array('ans_arr'=>'string','startdatetime'=>'date|Y-m-d H:i:s','enddatetime'=>'date|Y-m-d H:i:s');
				globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
                
                //CHECK ANS ARRAY
				$ans_arr = json_decode($parent->_request["ans_arr"]);
                if(count($ans_arr)==0)
				{
					$parent->response(array('response'=>'failed','message'=>$this->page_data["error5"]), 406);
				}
                                
				$startdatetime = isset($parent->_request["startdatetime"])?escape_str($parent->_request["startdatetime"]):NOW;
				$enddatetime = isset($parent->_request["enddatetime"])?escape_str($parent->_request["enddatetime"]):NOW;
                $attempt_time=1;
                
                usleep(rand(100000,1000000));
                
                //CHECK USER ATTEMPT LIMIT                
                $get_userresult_str="SELECT * FROM ".TABLE_ASSESSMENTRESULT." WHERE assessmentid='".$assessmentid."' AND userid='".$parent->current_user_id."' AND status=0 ORDER BY arid DESC";
				$userresult_arr=$parent->getQueryValue($get_userresult_str); 
                //if(!(count($userresult_arr)>0)) $parent->response(array('response'=>'failed','message'=>$this->page_data["error8"]), 406);
                if(count($userresult_arr)>0 &&$userresult_arr[0]->status=='0')
                {
                    //RESULT ALREADY STARTED  NEED TO RESET
                    $parent->executeQuery("UPDATE ".TABLE_ASSESSMENTRESULT." SET  `assessmentdate`='".NOW."', `startdatetime`='".NOW."', `modified_on`='".NOW."' WHERE arid='".$userresult_arr[0]->arid."'");
                }else
                {
                    $get_userresult_str="SELECT * FROM ".TABLE_ASSESSMENTRESULT." WHERE assessmentid='".$assessmentid."' AND userid='".$parent->current_user_id."' ORDER BY arid DESC";
                    $userresult_arr=$parent->getQueryValue($get_userresult_str); 
                    $attempt_time=count($userresult_arr)+1;
                    
            
                    if($assessment_arr[0]->attemptslimit<=count($userresult_arr))
                    {
                        $parent->response(array('response'=>'failed','message'=>$this->page_data["error6"]), 406);
                    }
                                
                    //RESULT INSERT
                    $parent->executeQuery("INSERT INTO ".TABLE_ASSESSMENTRESULT." (`assessmentid`, `attempt_time`, `userid`, `assettypeid`, `assessmenttype`,`assessmentdate` , `startdatetime`,`status`, `created_on`, `modified_on`)VALUES('".$assessmentid."','".$attempt_time."','".$parent->current_user_id."','".$assessment_arr[0]->assettypeid."','".$assessment_arr[0]->assessmenttype."', '".NOW."','".NOW."','0','".NOW."','".NOW."')");
                    
                    $get_userresult_str="SELECT * FROM ".TABLE_ASSESSMENTRESULT." WHERE assessmentid='".$assessmentid."' AND userid='".$parent->current_user_id."' ORDER BY arid DESC";
                    $userresult_arr=$parent->getQueryValue($get_userresult_str); 
                }
            
                //ASSESSMENT SCORE
                $ques_arr=array();     
                $assessment_ques_arr=array();  
                if(count($ans_arr)>0)
				{
                    //GET QUESTION ARRAY
                    foreach($ans_arr as $res)
                    {
                        //print_r($res);
                        $question_arr[]=$res->qid;
                        $assessment_ques_arr[]=$res->aqid;
                    }                    
                }
            
                //CHECK QUESTION COUNT
                if(!(count($question_arr)>0) || !(count($assessment_ques_arr)>0))
                {
                    $parent->response(array('response'=>'failed','message'=>$this->page_data["error7"]), 406);
                }
                
                //VALIDATE QUESTION
                $validate_assessment_ques_str =" SELECT * FROM ".TABLE_ASSESSMENT_QUESTION." WHERE assessmentid='".$assessmentid."' AND aqid IN (".@implode(',',$assessment_ques_arr).") AND qid IN (".@implode(',',$question_arr).") ";
                $validate_assessment_ques_arr=$parent->getQueryValue($validate_assessment_ques_str);
                if(!(count($validate_assessment_ques_arr)>0)) $parent->response(array('response'=>'failed','message'=>$this->page_data["error9"]), 406);
                //if(!(count($validate_assessment_ques_arr)==count($assessment_ques_arr))) $parent->response(array('response'=>'failed','message'=>$this->page_data["error9"]), 406);
                
                //SCORE CALCULATION
                $assessmentscore_str = "SELECT SUM(op.score) as totalscore FROM (SELECT * FROM ".TABLE_QUESTIONOPTION." WHERE qid IN (".@implode(',',$question_arr).")  )as op  JOIN (SELECT * FROM ".TABLE_QUESTION." WHERE id IN (".@implode(',',$question_arr).") ) as q ON op.qid=q.id JOIN (SELECT * FROM ".TABLE_ASSESSMENT_QUESTION." WHERE assessmentid='".$assessmentid."' AND aqid IN (".@implode(',',$assessment_ques_arr).") ) aq ON aq.qid=q.id WHERE aq.assessmentid='".$assessmentid."' AND op.iscorrect=1";               
                $assessmentscore_arr=$parent->getQueryValue($assessmentscore_str);	
            
                $total_score='0';
                if(count($assessmentscore_arr)>0)
                {
                    $total_score=($assessmentscore_arr[0]->totalscore)?$assessmentscore_arr[0]->totalscore:'0';
                } 
                       
                //INSERT OPTIONS
                $insert_result_arr=array();
                for($mid = 0; $mid < count($ans_arr);$mid++)
                {
                    $aqid = $ans_arr[$mid]->aqid;
                    $qid = $ans_arr[$mid]->qid;
                    $options_arr = $ans_arr[$mid]->options;
            
                    if(is_array($options_arr) && count($options_arr)>0)
                    {
                        for($nid = 0; $nid < count($options_arr);$nid++)
                        {
                            $option_id = $options_arr[$nid];                            
                            $insert_result_arr[] = " ('".$userresult_arr[0]->arid."','".$assessmentid."','".$parent->current_user_id."','".$aqid."','".$qid."','".$option_id."','".NOW."','".NOW."')";
                        }
                    } else{
                        $insert_result_arr[] = " ('".$userresult_arr[0]->arid."','".$assessmentid."','".$parent->current_user_id."','".$aqid."','".$qid."','0','".NOW."','".NOW."')";    
                    } 
            
                }
            
                //DELETE USER RESULT
                $parent->executeQuery("DELETE FROM  ".TABLE_ASSESSMENT_USERRESULT."  WHERE  arid='".$userresult_arr[0]->arid."' AND userid='".$parent->current_user_id."' AND assessmentid='".$assessmentid."'");
                if(count($insert_result_arr)>0)
                {
                   $parent->executeQuery("INSERT INTO ".TABLE_ASSESSMENT_USERRESULT." (arid,assessmentid,userid,aqid,qid,choiseid,created_on,modified_on)VALUES ".@implode(',',$insert_result_arr)."");
                }
                
                
                //CALCULATE USER SCORE SINGLE CHOISE
               // $userscore_str = "SELECT SUM(op.score) as totalscore FROM ".TABLE_QUESTIONOPTION." as op JOIN ".TABLE_ASSESSMENT_USERRESULT." ar ON ar.choiseid=op.optid WHERE ar.assessmentid='".$assessmentid."' AND op.iscorrect=1 AND userid='".$parent->current_user_id."' AND arid='".$userresult_arr[0]->arid."'";
                $userscore_str = "SELECT SUM(op.score) as totalscore FROM ".TABLE_QUESTIONOPTION." as op JOIN ".TABLE_ASSESSMENT_USERRESULT." ar ON ar.choiseid=op.optid JOIN ".TABLE_QUESTION." as q ON ar.qid=q.id WHERE ar.assessmentid='".$assessmentid."'  AND q.questiontypeid='1' AND op.iscorrect=1 AND userid='".$parent->current_user_id."' AND arid='".$userresult_arr[0]->arid."'";
                //$userscore_arr = $userscore_qry->fetchAll(PDO::FETCH_OBJ);
                $userscore_arr=$parent->getQueryValue($userscore_str);	
                $user_score='0';
                if(count($userscore_arr)>0)
                {
                    $user_score=($userscore_arr[0]->totalscore)?$userscore_arr[0]->totalscore:'0';
                }
                
                //CHECK MULTI CHOICE
                $get_multi_choice_ques_str = "SELECT ar.* FROM  ".TABLE_ASSESSMENT_USERRESULT." as ar  JOIN ".TABLE_QUESTION." as q ON ar.qid=q.id WHERE ar.assessmentid='".$assessmentid."'  AND q.questiontypeid='2' AND ar.userid='".$parent->current_user_id."' AND ar.arid='".$userresult_arr[0]->arid."' GROUP BY ar.aqid ";            
                $get_multi_choice_arr=$parent->getQueryValue($get_multi_choice_ques_str);
                if(count($userscore_arr)>0)
                {
                    foreach($get_multi_choice_arr as $res_multi)
                    {
                        $ques_score=0;
                        //GET ALL QUESTION OPTIONS
                        $ques_option_str ="SELECT op.optid,op.opttext,op.score,op.iscorrect FROM ".TABLE_QUESTIONOPTION." as op WHERE op.qid='".$res_multi->qid."'";
                        $ques_option_arr=$parent->getQueryValue($ques_option_str);  

                        //GET USER ANSWERED OPTIONS
                        $user_answer_str ="SELECT * FROM ".TABLE_ASSESSMENT_USERRESULT."  WHERE userid='".$parent->current_user_id."' AND arid='".$userresult_arr[0]->arid."' AND aqid='".$res_multi->aqid."'";
                        $user_answer_arr=$parent->getQueryValue($user_answer_str);
                        
                        $correct_ans_arr=array();
                        $choise_arr=array();
                        if(count($ques_option_arr)>0)
                        {
                            if(count($user_answer_arr)>0)
                            {
                                $choise_arr=array_column($user_answer_arr,'choiseid');
                            }
                            
                            foreach($ques_option_arr as $mkey=>$res_opt)
                            {   
                                //correct ans
                                if($res_opt->iscorrect=='1')
                                {
                                    $correct_ans_arr[]=$res_opt->optid;
                                    $ques_score+=$res_opt->score;
                                }
                                
                            }

                        }
                        
                        //MUTIPLE CHOISE CORRECT ANSWER CHECK
                        if(count($correct_ans_arr)==count($choise_arr))
                        {
                            $result=array_diff($correct_ans_arr,$choise_arr);
                            $is_correct=(count($result)==0)?'1':'0';
                            if($is_correct=='1'){ $user_score+=$ques_score;}
                        }
                        
                    }
                }
                
                
                $percentage_score=($user_score>0 && $total_score>0)?round(($user_score/$total_score)*100):'0';
                //ASSESSMENT RESULT               
                
                $exam_time_diff=strtotime($enddatetime)-strtotime($startdatetime);
              
                $parent->executeQuery("UPDATE  ".TABLE_ASSESSMENTRESULT." SET userscore='".$user_score."',totalscore='".$total_score."', percentage_score='".$percentage_score."', `startdatetime`='".$startdatetime."',`enddatetime`='".$enddatetime."', time_taken='".$exam_time_diff."', `status`='1', `modified_on`='".NOW."' WHERE  arid='".$userresult_arr[0]->arid."'");
               
                //UPDATE HIGHSCORE IN TABLE_ASSESSMENT_USER
                $exam_highscore_str = "SELECT  * FROM ".TABLE_ASSESSMENTRESULT."  WHERE assessmentid='".$assessmentid."' AND userid='".$parent->current_user_id."' ORDER by percentage_score DESC LIMIT 1";
                $exam_highscore_arr=$parent->getQueryValue($exam_highscore_str);
            
                $highscore=(count($exam_highscore_arr)>0)?$exam_highscore_arr[0]->percentage_score:0;
                $highscorearid=(count($exam_highscore_arr)>0)?$exam_highscore_arr[0]->arid:0;
                
                if(count($assessment_user_arr)>0)
                {
                    $parent->executeQuery("UPDATE  ".TABLE_ASSESSMENT_USER." SET highscore='".$highscore."',highscorearid='".$highscorearid."',modified_on='".NOW."' WHERE  id='".$assessment_user_arr[0]->id."' AND userid='".$parent->current_user_id."'");
                }else
                {
                    $parent->executeQuery("INSERT INTO `".TABLE_ASSESSMENT_USER."`( `assessmentid`, `userid`,  `highscore`, `highscorearid`,   `status`, `created_on`, `modified_on`) VALUES ('".$assessmentid."','".$parent->current_user_id."','".$highscore."','".$highscorearid."','1','".NOW."','".NOW."')");
                }
                
                //LOG
                $logstr='ASSESSMENT SUBMIT';			 
                globalfunc::insertUserLog($parent,$logstr,$assessmentid);
                
                //ASSESSMENT SCORE > 80
                
                //if($percentage_score>=ASSESSMENT_PASS_PERCENT)
                if($percentage_score>=$assessment_arr[0]->pass_score)
                {
                    $msg="You have successfully qualified in ".$assessment_arr[0]->assessmentname."";
					
                    if($assessment_arr[0]->assessmentpoints>0 && in_array($parent->current_user_role,array('8','9','10','11','12','13')))
                    {
                        //ADD REWARD POINTS
                        $obj=new stdClass();
                        $obj->type="assessment";
                        $obj->type_id=$assessmentid;
                        $obj->description="Points for Assessment - ".$assessment_arr[0]->assessmentname."";
                        $obj->points=$assessment_arr[0]->assessmentpoints;
                        $status=projectfunc::userAddPoints($parent,$obj,$parent->current_user_id);
                        
                        if($status==1)
                        {
                            //SEND NOTIFICATION ON POINT ADD     
                            $nobj=new stdClass();
                            $nobj->notificationtitle='Reward points '.$assessment_arr[0]->assessmentpoints.' added ';
                            $nobj->notificationtext='Reward points '.$assessment_arr[0]->assessmentpoints.' has been added for qualifying assessment - '.$assessment_arr[0]->assessmentname;
                            $nobj->notificationtype='6';
                            $nobj->notificationdata=new stdClass();
                            // projectfunc::sendUserNotification($parent,$nobj);
                        }
                    }
                }else   
                {            
                   $msg="You must achieve ".$assessment_arr[0]->pass_score."% in order to pass.";
                }
                
                if ($assessment_arr[0]->schedule_id != 0) {
                   $msg = "You have completed assessment successfully";
                }
                
				$parent->response(array('response'=>'success', 'data'=>array('result_id'=>$userresult_arr[0]->arid,'user_score'=>$user_score,'total_score'=>$total_score,'percentage_score'=>$percentage_score),'assessment_msg'=>$msg,'message'=>$this->page_data['success1']),200);
			break;
		} 				
	}
 	/* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// ASSESSMENT STATUS  //////////////////////////////////////////////// */
    private function assessment_status($parent){
		globalfunc::checkMethodType($parent,array('GET'));	
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
		
        globalfunc::checkParamCount($parent,2);
        $assessmentid = escape_str($parent->params['1']);	
            
        //USER COND
        $user_cond_arr=projectfunc::getUserAssessmentCond($parent);               
        $user_cond=" AND ".@implode(' AND ',$user_cond_arr);
        
        //NEW ROLE CONDITION
        switch($parent->current_user_role)
        {
            //NORMAL DSE
            case '8':
            case '9':
            case '10':    
            case '11':        
            case '12':
            case '13':
                $user_cond.=" AND a.user_type=0 ";
                break;
            //International Bike Sales Executive
            case '15':
                $user_cond.=" AND a.user_type=1 ";
                break;
            //HO Manager
            case '3':
                $user_cond.=" AND a.user_type=2 ";
                break;
            //Zonal Manager
            case '4':
                $user_cond.=" AND a.user_type=3 ";
                break;
            //Trainer
            case '5':
                $user_cond.=" AND a.user_type=4 ";
                break;
            //Regional Manager
            case '6':
                $user_cond.=" AND a.user_type=5 ";
                break;
            //Area Manager
            case '7':
                $user_cond.=" AND a.user_type=6 ";
                break;
            //Dealer
            case '14':
                $user_cond.=" AND a.user_type=7 ";
                break;
             case '16':
                $user_cond.=" AND a.user_type=8 ";
                break;
        }
        if($parent->current_user_role>7 && $parent->current_user_role<14)
        {            
            $user_cond.=" AND (segment='0' OR segment='".$parent->current_user_data->segment."')";
        }    
        $status_arr=array();      
        $assessment_str = "SELECT a.* FROM  ".TABLE_ASSESSMENT." as a WHERE a.status='1' AND a.assettypeid='1'   AND a.assessmentid='".$assessmentid."'  AND a.publisheddate<='".NOW."' ".$user_cond." LIMIT 1";            
        $assessment_arr=$parent->getQueryValue($assessment_str);				
        if(count($assessment_arr)>0)
        {
          
            //GET ALL STATUS
            $status_str = "SELECT * FROM ".TABLE_STATUS;						
            $status_res_arr=$parent->getQueryValue($status_str);

            //print_r($status_res_arr);
            if(count($status_res_arr)>0)
            {
                foreach($status_res_arr  as $res)
                {                            
                    $obj_key=$res->statusid;
                    $status_arr[$obj_key]=$res->status;
                }
            }

            /*
             * 
                1	Active
                    //2	Inactive
                3	Completed
                    //4	In Progress
                    //5	Published
                    //6	Closed
                7	Not started
                8	Expired
            * 
            */ 

            //S3 OBJECT
            $s3=awsfileserver::connectS3();
            //ADD EXTRA FIELDS
            foreach($assessment_arr as $key=>$res_assessment)
            {
                //assessmenttype 0-Offline,1-Online
                $assessment_arr[$key]->assessmenttype_str=($res_assessment->assessmenttype=='0')?'Offline':'Online';


                $assessment_arr[$key]->is_expired ='0';
                //$assessment_arr[$key]->is_expired ='2';
                
                //CHECK ALREADY ATTENDTED
                $assessment_result_str = "SELECT * FROM ".TABLE_ASSESSMENTRESULT." WHERE assessmentid='".$res_assessment->assessmentid."' AND userid='".$parent->current_user_id."' ORDER BY arid DESC";
                $assessment_result_arr=$parent->getQueryValue($assessment_result_str);                        
                if(count($assessment_result_arr)>0)
                {
                    //  3-Completed , 4 - In Progress
                    $assessment_arr[$key]->status =($assessment_result_arr[0]->status=='1')?'3':'1';
                    $res_assessment->status = $assessment_arr[$key]->status;    
                } else {
                    $assessment_arr[$key]->status ='7';
                    $res_assessment->status = $assessment_arr[$key]->status;   
                }

                //EXPIRED
                if(strtotime($res_assessment->enddate)<strtotime(NOW))
                {
                    $assessment_arr[$key]->is_expired='1';
                    $assessment_arr[$key]->status = '8';
                    $res_assessment->status = '8'; 

                }

                //STATUS STRING
                $assessment_arr[$key]->statusname=(isset($status_arr[$res_assessment->status]))?$status_arr[$res_assessment->status]:"";

                 
                //ATTEMPT TIME
                $attempt_time_str = "SELECT  * FROM ".TABLE_ASSESSMENTRESULT."  WHERE assessmentid='".$res_assessment->assessmentid."' AND userid='".$parent->current_user_id."' ORDER by attempt_time DESC";
                $attempt_time_arr=$parent->getQueryValue($attempt_time_str);
                $assessment_arr[$key]->attempt_time=(count($attempt_time_arr)>0)?$attempt_time_arr[0]->attempt_time:0;

                //IS ATTENDED
                $assessment_arr[$key]->is_attended='0';

                //HIGHSCORE
                $assessment_arr[$key]->highscore='0';
                if(count($attempt_time_arr)>0)
                {            
                    $user_assessment_score_arr=array_column($attempt_time_arr,'percentage_score');        
                    rsort( $user_assessment_score_arr);
                    $assessment_arr[$key]->highscore=(string)$user_assessment_score_arr[0];
                    $assessment_arr[$key]->is_attended='1';    
                }

            }
        }else
        {
            $parent->response(array('response'=>'failed', 'message'=>$this->page_data['error2']),406);
        }
        //LOG
        $logstr='ASSESSMENT STATUS';
        globalfunc::insertUserLog($parent,$logstr,$assessmentid);
        $parent->response(array('response'=>'success', 'data'=>$assessment_arr[0],'message'=>$this->page_data['success1']),200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
	
	/* /////////////////////////////// QUESTION //////////////////////////////////////// */
	private function question($parent){
		globalfunc::checkMethodType($parent,array('GET'));		
		globalfunc::checkParamCount($parent,2);
		globalfunc::checkAuthrozation($parent,array('type'=>'user'));
		$assessmentid = escape_str($parent->params['1']);	
                    
        //VALIDATE ASSESSMENT
        projectfunc::userAssessmentValid($parent,$parent->current_user_id,$assessmentid);        
              
		//ASSESSMENT VALIDATION 
        $assessment_str = "SELECT * FROM ".TABLE_ASSESSMENT." WHERE assessmentid='".$assessmentid."' AND status='1'  AND assettypeid='1' LIMIT 1";
		$assessment_arr=$parent->getQueryValue($assessment_str);            
		if(count($assessment_arr)!=1) $parent->response(array('response'=>'failed','message'=>$this->page_data["error2"]),406);
        
        //S3 OBJECT
		$s3=awsfileserver::connectS3();
            
        if($assessment_arr[0]->randomcond=='1' )
        {
           $econd=" ORDER BY RAND() ";
        }else
        {
            $econd=" ORDER BY aq.aqid ASC";
        }
                
        $limit_str="  LIMIT 0,".$assessment_arr[0]->total_question." ";
        $ques_str ="SELECT aq.aqid,aq.is_mandatory,q.id as qid,  q.`questiontypeid`, q.`questiontext`, q.`qimage`, q.`qvideo`  FROM ".TABLE_QUESTION." as q JOIN (SELECT * FROM ".TABLE_ASSESSMENT_QUESTION." WHERE assessmentid='".$assessmentid."')as aq ON q.id=aq.qid WHERE 1=1 ".$econd.$limit_str;
        $ques_arr=$parent->getQueryValue($ques_str);

        if(count($ques_arr)>0)
        {
            //CONNECT S3
            $s3=awsfileserver::connectS3();
            foreach($ques_arr as $key=>$res_ques)
            {
                //QUESTION IMAGE
                $res_ques->qimage_url='';
                if($res_ques->qimage!='')
                {                    
                    $res_ques->qimage_url=awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_QUESTION_URL.$res_ques->qimage);     
                }

                //QUESTION VIDEO
                $res_ques->qvideo_url='';
                if($res_ques->qvideo!='')
                {                    
                    $res_ques->qvideo_url=awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_QUESTION_URL.$res_ques->qvideo); 
                }

                //CHOICE
                $chocie_arr=array();
                //WEB NEED selected
                $wed_cond=($parent->device_type=='web')?" ,'0' as selected ":'';
                $quesoption_str = "SELECT optid,opttext ".$wed_cond." FROM ".TABLE_QUESTIONOPTION." WHERE qid='".$res_ques->qid."'";
                $quesoption_arr=$parent->getQueryValue($quesoption_str);
                $res_ques->options = $quesoption_arr;

            

                $question_arr[]=$res_ques;
            }
        }
            
        //LOG
        $logstr='ASSESSMENT QUESTION';			 
        globalfunc::insertUserLog($parent,$logstr,$assessmentid);
        
		$parent->response(array('response'=>'success', 'data'=>$question_arr,'message'=>$this->page_data['success1']),200);		
	}
	/* //////////////////////////////////////////////////////////////////////////////////////////// */
        
    /* /////////////////////////////// STARTEXAM //////////////////////////////////////// */
	private function startexam($parent){
        globalfunc::checkMethodType($parent,array('GET'));		
		globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        globalfunc::checkParamCount($parent,2);
        
        //GET ASSESSMENTID
        $assessmentid = escape_str($parent->params[1]);	
               
        //VALIDATE ASSESSMENT
        projectfunc::userAssessmentValid($parent,$parent->current_user_id,$assessmentid); 
        
        //ASSESSMENT VALIDATION 
        $assessment_str = "SELECT * FROM ".TABLE_ASSESSMENT." WHERE assessmentid='".$assessmentid."' AND status='1'  AND assettypeid='1' LIMIT 1";
        $assessment_arr=$parent->getQueryValue($assessment_str);            
        if(count($assessment_arr)!=1) $parent->response(array('response'=>'failed','message'=>$this->page_data["error2"]),406);
        
        $attempt_time=1;
                
        //CHECK USER ATTEMPT LIMIT                
        $get_userresult_str="SELECT * FROM ".TABLE_ASSESSMENTRESULT." WHERE assessmentid='".$assessmentid."' AND userid='".$parent->current_user_id."' ORDER BY arid DESC";
        $userresult_arr=$parent->getQueryValue($get_userresult_str); 
        if($assessment_arr[0]->attemptslimit<=count($userresult_arr))
        {
            $parent->response(array('response'=>'failed','message'=>$this->page_data["error6"]), 406);
        }
        else
        {
            $attempt_time=count($userresult_arr)+1;
        }
        
        //CHECK IN PROGRESS EXAM EXIST
        if($userresult_arr[0]->status=='0')
        {
            //RESULT ALREADY STARTED  NEED TO RESET
            $parent->executeQuery("UPDATE ".TABLE_ASSESSMENTRESULT." SET  `assessmentdate`='".NOW."', `startdatetime`='".NOW."', `modified_on`='".NOW."' WHERE arid='".$userresult_arr[0]->arid."'");
        }else
        {
            //RESULT INSERT
            $parent->executeQuery("INSERT INTO ".TABLE_ASSESSMENTRESULT." (`assessmentid`, `attempt_time`, `userid`, `assettypeid`, `assessmenttype`,`assessmentdate` , `startdatetime`,`status`, `created_on`, `modified_on`)VALUES('".$assessmentid."','".$attempt_time."','".$parent->current_user_id."','".$assessment_arr[0]->assettypeid."','".$assessment_arr[0]->assessmenttype."', '".NOW."','".NOW."','0','".NOW."','".NOW."')");
        }
        //LOG
        $logstr='START ASSESSMENT';			 
        globalfunc::insertUserLog($parent,$logstr,$assessmentid);
                
        $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);		
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// REVIEW //////////////////////////////////////// */
	private function review($parent){
        globalfunc::checkMethodType($parent,array('GET'));		
		globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        globalfunc::checkParamCount($parent,2);
                
        //GET RESULTID
        $arid = escape_str($parent->params[1]);	
        
        $get_user_assessmentresult_str="SELECT * FROM ".TABLE_ASSESSMENTRESULT." WHERE userid='".$parent->current_user_id."' AND arid='".$arid."'";
        $user_assessmentresult_arr=$parent->getQueryValue($get_user_assessmentresult_str); 
        if(!(count($user_assessmentresult_arr)>0))
        {
            $parent->response(array('response'=>'failed','message'=>$this->page_data["error2"]), 406);
        }
        
        //CONNECT S3
        $s3=awsfileserver::connectS3();
        
        $result_arr=array();
        //GET ASSESSMENT RESULT
        $get_user_ques_result_str="SELECT * FROM ".TABLE_ASSESSMENT_USERRESULT." WHERE userid='".$parent->current_user_id."' AND arid='".$arid."' GROUP BY aqid ORDER BY userresultid ASC";
        $user_ques_result_arr=$parent->getQueryValue($get_user_ques_result_str); 
        if(count($user_ques_result_arr)>0)
        {
            foreach($user_ques_result_arr as $res_value)
            {
                $ques_str ="SELECT q.id as qid, q.`questiontypeid`, q.`questiontext`, q.`qimage`, q.`qvideo`  FROM ".TABLE_QUESTION." as q WHERE id='".$res_value->qid."' LIMIT 1";
                $ques_arr=$parent->getQueryValue($ques_str);

                if(count($ques_arr)>0)
                {
                    //QUESTION IMAGE
                    $ques_arr[0]->qimage_url='';
                    if($ques_arr[0]->qimage!='')
                    {
                        $ques_arr[0]->qimage_url=awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_QUESTION_URL.$ques_arr[0]->qimage); 
                    }

                    //QUESTION VIDEO
                    $ques_arr[0]->qvideo_url='';
                    if($ques_arr[0]->qvideo!='')
                    {                        
                        $ques_arr[0]->qvideo_url=awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_QUESTION_URL.$ques_arr[0]->qvideo); 
                    }
                    
                    //GET ALL QUESTION OPTIONS
                    $ques_option_str ="SELECT op.optid,op.opttext,op.score,op.iscorrect,'0' as selected  FROM ".TABLE_QUESTIONOPTION." as op WHERE op.qid='".$res_value->qid."'";
                    $ques_option_arr=$parent->getQueryValue($ques_option_str);  
                    
                    //GET USER ANSWERED OPTIONS
                    $user_answer_str ="SELECT * FROM ".TABLE_ASSESSMENT_USERRESULT."  WHERE userid='".$parent->current_user_id."' AND arid='".$arid."' AND aqid='".$res_value->aqid."'";
                    $user_answer_arr=$parent->getQueryValue($user_answer_str);
                                       
                    //CORRECT ANSWER CHECK 
                    $ques_arr[0]->is_correct='0';    
                    $correct_ans_arr=array();
                    $choise_arr=array();
                    if(count($ques_option_arr)>0)
                    {
                        if(count($user_answer_arr)>0)
                        {
                            $choise_arr=array_column($user_answer_arr,'choiseid');
                        }    
            
                        foreach($ques_option_arr as $mkey=>$res_opt)
                        {            
                            if(count($user_answer_arr)>0)
                            {
                                $ques_option_arr[$mkey]->selected=(in_array($res_opt->optid,$choise_arr))?'1':'0';                                                           
                            }
                            //correct ans
                            if($res_opt->iscorrect=='1')
                            {
                                $correct_ans_arr[]=$res_opt->optid;
                            }
                        }
                        
                    }
            
                    //MUTIPLE CHOISE CORRECT ANSWER CHECK
                    if(count($correct_ans_arr)==count($choise_arr))
                    {
                        $result=array_diff($correct_ans_arr,$choise_arr);
                        $ques_arr[0]->is_correct=(count($result)==0)?'1':'0';
                    }
            
                    
                    $ques_arr[0]->options=$ques_option_arr;
                    $result_arr[]=$ques_arr[0];
                }
            }
        }
        //LOG
        $logstr='ASSESSMENT REVIEW';			 
        globalfunc::insertUserLog($parent,$logstr,$arid);
        $parent->response(array('response'=>'success','data'=>$result_arr,'message'=>$this->page_data['success1']),200);	
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
}

?>