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

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

class trainer
{
                    
	//FUNCTION LISTS
	function __construct($parent)
	{
		//GET PAGE MESSAGE
		$this->page_data=globalfunc::getMessage($parent,$parent->lang,'trainer');
		if(count($parent->params)==0)
		{
			// $this->dashboardfunc($parent);
		}else
		{
			$qry_params=explode ("?",$parent->params[0]);
			$parameter_val=strtolower($qry_params[0]);
			
            switch($parameter_val){
                case "monthdata":
                case "training":  
                case "participant":    
                case "smpinparticipant":      
                case "removeparticipant":      
                case "batch":    
                    
                case "newtraining":    
                case "participantscore":    
                case "trainingimageupload":     
                case "participantimageupload":     
                    $this->$parameter_val($parent );
                break;
                default: 
                break;
            }
		}
		
		$parent->response(array('response'=>'failed', 'message' => 'PAGE NOT FOUND'), 404);
	}
    
                
    /* /////////////////////////////// MONTH DATA //////////////////////////////////////////////// */
	private function monthdata($parent)
	{               
		globalfunc::checkMethodType($parent,array('POST'));		 
		globalfunc::checkParamCount($parent,3);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        
        projectfunc::authorizedRole($parent,array('5'));
        
        $year_data=escape_str($parent->params[1]);
        $last_data = escape_str($parent->params[2]);
        $last_data_arr= explode('?',$last_data);
        $month_data=escape_str(trim($last_data_arr[0])); 
        
        $startmonth=date('Y-m-d',strtotime($year_data."-".$month_data."-01"))." 00:00:00"; 
        $nextmonth=date('Y-m-d',strtotime('+1 month',strtotime($startmonth)))." 23:59:59";
        
        //PAGINDATION
        $limit_str=globalfunc::setPageLimit($parent,$parent->params[2]);
        $limit_cond=($limit_str)?" LIMIT ".$limit_str:'';
        
        //SEARCH
        $search_cond='';
        $search_str = (isset($parent->_request["search"]))?escape_str($parent->_request["search"]):'';
        if($search_str!='')
        {
            $search_cond=" AND schedule_name LIKE'%".$search_str."%'";
        }


        $date_cond .= " AND (( start_date BETWEEN CAST('".$startmonth."' AS DATE) AND CAST('".$nextmonth."' AS DATE)) OR (end_date BETWEEN CAST('".$startmonth."' AS DATE)AND CAST('".$nextmonth."' AS DATE))OR ( CAST('".$startmonth."' AS DATE) BETWEEN start_date AND end_date) OR ( CAST('".$nextmonth."' AS DATE) BETWEEN start_date AND end_date))";
        $order_by_cond=" ORDER BY start_date ASC ";        
        $schedule_str = "SELECT * FROM ".TABLE_TRAINING_SCHEDULE." WHERE trainer_id='".$parent->current_user_id."' ".$date_cond.$search_cond.$order_by_cond.$limit_cond;;
        $schedule_arr=$parent->getQueryValue($schedule_str);
        
        if(count($schedule_arr)>0)
        {
            foreach($schedule_arr as $skey=>$res_schedule)
            {
                switch($res_schedule->assessment_type)
                {
                    case "0":     
                        $assessment_type_str="Pre Assessment";
                    break;
                    case "1":   
                        $assessment_type_str="Post Assessment";
                    break;
                    case "2":   
                        $assessment_type_str="Common";
                    break;

                }
                $schedule_arr[$skey]->assessment_type_str=$assessment_type_str;
                
                $schedule_status_str="";
                switch($res_schedule->status)
                {
                    case "1":     

                        if(strtotime($res_schedule->start_date)>strtotime(NOW))
                        {
                            $schedule_status_str="Not Started";
                        }else if(strtotime($res_schedule->end_date)>strtotime(NOW))
                        {
                            $schedule_status_str="Expired";
                        }else
                        {
                            $schedule_status_str="In-progress";
                        }
                    break;
                    case "2":   
                        $schedule_status_str="Closed";
                    break;
                    case "3":   
                        $schedule_status_str="Closed";
                    break;
                     case "4":   
                        $schedule_status_str="Closed";
                    break;

                }
                $schedule_arr[$skey]->status_str=$schedule_status_str;                
                $schedule_arr[$skey]->schedule_start_date=date('Y-m-d',strtotime($res_schedule->start_date)); 
            }
        }
        
        //GET COUNT
        $get_count_str="SELECT  COUNT(schedule_id)as scount FROM ".TABLE_TRAINING_SCHEDULE." WHERE trainer_id='".$parent->current_user_id."' ".$search_cond.$date_cond." LIMIT 1";
        $get_count_arr=$parent->getQueryValue($get_count_str); 
        $total=(count($get_count_arr)>0)?$get_count_arr[0]->scount:0;
        $last_page=($total)?ceil($total/$parent->current_limit)-1:0;
                    
        //LOG        
        $logstr='TRAINER TRAINING LIST';			 
        globalfunc::insertUserLog($parent,$logstr);        
        $parent->response(array('response'=>'success', 'data'=>$schedule_arr,'total'=>$total,'last_page'=>$last_page,'current_page'=>$parent->current_page,  'message'=>$this->page_data['success1']),200);  
        
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// TRAINING //////////////////////////////////////////////// */
	private function training($parent)
	{               
        globalfunc::checkMethodType($parent,array('GET','POST')); 
        
        switch ($parent->get_request_method()){
			case "GET": 
                globalfunc::checkParamCount($parent,2); 
                globalfunc::checkAuthrozation($parent,array('type'=>'user'));
                projectfunc::authorizedRole($parent,array('5'));
                
                $schedule_id=escape_str($parent->params[1]);
                $schedule_str = "SELECT * FROM ".TABLE_TRAINING_SCHEDULE." WHERE trainer_id='".$parent->current_user_id."' AND schedule_id='".$schedule_id."'  LIMIT 1";
                $schedule_arr=$parent->getQueryValue($schedule_str);
                if(count($schedule_arr)>0)
                {
                    $schedule_arr[0]->participant=array();
                    
                    switch($schedule_arr[0]->assessment_type)
                    {
                        case "0":     
                            $assessment_type_str="Pre Assessment";
                        break;
                        case "1":   
                            $assessment_type_str="Post Assessment";
                        break;

                    }
                    $schedule_arr[0]->assessment_type_str=$assessment_type_str;

                    $schedule_status_str="";
                    switch($schedule_arr[0]->status)
                    {
                        case "1":     

                            if(strtotime($schedule_arr[0]->start_date)>strtotime(NOW))
                            {
                                $schedule_status_str="Not Started";
                            }else if(strtotime($schedule_arr[0]->end_date)>strtotime(NOW))
                            {
                                $schedule_status_str="Expired";
                            }else
                            {
                                $schedule_status_str="In-progress";
                            }
                        break;
                        case "2":   
                            $schedule_status_str="Closed";
                        break;
                        case "3":   
                            $schedule_status_str="Closed";
                        break;
                         case "4":   
                            $schedule_status_str="Closed";
                        break;

                    }
                    $schedule_arr[0]->status_str=$schedule_status_str;                
                    $schedule_arr[0]->schedule_start_date=date('Y-m-d',strtotime($res_schedule->start_date)); 
                    
                    
                    //PARTICIPANT
                    $participant_str = "SELECT p.`userid`, p.`is_attendance`,p.remarks, p.`score`, p.`assessment_score`,u.smpin,CONCAT(fname,lname)as name,d.dealer_name,p.creatorid FROM ".TABLE_TRAINING_PARTICIPANT."  p JOIN ".TABLE_USER." u ON p.userid=u.userid JOIN ".DMS_DEALER." d ON d.dealer_code=u.dealer_code WHERE p.schedule_id='".$schedule_arr[0]->schedule_id."' ";
                    $participant_arr=$parent->getQueryValue($participant_str);
                    
                    if(count($participant_arr)>0)
                    { 
                        foreach($participant_arr as $skey=>$res_part)
                        {
                            $assessment_str = "SELECT ta.assessmentid,ta.schedule_id FROM ".TABLE_TRAINING_ASSESSMENT." as ta JOIN ".TABLE_ASSESSMENT_USER." as au ON ta.assessmentid=au.assessmentid AND ta.userid=au.userid WHERE ta.schedule_id='".$schedule_arr[0]->schedule_id."' AND ta.userid='".$res_part->userid."' LIMIT 1";
                            $assessment_arr=$parent->getQueryValue($assessment_str);
                            
                            $participant_arr[$skey]->is_edit=($res_part->creatorid==$parent->current_user_id)?"1":"0";
                            $participant_arr[$skey]->is_delete=(count($assessment_arr)>0)?"0":"1";
                            $participant_arr[$skey]->is_created=($res_part->creatorid==$parent->current_user_id)?"1":"0";
                            
                        }
                        $schedule_arr[0]->participant=$participant_arr;
                    }
                    
                    //LOG        
                    $logstr='TRAINING DETAILS';			 
                    globalfunc::insertUserLog($parent,$logstr); 
                    
                    
                    $parent->response(array('response'=>'success', 'data'=>$schedule_arr[0], 'message'=>$this->page_data['success1']),200);   
                }else
                {
                    $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
                }
               
                
                
            break;
            case "POST": 
                //SUBMIT 
                globalfunc::checkParamCount($parent,2); 
                globalfunc::checkAuthrozation($parent,array('type'=>'user'));
                projectfunc::authorizedRole($parent,array('5')); 
                
                $schedule_id=escape_str($parent->params[1]);
                
                //FIELDS VALIDATION
				$REQUEST_KEYS=array('participant_json'=>'string');
				globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
                
                //CHECK ANS ARRAY
				$participant_arr = json_decode($parent->_request["participant_json"]);
                
                if(!count($participant_arr)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error2"]),406);
                        
                
                $schedule_str = "SELECT * FROM ".TABLE_TRAINING_SCHEDULE." WHERE trainer_id='".$parent->current_user_id."' AND schedule_id='".$schedule_id."' LIMIT 1";
                $schedule_arr=$parent->getQueryValue($schedule_str);
                 
                $user_id_arr=array();
                if(count($schedule_arr)>0)
                {
                    //DATE CHECK
                    if(strtotime(NOW)>=strtotime($schedule_arr[0]->end_date))$parent->response(array('response'=>'failed','message'=>$this->page_data["error3"]),406);    
                    
                    foreach($participant_arr as $res_part)
                    {
                        $participant_ids[]=$res_part->userid;      
                        $user_id_arr[$res_part->userid]=$res_part;   
                    }
                        
                    $assessment_str = "SELECT ta.assessmentid,ta.schedule_id FROM ".TABLE_TRAINING_ASSESSMENT." as ta JOIN ".TABLE_ASSESSMENT_USER." as au ON ta.assessmentid=au.assessmentid AND ta.userid=au.userid WHERE ta.schedule_id='".$schedule_id."' AND ta.userid NOT IN (".@implode(',',$participant_ids).") LIMIT 1";
                    $assessment_arr=$parent->getQueryValue($assessment_str);
                    
                    if(count($assessment_arr)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error4"]),406);
                    
                    //CURRENT PARTICIPNAT
                    $schedule_part_str = "SELECT * FROM ".TABLE_TRAINING_PARTICIPANT." WHERE  schedule_id='".$schedule_id."' ";
                    $schedule_part_arr=$parent->getQueryValue($schedule_part_str);
                   
                    if(count($schedule_part_arr)>0)
                    {
                        foreach($schedule_part_arr as $res_part)
                        {
                            $cur_participant_ids[]=$res_part->userid;     
                            
                            if(in_array($res_part->userid, $participant_ids)) 
                            {
                                $update_str="UPDATE ".TABLE_TRAINING_PARTICIPANT ." SET `is_attendance`='".$user_id_arr[$res_part->userid]->is_attendance."', `remarks`='".$user_id_arr[$res_part->userid]->remarks."', `score`='".$user_id_arr[$res_part->userid]->score."', `modified_on`='".NOW."' WHERE participant_id='".$res_part->participant_id."'";   
                                $parent->executeQuery($update_str);
                            }
                            
                        }
                        
                        //GET NEW PARTICIPANT 
                        $new_participant=array_diff($participant_ids,$cur_participant_ids);
                        if(count($new_participant)>0)
                        {
                            $new_part_ins=array();
                            foreach($new_participant as $res_part)
                            {
                                $participant_data=$user_id_arr[$res_part];
                                $new_part_ins[]=" ( '".$schedule_id."', '".$res_part."','".$participant_data->is_attendance."', '".$participant_data->remarks."','".$participant_data->score."','','".$parent->current_user_id."','".NOW."','".NOW."')";
                            }
                            //INSERT NEW PARTICIPANT
                            $insert_part_qry = "INSERT INTO ".TABLE_TRAINING_PARTICIPANT ." ( `schedule_id`, `userid`, `is_attendance`, `remarks`, `score`, `assessment_score`, `creatorid`, `created_on`, `modified_on`) VALUES ".@implode(',',$new_part_ins);                             
                            $parent->executeQuery($insert_part_qry);
                        }  
                        
                        //DELETE
                        $delete_participant=array_diff($cur_participant_ids,$participant_ids);
                        if(count($delete_participant)>0)
                        {
                            //DELETE  PARTICIPANT
                            $delete_part_qry = "DELETE FROM  ".TABLE_TRAINING_PARTICIPANT ." WHERE schedule_id='".$schedule_id."' AND userid IN (".@implode(',',$delete_participant).")";
                            $parent->executeQuery($delete_part_qry);
                        }
                        
                    }else
                    {
                        $new_part_ins=array();
                        foreach($participant_arr as $res_part)
                        {
                            $participant_ids[]=$res_part->userid;         
                            $participant_data=$user_id_arr[$res_part];
                            $new_part_ins[]=" ( '".$schedule_id."', '".$res_part."','".$participant_data->is_attendance."', '".$participant_data->remarks."','".$participant_data->score."','','".$parent->current_user_id."','".NOW."','".NOW."')";
                        }
                        //INSERT NEW PARTICIPANT
                        $insert_part_qry = "INSERT INTO ".TABLE_TRAINING_PARTICIPANT ." ( `schedule_id`, `userid`, `is_attendance`, `remarks`, `score`, `assessment_score`, `creatorid`, `created_on`, `modified_on`) VALUES ".@implode(',',$new_part_ins);                             
                        $parent->executeQuery($insert_part_qry);
                    }
                    
                    $assessment_str = "SELECT * FROM ".TABLE_TRAINING_ASSESSMENT." WHERE schedule_id='".$schedule_id."'";
                    $assessment_arr=$parent->getQueryValue($assessment_str);
                    
                    if(count($assessment_arr)>0)
                    {
                        foreach($assessment_arr as $res_ass)
                        {
                            $cur_assess_ids[]=$res_ass->userid;                        
                        }
                        //GET NEW PARTICIPANT 
                        $new_ass_participant=array_diff($participant_ids,$cur_assess_ids);
                        if(count($new_ass_participant)>0)
                        {
                            $new_ass_ins=array();
                            foreach($new_ass_participant as $res_ass_part)
                            {
                                $new_ass_ins[]=" ( '".$assessment_arr[0]->assessmentid."', '".$schedule_id."','".$res_ass_part->userid."', '0')";
                            }
                            //INSERT NEW PARTICIPANT
                            $insert_ass_qry = "INSERT INTO ".TABLE_TRAINING_ASSESSMENT ." (`assessmentid`, `schedule_id`, `userid`, `is_attended`) VALUES ".@implode(',',$new_ass_ins);                             
                            $parent->executeQuery($insert_ass_qry);
                        }
                        
                        //DELETE
                        $delete_ass_participant=array_diff($cur_assess_ids,$participant_ids);
                        if(count($delete_ass_participant)>0)
                        {
                            //DELETE  PARTICIPANT
                            $delete_asspart_qry = "DELETE FROM  ".TABLE_TRAINING_ASSESSMENT ." WHERE schedule_id='".$schedule_id."' AND userid IN (".@implode(',',$delete_ass_participant).")" ;
                            $parent->executeQuery($delete_asspart_qry);
                        }
                        
                    }else
                    {
                       $get_assess_str = "SELECT * FROM ".TABLE_ASSESSMENT." WHERE schedule_id='".$schedule_id."' AND atype='1' LIMIT 1";
                       $get_assess_arr=$parent->getQueryValue($get_assess_str);
                       if(count($get_assess_arr)>0)
                       {
                           $new_ins_ass=array();
                           foreach($participant_arr as $res_part)
                           {
                                //$participant_ids[]=$res_part->userid;                 
                                $new_ins_ass[]=" ( '".$get_assess_arr[0]->assessmentid."', '".$schedule_id."','".$res_part->userid."','')";
                           }
                           
                           //INSERT TRAINING ASSESSMENT
                           $insert_ins_qry = "INSERT INTO ".TABLE_TRAINING_ASSESSMENT ." (`assessmentid`, `schedule_id`, `userid`, `is_attended`) VALUES ".@implode(',',$new_ins_ass);                             
                           $parent->executeQuery($insert_ins_qry);
                       }
                        
                    }
                    $is_save =(isset($parent->_request["is_save"]))? escape_str($parent->_request["is_save"]):'';
                    if($is_save!='1')
                    {                        
                        //UPDATE 
                        $update_qry = "UPDATE ".TABLE_TRAINING_SCHEDULE ." SET status='2', modified_on='".NOW."' WHERE schedule_id='".$schedule_id."'";                             
                        $parent->executeQuery($update_qry);
                    }
                        
                }else
                {
                    $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
                }
				
				//LOG        
				$logstr='TRAINING SUBMIT';			 
				globalfunc::insertUserLog($parent,$logstr,$schedule_id); 
                
                $parent->response(array('response'=>'success', 'data'=>$schedule_arr[0], 'message'=>$this->page_data['success1']),200);  
            break;
        }
         
        
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// PARTICIPANT //////////////////////////////////////////////// */
	private function participant($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));		 
		globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        
        $REQUEST_KEYS=array('lvl_id'=>'integer');
		globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        
        $lvl_id=$parent->_request["lvl_id"];
        
        if((isset($parent->_request["zone"])))
        {
            $zone = (isset($parent->_request["zone"]))?escape_str($parent->_request["zone"]):'';
            if($zone)
            {
                $zone_arr=@explode(',',$zone);
                $zone_quotes = array_map("quotes_array", $zone_arr);                 
                $dealercond.=" AND zone IN (".@implode(',',$zone_quotes).")";
            }else
            {
                $dealercond.=" AND zone IN ('')";
            }
        }
        
        if(isset($parent->_request["city"]) )
        {
            $city = (isset($parent->_request["city"]) )?escape_str($parent->_request["city"]):'';
            if($city)
            {
                $city_arr=@explode(',',$city);
                $city_quotes = array_map("quotes_array", $city_arr);                 
                $dealercond.=" AND city IN (".@implode(',',$city_quotes).")";
            }else
            {
                $dealercond.=" AND city IN ('')";
            }
        } 
        
        if((isset($parent->_request["dealer"])))
        {
            $dealer = (isset($parent->_request["dealer"]))?escape_str($parent->_request["dealer"]):'';
            if($dealer)
            {
                $dealer_arr=@explode(',',$dealer);
                $dealer_quotes = array_map("quotes_array", $dealer_arr);                 
                $cond.=" AND dealer IN (".@implode(',',$dealer_quotes).")";
                $dealer_code_cond=" AND dealer_code IN (".@implode(',',$dealer_quotes).")";
            }else
            {
                $cond.=" AND dealer IN ('')";
                $dealer_code_cond=" AND dealer_code IN ('')";
            }
        }
        if((isset($parent->_request["schedule_id"])))
        {
            $edit_cond=" AND s.schedule_id!='".escape_str($parent->_request["schedule_id"])."'";
        }
        
        if((isset($parent->_request["user_type"])))
        {
            $edit_cond=" AND s.schedule_id!='".escape_str($parent->_request["user_type"])."'";
        }
        $user_cond=(isset($parent->_request["user_type"]) && $parent->_request["user_type"]=='0')?" AND role>7 AND role<14":" AND role=15";        
        
        $data_arr=array();
        $dealercond=($dealercond!='')?" AND dealer_code IN  (SELECT * FROM ".DMS_DEALER." WHERE status='1' AND ".$dealercond.")":"";
                        
        $dealer_arr=$parent->getQueryValue("SELECT * FROM ".DMS_DEALER." WHERE  status='1'  ".$dealer_code_cond.$dealercond);
        if(count($dealer_arr)>0)
        {  

            foreach($dealer_arr as $res_dealer)
            {
                $arr=new stdClass();
                $query_str = "SELECT userid,`smpin`, CONCAT(fname,lname) as name FROM ".TABLE_USER." WHERE   status='1' ".$user_cond." AND is_deleted='0' AND dealer_code='".$res_dealer->dealer_code."' AND smpin IN (SELECT smpin FROM ".TABLE_USER_LEARNING." WHERE current_status='1' AND lvl_id='".$lvl_id."') AND userid NOT IN (SELECT p.userid FROM ".TABLE_TRAINING_PARTICIPANT." p JOIN ".TABLE_TRAINING_SCHEDULE." s ON p.schedule_id=s.schedule_id WHERE s.status<4 AND s.is_deleted=0 ".$edit_cond.")  ORDER BY dealer_code"; 
                $user_arr=$parent->getQueryValue($query_str);
                if(count($user_arr)>0)
                {
                    $arr->user =$user_arr;
                    $arr->dealer_code=$res_dealer->dealer_code;
                    $arr->dealer_name=$res_dealer->dealer_name;
                    $data_arr[]=$arr;
                }
            }
        }
        
		//LOG        
		$logstr='PARTICIPANT LIST';			 
		globalfunc::insertUserLog($parent,$logstr);	
		$parent->response(array('response'=>'success', 'data'=>$data_arr, 'message'=>$this->page_data['success1']),200);    
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// PARTICIPANT //////////////////////////////////////////////// */
	private function smpinparticipant($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));		 
		globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
       
        //FIELDS VALIDATION
        $REQUEST_KEYS=array('schedule_id'=>'integer','smpin'=>'string');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        
        $schedule_id= escape_str($parent->_request["schedule_id"]);
        $smpin= escape_str($parent->_request["smpin"]);
        
        $schedule_str = "SELECT * FROM ".TABLE_TRAINING_SCHEDULE." WHERE trainer_id='".$parent->current_user_id."' AND schedule_id='".$schedule_id."' LIMIT 1";
        $schedule_arr=$parent->getQueryValue($schedule_str);
                        
        $user_id_arr=array();
        if(count($schedule_arr)>0)
        {
            $lvl_id=$schedule_arr[0]->lvl_id;
            
            $user_cond=($schedule_arr[0]->user_type=='0')?" AND role>7 AND role<14":" AND role=15";        
            
            $query_smpin_str = "SELECT userid,`smpin`, CONCAT(fname,lname) as name FROM ".TABLE_USER." WHERE  status='1' ".$user_cond." AND is_deleted='0' AND smpin IN (SELECT smpin FROM ".TABLE_USER_LEARNING." WHERE current_status='1' AND lvl_id='".$lvl_id."')  AND smpin='".$smpin."' ORDER BY dealer_code";      
            $user_arr=$parent->getQueryValue($query_smpin_str);
            if(count($user_arr)>0)
            {
                  //  AND userid NOT IN (SELECT p.userid FROM ".TABLE_TRAINING_PARTICIPANT." p JOIN ".TABLE_TRAINING_SCHEDULE." s ON p.schedule_id=s.schedule_id WHERE s.status<4 AND s.is_deleted=0 )
                //USER ALREADY IN PARTICIPANT
                $query_check_str ="SELECT p.userid FROM ".TABLE_TRAINING_PARTICIPANT." p JOIN ".TABLE_TRAINING_SCHEDULE." s ON p.schedule_id=s.schedule_id WHERE s.status<4 AND s.is_deleted=0 AND p.userid='".$user_arr[0]->userid."' ";
                $check_arr=$parent->getQueryValue($query_check_str);
                if(count($check_arr)>0)
                {
                    $parent->response(array('response'=>'failed','message'=>$this->page_data["error6"]),406); 
                }else
                {
                    $insert_train_qry = "INSERT INTO ".TABLE_TRAINING_PARTICIPANT ." ( `schedule_id`, `userid`, `is_attendance`, `score`, `assessment_score`, `creatorid`, `created_on`, `modified_on`) VALUES ( '".$schedule_id."', '".$user_arr[0]->userid."','','', '','".$parent->current_user_id."', '".NOW."', '".NOW."')"; 
                    $parent->executeQuery($insert_train_qry);
					
					//SEND NOTIFICATION 
					$nobj=new stdClass();
					$notificationtext="New Training scheduled  - `".$schedule_arr[0]->schedule_name."` from  date : ".date('d M Y',strtotime($schedule_arr[0]->start_date))." - ".date('d M Y',strtotime($shedule_arr[0]->end_date));   
					$nobj->notificationtitle=$schedule_arr[0]->schedule_name;
					$nobj->notificationtext=$notificationtext;
					$nobj->notificationtype='5';
					$nobj->notificationdata=new stdClass(); 
					// projectfunc::sendUserNotification($parent,$nobj,$user_arr[0]->userid);
					
                    
                    $train_assess_str ="SELECT * FROM ".TABLE_ASSESSMENT." WHERE  schedule_id='".$schedule_id."' AND atype='1' LIMIT 1 ";
                    $train_assess_arr=$parent->getQueryValue($train_assess_str);
                    
                    if(count($train_assess_arr)>0)
                    {
                        //ASSESSMENT QUESTION
                        $train_assess_qry= "INSERT INTO ".TABLE_TRAINING_ASSESSMENT ." ( `assessmentid`, `schedule_id`, `userid`, `is_attended`) VALUES ('".$train_assess_arr[0]->assessmentid."', '".$schedule_id."', '".$user_arr[0]->userid."','')";
                        $parent->executeQuery($train_assess_qry);
                    }        
                    
                    //PARTICIPANT
                    $participant_str = "SELECT p.`userid`, p.`is_attendance`,p.remarks, p.`score`, p.`assessment_score`,u.smpin,CONCAT(fname,lname)as name,d.dealer_name,p.creatorid FROM ".TABLE_TRAINING_PARTICIPANT."  p JOIN ".TABLE_USER." u ON p.userid=u.userid JOIN ".DMS_DEALER." d ON d.dealer_code=u.dealer_code WHERE p.schedule_id='".$schedule_id."' AND u.userid='".$user_arr[0]->userid."' ";
                    $participant_arr=$parent->getQueryValue($participant_str);
                    
                    if(count($participant_arr)>0)
                    { 
                        foreach($participant_arr as $skey=>$res_part)
                        {
                            $assessment_str = "SELECT ta.assessmentid,ta.schedule_id FROM ".TABLE_TRAINING_ASSESSMENT." as ta JOIN ".TABLE_ASSESSMENT_USER." as au ON ta.assessmentid=au.assessmentid AND ta.userid=au.userid WHERE ta.schedule_id='".$schedule_id."' AND ta.userid='".$res_part->userid."' LIMIT 1";
                            $assessment_arr=$parent->getQueryValue($assessment_str);
                            
                            $participant_arr[$skey]->is_edit="1";
                            $participant_arr[$skey]->is_delete=(count($assessment_arr)>0)?"0":"1";
                            $participant_arr[$skey]->is_created=($res_part->creatorid==$parent->current_user_id)?"1":"0";
                        }
                        
                    }
					//LOG        
					$logstr='PARTICIPANT ADD';			 
					globalfunc::insertUserLog($parent,$logstr,$schedule_id);	
                    $parent->response(array('response'=>'success', 'data'=>$participant_arr, 'message'=>$this->page_data['success1']),200);                           
                }
            }else
            {
               $parent->response(array('response'=>'failed','message'=>$this->page_data["error5"]),406); 
            }
        }else{
            $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
        }
        
        $parent->response(array('response'=>'success', 'data'=>$data_arr, 'message'=>$this->page_data['success1']),200);    
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
     /* /////////////////////////////// REMOVE PARTICIPANT //////////////////////////////////////////////// */
	private function removeparticipant($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));		 
		globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
       
        //FIELDS VALIDATION
        $REQUEST_KEYS=array('schedule_id'=>'integer','userid'=>'integer');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        
        $schedule_id= escape_str($parent->_request["schedule_id"]);
        $userid= escape_str($parent->_request["userid"]);
        
        $schedule_str = "SELECT * FROM ".TABLE_TRAINING_SCHEDULE." WHERE trainer_id='".$parent->current_user_id."' AND schedule_id='".$schedule_id."' LIMIT 1";
        $schedule_arr=$parent->getQueryValue($schedule_str);
                        
        $user_id_arr=array();
        if(count($schedule_arr)>0)
        { 
            $train_parti_str ="SELECT * FROM ".TABLE_TRAINING_PARTICIPANT." WHERE  schedule_id='".$schedule_id."' AND 	userid='".$userid."' LIMIT 1 ";
            $train_parti_arr=$parent->getQueryValue($train_parti_str);
            
            if(count($train_parti_arr)>0)                
            { 
                $assess_user_str = "SELECT au.* FROM ".TABLE_ASSESSMENT_USER." as au JOIN ".TABLE_TRAINING_ASSESSMENT." as ta ON ta.assessmentid=au.assessmentid AND au.userid=ta.userid  WHERE ta.schedule_id='".$schedule_id."' AND au.userid='".$userid."' LIMIT 1 "; 
                $assess_user_arr=$parent->getQueryValue($assess_user_str);
               // $is_edit=(count($assess_arr)>0)?"0":"1";
                if(count($assess_user_arr)>0)
                {
                    $parent->response(array('response'=>'failed','message'=>$this->page_data["error6"]),406); 
                }else
                {
                    $delete_parti_qry= "DELETE FROM  ".TABLE_TRAINING_PARTICIPANT ."  WHERE `schedule_id`='".$schedule_id."' AND userid='".$userid."'";
                    $parent->executeQuery($delete_parti_qry);
                    
                    $delete_assess_qry= "DELETE FROM  ".TABLE_TRAINING_ASSESSMENT ."  WHERE `schedule_id`='".$schedule_id."' AND userid='".$userid."'";
                    $parent->executeQuery($delete_assess_qry);
                    
                    //LOG        
					$logstr='PARTICIPANT REMOVE';			 
					globalfunc::insertUserLog($parent,$logstr,$schedule_id);
                    $parent->response(array('response'=>'success',  'message'=>$this->page_data['success1']),200);    
                } 
            }else
            {
               $parent->response(array('response'=>'failed','message'=>$this->page_data["error5"]),406); 
            }
        }else{
            $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
        }
        
        $parent->response(array('response'=>'success', 'data'=>$data_arr, 'message'=>$this->page_data['success1']),200);    
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// BATCH //////////////////////////////////////////////// */
	private function batch($parent)
	{  
        globalfunc::checkMethodType($parent,array('GET','POST','DELETE'));	
        globalfunc::checkAuthrozation($parent,array('type'=>'user')); 
        switch ($parent->get_request_method())
        {
            case "GET": //LIST
                if(count($parent->params)==1) //LIST DATA
                {

                    globalfunc::checkParamCount($parent,1);
                    $userid=$parent->current_user_id;
                    $role=$parent->current_user_role;
                    
                    if(strstr($parent->params[0],"page="))
                    {                    
                        //PAGINATION SETTINGS
                        $limit_cond='';
                        $data_arr=array();  
                        $limit_str=globalfunc::setPageLimit($parent,$parent->params[0]);
                        $limit_cond=($limit_str)?" LIMIT ".$limit_str:'';
                    }else
                    {
                        $parent->current_page=0;
                    }
                    $get_list_arr=$parent->selectQuery(TABLE_TRAINERBATCH."" ,"SQL_CALC_FOUND_ROWS * ","trainerid='".$userid."' ORDER BY id ASC ".$limit_cond,"");

                    $tot = $parent->getQueryValue("select FOUND_ROWS() as total_records");
                    $total=(count($tot)>0)?$tot[0]->total_records:0;
                    $data_arr=($get_list_arr['nr']>0)?$get_list_arr['result']:array();    
                    $last_page=($total && strstr($parent->params[0],"page="))?ceil($total/$parent->current_limit)-1:0;
                    
                    //LOG        
                    $logstr='BATCH LIST DATA';			 
                    globalfunc::insertUserLog($parent,$logstr);
                    $parent->response(array('response'=>'success', 'data'=>$data_arr,'total'=>$total,'last_page'=>$last_page,'current_page'=>$parent->current_page,'message'=>$this->page_data['success1']),200);
                }else if(count($parent->params)==2)
                {
                    
                    $batchid= escape_str($parent->params[1]); 
                    $check_str = "SELECT * FROM ".TABLE_TRAINERBATCH."  WHERE  batchid='".$batchid."'";  
                    $batch_arr=$parent->getQueryValue($check_str);
                    if(!count($data_arr)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error8"]),406);
            
                    $user_str = "SELECT b.smpin,u.fname,u.lname,u.dealer_code,d.dealer_name FROM ".TABLE_TRAINERBATCHUSER." b  JOIN ".TABLE_USER." u ON u.smpin=b.smpin JOIN ".DMS_DEALER." d ON d.dealer_code=u.dealer_code WHERE u.role>7 AND u.role<14 AND b.batchid='".$batchid."' GROUP BY b.smpin ORDER BY u.smpin ASC,u.userid ASC";  
                    $user_arr=$parent->getQueryValue($user_str); 

                    $data_arr=array('batch'=>$batch_arr[0],'user'=>$user_arr);
            
                    //LOG        
                    $logstr='BATCH SINGLE DATA';			 
                    globalfunc::insertUserLog($parent,$logstr);
                    $parent->response(array('response'=>'success', 'data'=>$data_arr,'message'=>$this->page_data['success1']),200);
                }
                break;
            case "POST": //ADD
                if(count($parent->params)==1)
                {
                    $REQUEST_KEYS=array('title'=>'string', 'smpin'=>'string');
                    globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
                  
                    $title=escape_str($parent->_request["title"]);
                    $smpin_json=escape_str($parent->_request["smpin"]);
                    $smpin_arr=json_encode($smpin_json);
                    if(!count($smpin_arr)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error7"]),406);
            
                    $insert_str= "INSERT INTO ".TABLE_TRAINERBATCH ." (`trainerid`, `title`, `created_on`) VALUES ('".$parent->current_user_id."','".$title."','".NOW."')";
                    $parent->executeQuery($insert_str);
                    $id=$parent->lastInsertId();
                    
                    $ins_arr=array();
                    foreach($smpin_arr as $smpin)
                    {
                        $ins_arr[]="('".$id."', '".$smpin."', '".NOW."')";
                    }

                    $insert_user= "INSERT INTO ".TABLE_TRAINERBATCHUSER ." (`batchid`, `smpin`, `created_on`) VALUES ".@implode(",".$ins_arr);
                    $parent->executeQuery($insert_user);
                    //LOG        
                    $logstr='BATCH INSERT';			 
                    globalfunc::insertUserLog($parent,$logstr);
                    $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
                }else if(count($parent->params)==2)//EDIT
                {
                    
                    $editid= escape_str($parent->params[1]); 
                    $REQUEST_KEYS=array('title'=>'string', 'smpin'=>'string');
                    globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
                  
                    $title=escape_str($parent->_request["title"]);
                    $smpin_json=escape_str($parent->_request["smpin"]);
                    $smpin_arr=json_encode($smpin_json);
                    if(!count($smpin_arr)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error7"]),406);                     
                    $parent->executeQuery("UPDATE ".TABLE_TRAINERBATCH." SET  `title`='".$title."' WHERE id='".$editid."'");
                    
                    $parent->executeQuery("DELETE FROM ".TABLE_TRAINERBATCHUSER."   WHERE batchid='".$editid."'");
                    
                    $ins_arr=array();
                    foreach($smpin_arr as $smpin)
                    {
                        $ins_arr[]="('".$editid."', '".$smpin."', '".NOW."')";
                    }

                    $insert_user= "INSERT INTO ".TABLE_TRAINERBATCHUSER ." (`batchid`, `smpin`, `created_on`) VALUES ".@implode(",".$ins_arr);
                    $parent->executeQuery($insert_user);
                    
                    //LOG        
                    $logstr='BATCH EDIT';			 
                    globalfunc::insertUserLog($parent,$logstr);
                    $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
                }
                break;
            case "DELETE"://DELETE
                globalfunc::checkParamCount($parent,2);
                $del_id= escape_str($parent->params[1]); 
                
                $delete_parti_qry= "DELETE FROM  ".TABLE_TRAINERBATCH ."  WHERE `id`='".$del_id."'";
                $parent->executeQuery($delete_parti_qry);

                $delete_assess_qry= "DELETE FROM  ".TABLE_TRAINERBATCHUSER ."  WHERE `batchid`='".$del_id."'";
                $parent->executeQuery($delete_assess_qry);
            
                //LOG        
                $logstr='BATCH DELETE';			 
                globalfunc::insertUserLog($parent,$logstr);
                $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
                break;
        }
                
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// NEW TRAINING SUBMIT //////////////////////////////////////////////// */
	private function newtraining($parent)
	{               
		globalfunc::checkMethodType($parent,array('POST'));		 
		globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        projectfunc::authorizedRole($parent,array('5'));
        
        
         //FIELDS VALIDATION
        $REQUEST_KEYS=array('schedule_name'=>'string','lvl_id'=>'integer');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        
        $title=escape_str($parent->_request["schedule_name"]);
        $lvl_id=escape_str($parent->_request["lvl_id"]);
        $startdate=escape_str($parent->_request["startdate"]);
        $enddate=escape_str($parent->_request["enddate"]);
        
        $starttime=escape_str($parent->_request["starttime"]);
        $endtime=escape_str($parent->_request["endtime"]);
        if($starttime!='' && $endtime!='')
        {
            $startdate.=" ".$starttime;
            $enddate.=" ".$endtime;
        }else
        {
            $startdate.=" 00:00:00";
            $enddate.=" 23:59:59";
        } 
        
        $trainer_id=$parent->current_user_id;
        $filter_region='';
        $filter_dealer='';
        $travel_desc=escape_str($parent->_request["travel_desc"]);
        $hotel_desc=escape_str($parent->_request["hotel_desc"]);
        $assessment_type=escape_str($parent->_request["assessment_type"]); //0-Before,1-After,2 Both
        $assessmentname=escape_str($parent->_request["assessmentname"]);
        if(!in_array($assessment_type, array('0','1','2')))  $parent->response(array('response'=>'failed','message'=>$this->page_data["error8"]),406);  

        $randomcond=escape_str($parent->_request["randomcond"]);
        $assessmenttime=escape_str($parent->_request["assessmenttime"]);
        $user_type=escape_str($parent->_request["user_type"]);
        $ques_count=escape_str($parent->_request["ques_count"]);
        //$buffer_day=escape_str($parent->_request["buffer_day"]);
        $buffer_day='1';
        $location='';
        $participant_json=$parent->_request["participant"];
        $participant_arr=json_decode($participant_json);
        $is_feedback=$parent->_request["is_feedback"];
        
        if(!(is_array($participant_arr) && count($participant_arr)>0))  $parent->response(array('response'=>'failed','message'=>$this->page_data["error5"]),406);  
        if(!(is_numeric($ques_count)&& $ques_count>0))  $parent->response(array('response'=>'failed','message'=>$this->page_data["error9"]),406); 
        //CHECK QUESTION COUNT EXIST
        $ques_count_valid='0';
        $q_count=0;
        $assess_str = "SELECT COUNT(id) as ques_count FROM ".TABLE_QUESTION." WHERE status='1' AND cateid='".$lvl_id."' LIMIT 1"; 
        $assess_arr=$parent->getQueryValue($assess_str); 
        if(count($assess_arr)>0)
        {
            $ques_count_valid=($ques_count<=$assess_arr[0]->ques_count)?'1':'0';
            $q_count=$assess_arr[0]->ques_count;
        }    
        if($ques_count_valid=='0')  $parent->response(array('response'=>'failed','message'=>'Add Question\'s in Question Bank for selected Category. Total Question for selected Category : '.$q_count),406);   
        
        $insert_qry = "INSERT INTO ".TABLE_TRAINING_SCHEDULE ." ( `lvl_id`, `user_type`, `schedule_name`, `trainer_id`, `start_date`, `end_date`, `assessmentname`, `assessmenttime`, `randomcond`, `ques_count`, `location`, `assessment_type`, `buffer_day`, `filter_zone`, `filter_region`, `filter_dealer`, `travel_desc`, `hotel_desc`,is_feedback, `is_deleted`, `status`, `created_on`, `modified_on`) VALUES ( '".$lvl_id."','".$user_type."','".$schedule_name."', '".$trainer_id."','".$startdate."', '".$enddate."','".$assessmentname."','".$assessmenttime."','".$randomcond."','".$ques_count."','".$location."','".$assessment_type."','".$buffer_day."','".$filter_zone."','".$filter_region."','".$filter_dealer."','".$travel_desc."','".$hotel_desc."','0','".$is_feedback."','1','".NOW."', '".NOW."')"; 
        $parent->executeQuery($insert_qry);
        $schedule_id=$parent->lastInsertId();
        
        if(count($participant_arr)>0)
        {
            $participant_arr= array_unique($participant_arr);
            $ins_participant_arr=array();
            foreach($participant_arr as $userid)
            {
            
                $ins_participant_arr[] =" ( '".$schedule_id."', '".$userid."', '0', '0', '0', '".$trainer_id."','".NOW."', '".NOW."')"; 
            }
            //print_r($ins_participant_arr);
            $insert_qry = "INSERT INTO ".TABLE_TRAINING_PARTICIPANT ." ( `schedule_id`, `userid`, `is_attendance`, `score`, `assessment_score`, `creatorid`, `created_on`, `modified_on`) VALUES ".@implode(',',$ins_participant_arr); 
            $parent->executeQuery($insert_qry);
        }
        
        if($assessment_type!=2)
        {
            //GET ASSESSMENT START DATE
            $assessment_startdate=($assessment_type=='0')?NOW:date('Y-m-d H:i:s',strtotime($enddate));
            //GET ASSESSMENT END DATE
            $assessment_enddate=date('Y-m-d H:i:s',strtotime('+'.$buffer_day.' day',strtotime($enddate))); 
        }else
        {
            //GET ASSESSMENT START DATE
            $assessment_startdate=NOW;
            //GET ASSESSMENT END DATE
            $assessment_enddate=date('Y-m-d H:i:s',strtotime('+'.$buffer_day.' day',strtotime($enddate))); 


            //INSERT ASSESSMENT
            $insert_qry = "INSERT INTO ".TABLE_ASSESSMENT ." ( `atype`, `lvl_id`, `assessmentname`, `description`, `assessmentimage`, `assessmenttype`, `assettypeid`, `assessmenttimetype`, `assessmenttime`, `attemptslimit`, `publisheddate`, `enddate`, `randomcond`, `filter_role`, `filter_zone`, `filter_region`, `filter_dealer`, `assessmentnotification`, `total_question`,`schedule_id`, `status`, `creatorid`, `created_on`, `modified_on`) VALUES ('1','".$lvl_id."','".$assessmentname."','".$assessmentname."','','1','1','1','".$assessmenttime."','1','".$assessment_startdate."','".$assessment_enddate."','".$randomcond."','','','','','','".$ques_count."','".$schedule_id."','1','".$trainer_id."','".NOW."','".NOW."')"; 
            $parent->executeQuery($insert_qry);
            $assessmentid = $parent->lastInsertId();

            if(count($participant_arr)>0)
            {
                $ins_assess_arr=array();
                foreach($participant_arr as $userid)
                {       
                    $ins_assess_arr[] =" ( '".$assessmentid."','".$schedule_id."', '".$userid."', '0')"; 
                }
            }
            //ASSESSMENT PARTICPANT ADD
            $insert_qry = "INSERT INTO ".TABLE_TRAINING_ASSESSMENT ." ( `assessmentid`, `schedule_id`, `userid`, `is_attended`) VALUES ".@implode(',',$ins_assess_arr);
            $parent->executeQuery($insert_qry);

            //ASSESSMENT QUESTION ADD
            $rcond=($randomcond)?"ORDER BY RAND()":"ORDER BY id ASC";
            $ques_str = "SELECT *  FROM ".TABLE_QUESTION." WHERE status='1' AND cateid='".$lvl_id."' ".$rcond." LIMIT ".$ques_count; 
            $ques_arr=$parent->getQueryValue($ques_str);
            if(count($ques_arr)>0)
            {
                $ins_ques_arr=array();
                foreach($ques_arr as $res_ques)
                {
                    $ins_ques_arr[] =" ( '".$assessmentid."','".$res_ques->id."', '1', '".$trainer_id."','".NOW."', '".NOW."')"; 
                }

                //ASSESSMENT QUESTION
                $insert_qry = "INSERT INTO ".TABLE_ASSESSMENT_QUESTION ." (`assessmentid`, `qid`, `is_mandatory`, `creatorid`, `created_on`, `modified_on`) VALUES ".@implode(',',$ins_ques_arr);
                $parent->executeQuery($insert_qry);

            }
            
            //SECOND START AND END
            //GET ASSESSMENT START DATE
            $assessment_startdate=date('Y-m-d H:i:s',strtotime($enddate));
            //GET ASSESSMENT END DATE
            $assessment_enddate=date('Y-m-d H:i:s',strtotime('+'.$buffer_day.' day',strtotime($enddate))); 
            $ins_ques_arr=array();
            $ins_assess_arr=array();
            
        } 
        
        //INSERT ASSESSMENT
        $insert_qry = "INSERT INTO ".TABLE_ASSESSMENT ." ( `atype`, `lvl_id`, `assessmentname`, `description`, `assessmentimage`, `assessmenttype`, `assettypeid`, `assessmenttimetype`, `assessmenttime`, `attemptslimit`, `publisheddate`, `enddate`, `randomcond`, `filter_role`, `filter_zone`, `filter_region`, `filter_dealer`, `assessmentnotification`, `total_question`,`schedule_id`, `status`, `creatorid`, `created_on`, `modified_on`) VALUES ('1','".$lvl_id."','".$assessmentname."','".$assessmentname."','','1','1','1','".$assessmenttime."','1','".$assessment_startdate."','".$assessment_enddate."','".$randomcond."','','','','','','".$ques_count."','".$schedule_id."','1','".$trainer_id."','".NOW."','".NOW."')"; 
        $parent->executeQuery($insert_qry);
        $assessmentid = $parent->lastInsertId();

        if(count($participant_arr)>0)
        {
            $ins_assess_arr=array();
            foreach($participant_arr as $userid)
            {
                $ins_assess_arr[] =" ( '".$assessmentid."','".$schedule_id."', '".$userid."', '0')"; 
            }
        }
        //ASSESSMENT PARTICPANT ADD
        $insert_qry = "INSERT INTO ".TABLE_TRAINING_ASSESSMENT ." ( `assessmentid`, `schedule_id`, `userid`, `is_attended`) VALUES ".@implode(',',$ins_assess_arr);
        $parent->executeQuery($insert_qry);

        //ASSESSMENT QUESTION ADD
        $rcond=($randomcond)?"ORDER BY RAND()":"ORDER BY id ASC";
        $ques_str = "SELECT *  FROM ".TABLE_QUESTION." WHERE status='1' AND cateid='".$lvl_id."' ".$rcond." LIMIT ".$ques_count; 
        $ques_arr=$parent->getQueryValue($ques_str);
        if(count($ques_arr)>0)
        {
            $ins_ques_arr=array();
            foreach($ques_arr as $res_ques)
            {
                $ins_ques_arr[] =" ( '".$assessmentid."','".$res_ques->id."', '1', '".$trainer_id."','".NOW."', '".NOW."')"; 
            }

            //ASSESSMENT QUESTION
            $insert_qry = "INSERT INTO ".TABLE_ASSESSMENT_QUESTION ." (`assessmentid`, `qid`, `is_mandatory`, `creatorid`, `created_on`, `modified_on`) VALUES ".@implode(',',$ins_ques_arr);
            $parent->executeQuery($insert_qry);

        }
        $mobj=new stdClass();
        $mobj->schedule_id=$trainer_id;
        $this->trainingnotifictaion($parent,$mobj);
        
        
        //LOG        
        $logstr='TRAINING CREATE';			 
        globalfunc::insertUserLog($parent,$logstr,$schedule_id); 

        $parent->response(array('response'=>'success', 'message'=>$this->page_data['success1']),200);  
        
    }
    
    private function trainingnotifictaion($parent,$obj)
    {
        if(!(isset($obj) && isset($obj->schedule_id)))  $parent->response(array('response'=>'failed','message'=>'PHP ERROR Value not passed'),500);
        
        $schedule_id=$obj->schedule_id;
        $query_str = "SELECT * FROM ".TABLE_TRAINING_SCHEDULE." WHERE is_deleted='0' AND schedule_id='".$schedule_id."' LIMIT 1"; 
        $query_arr=$parent->getQueryValue($query_str); 
        
        $query_str = "SELECT * FROM `".TABLE_TRAINING_PARTICIPANT."` WHERE schedule_id='".$schedule_id."' "; 
        $user_arr=$parent->getQueryValue($query_str);
        if(count($query_arr)>0 && count($user_arr)>0)
        { 
            
            $ntext="New Training Scheduled  - ".$query_arr[0]->schedule_name." from  date : ".date('d M Y',strtotime($query_arr[0]->start_date))." - ".date('d M Y',strtotime($query_arr[0]->end_date));    
            
            $notificationtitle=$schedule_arr[0]->schedule_name;
            $notificationtext=$ntext;    
            $notificationtype=5;    
            $obj=new stdClass();
            $notificationdata= json_encode($obj);


            //INSERT NOTIFICATION
            $parent->executeQuery("INSERT INTO `".TABLE_NOTIFICATION."` ( `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('".escape_str($notificationtitle)."','".escape_str($notificationtext)."','".$notificationdata."','".$notificationtype."', '1','".NOW."','".NOW."','".NOW."')");
            $notificationid=$parent->lastInsertId();
            
            $data=array('notification_id'=>$notificationid,'title'=>$notificationtitle,'message'=>$notificationtext,'notificationtype'=>$notificationtype,'notificationdata'=>$notificationdata,'created_date'=>NOW);
            
            if(count($user_arr)>0)
            {
                foreach ($part_arr as $res_user)
                {
                    $user_arr[]=$res_user->userid;
                } 
                
                $ins_arr=array();
                foreach($user_arr as $res)
                {
                    $ins_arr[]=" ('".$notificationid."', '".$res."', '0', '".NOW."')";
                }
                
                $insert_chunk=array_chunk($ins_arr, 1000);
                foreach($insert_chunk as $chunk_ins)
                {
                    $parent->executeQuery("INSERT INTO ".TABLE_NOTIFICATION_USER."(`notificationid`, `userid`, `status`,  `created_on`) VALUES ".@implode(',',$chunk_ins)."  ON DUPLICATE KEY UPDATE `status` =0");
                }
                
                $usertokenarr['ios']=array();
                $usertokenarr['android']=array();

                $user_device_str = "SELECT ud.devicetype,ud.token FROM `".TABLE_USER_DEVICES."` as ud JOIN (SELECT userid FROM ".TABLE_NOTIFICATION_USER." WHERE notificationid='".$notificationid."')  as u ON ud.userid=u.userid  WHERE ud.is_deleted='0' AND (devicetype='ios' OR devicetype='android')  AND token!=''";
                $user_device_arr = $parent->getQueryValue($user_device_str);
                
                if(count($user_device_arr)>0)
                {
                    foreach($user_device_arr as $res_dev)
                    {
                        //print_r($user_device_arr);
                        if(strtolower($res_dev->devicetype)=='ios')
                        {
                            $usertokenarr['ios'][]=$res_dev->token;
                        }else if(strtolower($res_dev->devicetype)=='android')
                        {
                            $usertokenarr['android'][]=$res_dev->token;
                        }
                    }
                    // globalfunc::sendUserNotification($data,$usertokenarr);
                }
                
            }
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// PARTICIPANT SCORE //////////////////////////////////////////////// */
	private function participantscore($parent)
	{               
		globalfunc::checkMethodType($parent,array('GET','POST'));			 
		//globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        projectfunc::authorizedRole($parent,array('5'));
        switch ($parent->get_request_method())
        {
			case "GET":    
                globalfunc::checkParamCount($parent,2);
                $schedule_id=escape_str($parent->params[1]);
                
                $data_arr=array(); 
                
                $query_str = "SELECT p.participant_id,p.userid,p.score,p.remarks,p.image,u.smpin,u.fname,u.lname,u.dealer_code,d.dealer_name FROM `".TABLE_TRAINING_PARTICIPANT."` as p JOIN ".TABLE_USER." u  ON p.userid=u.userid  JOIN ".DMS_DEALER." d ON d.dealer_code=u.dealer_code WHERE p.schedule_id='".$schedule_id."' "; 
                $user_arr=$parent->getQueryValue($query_str);
                if(count($user_arr)>0)
                {
                    //CONNECT S3
					$s3=awsfileserver::connectS3();
                    foreach($user_arr as $key=>$res)
                    {
                        $user_arr[$key]->image_url=($res->image!='')?awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_TRAINING_URL.$res->image):'';   
                    }
                    $data_arr=$user_arr;
                }
                //LOG        
                $logstr='PARTICIPANT SCORE DATA LIST';			 
                globalfunc::insertUserLog($parent,$logstr);
                $parent->response(array('response'=>'success', 'data'=>$data_arr,'message'=>$this->page_data['success1']),200);
                break;
            case "POST":    
                globalfunc::checkParamCount($parent,1);
                $id=escape_str($parent->_request["id"]);
                $participant_arr=json_decode($parent->_request["participant"]);
                
                if(!(json_last_error() == JSON_ERROR_NONE && is_array($participant_arr)&& count($participant_arr)>0))  $parent->response(array('response'=>'failed','message'=>$this->page_data['error10']),406);
                
                if(count($participant_arr)>0)
                {
                    $check_arr=array();
                    $update_str=array();
                    foreach($participant_arr as $val)
                    {
                        $check_arr[]=$val->userid;
                        $val->score=(isset($val->score)&&$val->score>0)?$val->score:0;
                        $val->remarks=(isset($val->remarks)&&$val->remarks!='')?$val->remarks:'';
                        $val->is_attendance=(isset($val->is_attendance)&&$val->is_attendance!='')?$val->is_attendance:'';
                        
                        $update_str[]="UPDATE ".TABLE_TRAINING_PARTICIPANT." SET score='".$val->score."',remarks='".$val->remarks."',is_attendance='".$val->is_attendance."' WHERE schedule_id='".$schedule_id."' AND userid='".$val->userid."'";
                    }
                    //VALIDATION
                    $query_str = "SELECT * FROM `".TABLE_TRAINING_PARTICIPANT."` WHERE schedule_id='".$schedule_id."' AND userid IN (".@implode(',',$check_arr).")"; 
                    $checkparticipant_arr=$parent->getQueryValue($query_str);
                    if(!(count($participant_arr)==count($checkparticipant_arr)))  $parent->response(array('response'=>'failed','message'=>$this->page_data['error10']),406);
                    if(count($update_str)>0)
                    {
                        foreach($update_str as $qry)                            
                        {
                            $parent->executeQuery($qry);
                        }
                    }
            
                    //LOG        
                    $logstr='PARTICIPANT SCORE UPDATE';			 
                    globalfunc::insertUserLog($parent,$logstr);
                    $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
                }
                break;
            
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */   
    
    /* /////////////////////////////// TRAINING IMAGE UPLOAD //////////////////////////////////////////////// */
	private function trainingimageupload($parent)
	{               
		globalfunc::checkMethodType($parent,array('POST'));		 
		globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        projectfunc::authorizedRole($parent,array('5'));
        
        $REQUEST_KEYS=array('id'=>'number');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        $schedule_id=escape_str($parent->_request["id"]);
        //validate training    
        $query_str = "SELECT schedule_id FROM `".TABLE_TRAINING_SCHEDULE."` WHERE schedule_id='".$schedule_id."' AND trainer_id='".$parent->current_user_id."' AND is_deleted=0 LIMIT 1"; 
        $check_arr=$parent->getQueryValue($query_str);
        if(!count($check_arr)>0)  $parent->response(array('response'=>'success','message'=>$this->page_data['error1']),406);
            
		//CONNECT S3
		$s3=awsfileserver::connectS3();
		//IMAGE UPLOAD	
		$obj= new stdClass();
		$obj->filekey='file';
		$obj->size='10'; //IN MB
		$obj->type=array('jpg','jpeg','png');	
		globalfunc::validateFile($parent,$obj);			
		$obj->path="../../".S3_TRAINING_URL;
		$obj->filename= 'training_'.$schedule_id.'_'.uniqid();		 
		$fileName=globalfunc::uploadFile($parent,$obj);
		awsfileserver::checkupload($parent,$s3,S3_BUCKET,S3_TRAINING_URL.$fileName,dirname(__FILE__)."/../../../".S3_TRAINING_URL.$fileName) ;
        
        $qry="UPDATE ".TABLE_TRAINING_SCHEDULE." SET image='".$fileName."' WHERE schedule_id='".$check_arr[0]->schedule_id."'";
        $parent->executeQuery($qry); 
        
        //LOG        
        $logstr='TRAINING IMAGE UPDATE';			 
        globalfunc::insertUserLog($parent,$logstr);    
        $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */ 
    
    /* /////////////////////////////// IMAGE UPLOAD //////////////////////////////////////////////// */
	private function participantimageupload($parent)
	{               
		globalfunc::checkMethodType($parent,array('POST'));		 
		globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        projectfunc::authorizedRole($parent,array('5'));
        
        $REQUEST_KEYS=array('id'=>'number','userid'=>'number');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        $schedule_id=escape_str($parent->_request["id"]);
        $userid=escape_str($parent->_request["userid"]);
        
        //validate training
        $query_str = "SELECT * FROM `".TABLE_TRAINING_SCHEDULE."` WHERE schedule_id='".$schedule_id."' AND trainer_id='".$parent->current_user_id."' AND is_deleted=0  LIMIT 1"; 
        $check_arr=$parent->getQueryValue($query_str);
        if(!count($check_arr)>0)  $parent->response(array('response'=>'success','message'=>$this->page_data['error1']),406);
        
        //CONNECT S3
		$s3=awsfileserver::connectS3();
		//IMAGE UPLOAD	
		$obj= new stdClass();
		$obj->filekey='file';
		$obj->size='10'; //IN MB
		$obj->type=array('jpg','jpeg','png');	
		globalfunc::validateFile($parent,$obj);			
		$obj->path="../../".S3_TRAINING_URL;
		$obj->filename= 'partcipant_'.$schedule_id.'_'.$userid.'_'.uniqid();		 
		$fileName=globalfunc::uploadFile($parent,$obj);
		awsfileserver::checkupload($parent,$s3,S3_BUCKET,S3_TRAINING_URL.$fileName,dirname(__FILE__)."/../../../".S3_TRAINING_URL.$fileName) ;
        
        $qry="UPDATE ".TABLE_TRAINING_PARTICIPANT." SET image='".$fileName."' WHERE schedule_id='".$check_arr[0]->schedule_id."' AND userid='".$userid."'";
        $parent->executeQuery($qry);  
        
        //LOG        
        $logstr='TRAINING PARTCIPANT IMAGE UPDATE';			 
        globalfunc::insertUserLog($parent,$logstr);    
        $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */ 
    
}

?>