<?php
/****************************
 * File : videotraining.php
 * Author : Cygnusa
 * @2020
****************************/

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

class videotraining
{
                    
	function __construct($parent)
	{
                    
		//GET PAGE MESSAGE
		$this->page_data=globalfunc::getMessage($parent,$parent->lang,'videotraining');		 
		if(count($parent->params)==0)
		{	
            $this->videotrainingFunc($parent);			
		}else
		{
			$qry_params=explode ("?",$parent->params[0]);
			$parameter_val=strtolower($qry_params[0]);
           
            switch($parameter_val){
                case "traininglist":  
                case "amtraining": //am list    
                case "dselist":    
                case "trainingdse":      
                case "updatetime":     
                case "message":   
                case "scheduleusers":       
                    
                case "role":
                case "getroleuser": 
                case "rmlist": 
                case "amlist":     
                case "dealerlist":   
                
                case "scheduletraining"://ho schedule list
                case "addtraining"://ho schedule post    
                    
                    $this->$parameter_val($parent );
                break;

                default:
                    $this->videotrainingFunc($parent);	
                break;
            }	
		}
		$parent->response(array('response'=>'failed', 'message' => 'PAGE NOT FOUND'), 404);
	}
    
    /* /////////////////////////////// COMMON //////////////////////////////////////////////// */
	private function videotrainingFunc($parent){
          
        globalfunc::checkMethodType($parent,array('GET','POST','DELETE'));
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
		switch ($parent->get_request_method())
        {
			case "GET":
                globalfunc::checkParamCount($parent,0);
            
                //PAGINATION SETTINGS
                $limit_cond='';
                $data_arr=array();  
                $limit_str=globalfunc::setPageLimit($parent,$parent->funcparams[0]);
                $limit_cond=($limit_str)?" LIMIT ".$limit_str:'';
            
                $userid=$parent->current_user_id; 
				$role=$parent->current_user_role;
                
                if(in_array($role,array(8,9,10,11,12,13))) //DSE
                {
                    $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s JOIN ".TABLE_VIDEOSCHEDULEUSER." vu ON s.id=vu.sid JOIN ".TABLE_USER." u ON u.userid=s.organiser " ,"SQL_CALC_FOUND_ROWS s.*,CONCAT(u.fname,' ',u.lname) as organiser_name,u.emp_code"," s.status in(1,2) AND s.is_deleted=0 AND vu.userid='". $userid."'  GROUP BY s.id ORDER BY s.fromdate DESC,s.id ASC ".$limit_cond,"");
                }else
                {
                    //$organiser_name=trim($parent->current_user_data->fname." ".$parent->current_user_data->lname); 
                    //USER FILTER CONDITION APPLY            
                    $user_cond='';
                    //$get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE ,"SQL_CALC_FOUND_ROWS *,'".$organiser_name."' as organiser_name"," status in(1,2) AND is_deleted=0 AND `organiser_role`='".$role."' AND  `organiser`='".$userid."' ORDER BY fromdate DESC,id ASC ".$limit_cond,"");
                    $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s JOIN ".TABLE_VIDEOSCHEDULEUSER." vu ON s.id=vu.sid JOIN ".TABLE_USER." u ON u.userid=s.organiser " ,"SQL_CALC_FOUND_ROWS s.*,CONCAT(u.fname,' ',u.lname) as organiser_name,u.emp_code"," s.status in(1,2) AND s.is_deleted=0 AND ((vu.userid='". $userid."') OR (s.`organiser_role`='".$role."' AND s.`organiser`='".$userid."'))  GROUP BY s.id ORDER BY s.fromdate DESC,s.id ASC ".$limit_cond,"");
                }
            
                $tot = $parent->getQueryValue("select FOUND_ROWS() as total_records");
                $total=(count($tot)>0)?$tot[0]->total_records:0;
               
                
                if($get_list_arr['nr']>0 && ($role<8 || $role==14) ) //DSE
                {
                    //CONNECT S3
                    $s3=awsfileserver::connectS3();
                    foreach($get_list_arr['result'] as $key=>$res)
                    {
                        
                        //NEW STATUS CHECK                        
                        if($res->status==1 && strtotime(NOW)>strtotime($res->fromdate) && strtotime(NOW)<strtotime($res->todate))
                        {
                            $list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGTIMER  ,"*"," sid='".$res->id."' AND userid='".$res->organiser."' ORDER BY id DESC ","1");
                            if($list_arr['nr']>0)
                            {
                                $created_on=$list_arr['result'][0]->modified_on;
                                $check=date('Y-m-d H:i:s',strtotime('-300 seconds',strtotime(NOW)));
                                if(strtotime($check)>strtotime($created_on))
                                {
                                    $update_str = "UPDATE ".TABLE_VIDEOTRAININGSCHEDULE." SET status=2 WHERE id='".$res->id."'";
                                    $parent->executeQuery($update_str);
                                    $get_list_arr['result'][$key]->status="2";
                                }
                            } 
                        } 
                        
                        $get_list_arr['result'][$key]->organiser=$res->emp_code;
                        $get_list_arr['result'][$key]->userlist=array();
            
                        $query_str="SELECT u.userid,u.fname,u.lname,u.smpin,u.dealer_code,u.profile_photo,u.role,u.emp_code,CASE WHEN u.role IN (8,9,10,11,12,13) THEN d.dealer_name ELSE '' END as dealer_name,CASE WHEN u.segment=0 THEN 'Student Learner' WHEN u.segment=1 THEN 'Parents/Guardian' WHEN u.segment=2 THEN 'Instructor' END as segment_str FROM ".TABLE_VIDEOSCHEDULEUSER." vu JOIN  ".TABLE_USER." u ON vu.userid=u.userid LEFT JOIN ".DMS_DEALER." d ON u.dealer_code=d.dealer_code WHERE u.status='1' AND u.is_deleted='0' AND vu.sid='".$res->id."' ORDER BY  u.dealer_code ASC,u.fname ASC,u.userid ASC";
                        
                        $query_arr=$parent->getQueryValue($query_str); 
                        if(count($query_arr)>0)
                        {
                            foreach($query_arr as $ukey=>$user)
                            {
                                if(!in_array($user->role,array(8,9,10,11,12,13)))
                                {
                                    $query_arr[$ukey]->smpin=$user->emp_code;
                                    $query_arr[$ukey]->dealer_name='';
                                    $query_arr[$ukey]->segment_str='';  
                                } 
                                
                                if($user->profile_photo!='')
                                {
                                    $query_arr[$ukey]->profile=awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_PROFILE_IMAGE_URL.$user->profile_photo);                                             }else
                                {
                                    $query_arr[$ukey]->profile=USER_NOIMAGE_URL;
                                }
                                
                                
                                $timer_query_str="SELECT * FROM ".TABLE_VIDEOTRAININGTIMER." WHERE userid='".$user->userid."' AND sid='".$res->id."'";
                                $time_arr=$parent->getQueryValue($timer_query_str); 
                                $query_arr[$ukey]->timerlist=(count($time_arr)>0)?$time_arr:array();
            
                            }
                            $get_list_arr['result'][$key]->userlist=$query_arr;
                        }
                    }
                }
                $data_arr=($get_list_arr['nr']>0)?$get_list_arr['result']:array();
                
                
                //LOG        
                $logstr='VIDEO TRAINING LIST';			 
                globalfunc::insertUserLog($parent,$logstr);

                $last_page=($total)?ceil($total/$parent->current_limit)-1:0;
                $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);
            break;
            case "POST":
            
				globalfunc::checkParamCount($parent,0); 
                projectfunc::authorizedRole($parent,array('3','4','5','6','7','14'));
				$userid=$parent->current_user_id; 
				$role=$parent->current_user_role;
                
                $REQUEST_KEYS=array('title'=>'string', 'description'=>'string','fromdate'=>'date|Y-m-d H:i:s','todate'=>'date|Y-m-d H:i:s','channel'=>'string','dse'=>'string');
				globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
                
                $title=escape_str($parent->_request['title']);
                $description=escape_str($parent->_request['description']);
                $fromdate=escape_str($parent->_request['fromdate']);
                $todate=escape_str($parent->_request['todate']);
                $dse=$parent->_request['dse'];
                $dse=json_decode($dse); //sending as string
                $channel=escape_str($parent->_request['channel']);
                $typeid=escape_str($parent->_request['typeid']);
                //$participant_role=isset($parent->_request['participant_role'])?escape_str($parent->_request['participant_role']):10;
                
                if(strtotime($fromdate)<NOW)  $parent->response(array('response'=>'failed','message'=>$this->page_data["error4"]),406);
                if(strtotime($todate)<NOW) $parent->response(array('response'=>'failed','message'=>$this->page_data["error4"]),406);
                if(strtotime($fromdate)>strtotime($todate)) $parent->response(array('response'=>'failed','message'=>'to datetime should be greater than from datetime'),406);
        
                //UPDATED FOR APP TEAM
        		$channeltemp = explode("_",$channel);
        		$gettrname="select emp_code from tbl__user where userid='".$userid."'";
                $trname_arr=$parent->getQueryValue($gettrname);                
                $channel = $trname_arr[0]->emp_code."_".$channeltemp[1]."_".$channeltemp[2];
                
                if(!(is_array($dse) && count($dse)>0)) $parent->response(array('response'=>'failed','message'=>$this->page_data["error2"]),406);
                
				//INSERT 				
                $insert_str = "INSERT INTO ".TABLE_VIDEOTRAININGSCHEDULE."(typeid, `title`, `description`, `fromdate`, `todate`,channel, `status`, `organiser_role`, `organiser`, `created_on`, `modified_on`) VALUES ('".$typeid."','".$title."','".$description."','".$fromdate."','".$todate."','".$channel."','1','".$role."','".$userid."','".NOW."','".NOW."')";
                $parent->executeQuery($insert_str);               
                $trainingid=$parent->lastInsertId();
                
                //INSERT INTO `tbl__videoscheduleuser`(`id`, `sid`, `userid`, `status`, `created_on`, `modified_on`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6])
                foreach($dse as $userid)
                {
                    $ins_arr[]="('".$trainingid."', '".$userid."', 1,'".NOW."','".NOW."')";
                }
                $insert_str = "INSERT INTO ".TABLE_VIDEOSCHEDULEUSER." ( `sid`, `userid`, `status`, `created_on`, `modified_on`) VALUES ".@implode(",", $ins_arr);
                $parent->executeQuery($insert_str);                
                $this->notificationtriggervideotraining($parent,$trainingid);
            
                //LOG        
                $logstr='VIDEO TRAINING SUBMIT';			 
                globalfunc::insertUserLog($parent,$logstr);
                
                $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
            break;
            case "DELETE":
                globalfunc::checkParamCount($parent,1);
                projectfunc::authorizedRole($parent,array('3','4','5','6','7','14'));
            
				$userid=$parent->current_user_id; 
				$role=$parent->current_user_role;
                $deleteid= escape_str($parent->params[0]);  
                
                $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE ,"id"," (( `organiser_role`='".$role."'  AND  `organiser`='".$userid."') OR creator_id='".$userid."')  AND is_deleted=0 and id='".$deleteid."'","1");
                if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
                
                $parent->executeQuery("UPDATE ".TABLE_VIDEOTRAININGSCHEDULE." SET is_deleted=1 WHERE id='".$get_list_arr['result'][0]->id."'");
                
                //TRIGGER NOTIFICATION
                $extobj=new stdClass(); 
                $extobj->type='delete';
                $this->notificationtriggervideotraining($parent,$deleteid,$extobj);
                
                //LOG        
                $logstr='VIDEO TRAINING DELETE';			 
                globalfunc::insertUserLog($parent,$logstr);
                
                $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
            break;    
        }
	}
	/* //////////////////////////////////////////////////////////////////////////////////////////// */
      
    /* /////////////////////////////// USERLIST //////////////////////////////////////////////// */
	private function dselist($parent)  //NOT USING
	{               
		globalfunc::checkMethodType($parent,array('GET'));		 
		globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        projectfunc::authorizedRole($parent,array('3','4','5','6','7','14'));
        
        $userid=$parent->current_user_id; 
        $role=$parent->current_user_role;
            
        switch($parent->current_user_role)
        {
            case '3'://ho
                $usercond='';
                break;
            case '4':
                $usercond=" AND d.zm_email='".$parent->current_user_data->emailid."'";
                break;
            case '5':
                $get_trainer_str = "SELECT zone FROM ".DMS_HOUSER."  WHERE emp_code='".$parent->current_user_data->emp_code."' LIMIT 1";
                $trainer_arr=$parent->getQueryValue($get_trainer_str);
                $zone_cond.=(count($trainer_arr)>0)?"zone='".$trainer_arr[0]->zone."'":"zone='0'";
                
                $usercond=" AND d.".$zone_cond;
                break;
            case '6':
                $usercond=" AND d.rm_email='".$parent->current_user_data->emailid."'";
                break;
            case '7':
                $usercond=" AND d.am_email='".$parent->current_user_data->emailid."'";
                break; 
        }
        $usercond.=' AND d.status=1 AND d.is_deleted=0';    
        $filter_arr=globalfunc::getFilterValues($parent,$parent->params[0]);  
        //segment
        if(isset($filter_arr['segment']) && $filter_arr['segment']!='')
        {
            $usercond.=" AND u.segment='".escape_str($filter_arr['segment'])."' ";
        }
        
        
        //GET DATA
        $query_str="SELECT u.userid,u.fname,u.lname,u.smpin,u.dealer_code,d.dealer_name,u.segment,CASE WHEN u.segment=0 THEN 'Student Learner' WHEN u.segment=1 THEN 'Parents/Guardian' WHEN u.segment=2 THEN 'Instructor' END as segment_str FROM ".TABLE_USER." u LEFT JOIN ".DMS_EMPLOYEE." e ON u.smpin=e.smpin LEFT JOIN ".DMS_DEALER." d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 ".$usercond." ORDER BY  u.dealer_code ASC,u.fname ASC,u.userid ASC";
        $query_arr=$parent->getQueryValue($query_str);   
        
        $data_arr=(count($query_arr)>0)?$query_arr:array();
                    
        //LOG 
        $logstr='VIDEO TRAINING TRAINER DSE LIST';			 
        globalfunc::insertUserLog($parent,$logstr);       
        $parent->response(array('response'=>'success', 'data'=>$data_arr,'message'=>$this->page_data['success1']),200);  
        
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// TRAINING DSE //////////////////////////////////////////////// */
	private function trainingdse($parent)
	{               
		globalfunc::checkMethodType($parent,array('GET'));		 
		globalfunc::checkParamCount($parent,2);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        projectfunc::authorizedRole($parent,array('3','4','5','6','7','14'));
        
        $id= escape_str($parent->params[1]); 
        
        $userid=$parent->current_user_id; 
        $role=$parent->current_user_role;
            
        $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE ,"id,participant_role"," status='1' AND `organiser_role`='".$role."' AND  `organiser`='".$userid."' AND is_deleted=0 AND id='".$id."'","1");
        if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
           
            
        $query_str="SELECT u.userid,u.fname,u.lname,u.smpin,u.dealer_code,u.profile_photo,u.role,u.emp_code,CASE WHEN u.role IN (8,9,10,11,12,13) THEN d.dealer_name ELSE '' END as dealer_name,CASE WHEN u.segment=0 THEN 'Student Learner' WHEN u.segment=1 THEN 'Parents/Guardian' WHEN u.segment=2 THEN 'Instructor' END as segment_str FROM ".TABLE_VIDEOSCHEDULEUSER." vu JOIN  ".TABLE_USER." u ON vu.userid=u.userid LEFT JOIN ".DMS_DEALER." d ON u.dealer_code=d.dealer_code WHERE u.status='1' AND u.is_deleted='0' AND vu.sid='".$id."' ORDER BY  u.dealer_code ASC,u.fname ASC,u.userid ASC";
        //LEFT JOIN ".DMS_EMPLOYEE." e ON u.smpin=e.smpin LEFT JOIN ".DMS_DEALER." d ON u.dealer_code=d.dealer_code  
        //,d.dealer_name,u.segment,CASE WHEN u.segment=0 THEN 'Student Learner' WHEN u.segment=1 THEN 'Parents/Guardian' WHEN u.segment=2 THEN 'Instructor' END as segment_str
        $query_arr=$parent->getQueryValue($query_str);  
        if(count($query_arr)>0)
        {
            //CONNECT S3
            $s3=awsfileserver::connectS3();
                
            foreach($query_arr as $ukey=>$user)
            {
                if(!in_array($user->role,array(8,9,10,11,12,13)))
                {
                    $query_arr[$ukey]->smpin=$user->emp_code;
                    $query_arr[$ukey]->dealer_name='';
                    $query_arr[$ukey]->segment_str='';  
                } 
                
                if($user->profile_photo!='')
                {
                    $query_arr[$ukey]->profile=awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_PROFILE_IMAGE_URL.$user->profile_photo);                                             }else
                {
                    $query_arr[$ukey]->profile=USER_NOIMAGE_URL;
                } 
                $timer_query_str="SELECT * FROM ".TABLE_VIDEOTRAININGTIMER." WHERE userid='".$user->userid."' AND sid='".$id."'";
                $time_arr=$parent->getQueryValue($timer_query_str); 
                $query_arr[$ukey]->timerlist=(count($time_arr)>0)?$time_arr:array();

            }
        }
        $data_arr=(count($query_arr)>0)?$query_arr:array();
        
        //LOG 
        $logstr='VIDEO TRAINING DSE LIST';			 
        globalfunc::insertUserLog($parent,$logstr);       
        $parent->response(array('response'=>'success', 'data'=>$data_arr,'message'=>$this->page_data['success1']),200);  
        
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// TRAINING LIST //////////////////////////////////////////////// */
	private function traininglist($parent)
	{  
        globalfunc::checkMethodType($parent,array('GET'));
        globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        
        //$arr=array(["id"=>"base","title"=>"Base"],["id"=>"bronze","title"=>"Bronze"],["id"=>"silverlevel1","title"=>"Silver level 1"],["id"=>"silverlevel2","title"=>"Silver level 2"],["id"=>"goldlevel1","title"=>"Gold level 1"],["id"=>"goldlevel2","title"=>"Gold level 2"]);
        
        $training_str = "SELECT type_id as id,title FROM ".TABLE_VIDEOTRAININGTITLE." ORDER BY id ASC";
        $trainer_arr=$parent->getQueryValue($training_str);
        $arr=(count($trainer_arr)>0)?$trainer_arr:array();
        
        //LOG 
        $logstr='VIDEO TRAINING TYPE LIST';			 
        globalfunc::insertUserLog($parent,$logstr); 
        $parent->response(array('response'=>'success', 'data'=>$arr,'message'=>$this->page_data['success1']),200);  
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// UPDATE TIME //////////////////////////////////////////////// */
	private function updatetime($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));
        globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        
            
        $REQUEST_KEYS=array('timetaken'=>'number','sid'=>'number','fromtime'=>'date|Y-m-d H:i:s','totime'=>'date|Y-m-d H:i:s');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
         
        $sid=escape_str($parent->_request['sid']);
        $timetaken=escape_str($parent->_request['timetaken']);
        
        $userid=$parent->current_user_id; 
        $role=$parent->current_user_role;
        
        $fromtime=escape_str($parent->_request['fromtime']);
        $totime=escape_str($parent->_request['totime']);
        $id=escape_str($parent->_request['id']);    
        
        $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s JOIN ".TABLE_VIDEOSCHEDULEUSER." u ON s.id=u.sid" ,"s.id,s.organiser,s.fromdate"," s.status IN (1,2) AND s.is_deleted=0 AND s.id='".$sid."' AND (s.`organiser`='".$userid."' OR u.userid='".$userid."')","1");
        if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
        
        
//        $check_arr=$parent->selectQuery(TABLE_VIDEOTRAININGTIMER,"id","sid='".$sid."' AND userid='".$userid."'","1");
//        if($check_arr['nr']>0)
//        {
//            $update_str="UPDATE ".TABLE_VIDEOTRAININGTIMER." SET `timetaken`='".$timetaken."' WHERE id='".$check_arr['result'][0]->id."'";
//            $parent->executeQuery($update_str);             
//        }else
//        {
//            $insert_str = "INSERT INTO ".TABLE_VIDEOTRAININGTIMER."(  `sid`, `userid`, `role`, `timetaken`, `created_on`) VALUES ('".$sid."','".$userid."','".$role."','".$timetaken."','".NOW."')";
//            $parent->executeQuery($insert_str);  
//        }
        if($id!='')
        {
            $update_str = "UPDATE ".TABLE_VIDEOTRAININGTIMER." SET `timetaken`='".$timetaken."',`totime`='".$totime."',modified_on='".NOW."' WHERE id='".$id."'";
            $parent->executeQuery($update_str);
        }else
        {
            
            $insert_str = "INSERT INTO ".TABLE_VIDEOTRAININGTIMER."(  `sid`, `userid`, `role`, `timetaken`,`fromtime`, `totime`, `created_on`,modified_on) VALUES ('".$sid."','".$userid."','".$role."','".$timetaken."','".$fromtime."','".$totime."','".NOW."','".NOW."')";
            $parent->executeQuery($insert_str);
            $id=$parent->lastInsertId();
        }
        
        //time check
       
        $list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGTIMER  ,"*","  sid='".$sid."' AND userid='".$get_list_arr['result'][0]->organiser."' ORDER BY id DESC ","1");
        if($list_arr['nr']>0)
        {
            $created_on=$list_arr['result'][0]->modified_on;
            $check=date('Y-m-d H:i:s',strtotime('-300 seconds',strtotime(NOW)));
            if(strtotime($check)>strtotime($created_on))
            {
                $update_str = "UPDATE ".TABLE_VIDEOTRAININGSCHEDULE." SET status=2 WHERE id='".$sid."'";
                $parent->executeQuery($update_str);
                $parent->response(array('response'=>'failed','data'=>$id, 'message'=>'failed'),200);  
            }
        } 
        
        //LOG        
        $logstr='VIDEO TRAINING TIMER UPDATE';			 
        globalfunc::insertUserLog($parent,$logstr);
            
        $parent->response(array('response'=>'success','data'=>$id, 'message'=>$this->page_data['success1']),200);  
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
            
    /* /////////////////////////////// MESSAGE //////////////////////////////////////////////// */
	private function message($parent)
    {
          
        globalfunc::checkMethodType($parent,array('GET','POST','DELETE'));	
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
		switch ($parent->get_request_method())
        {
			case "GET":
                
                globalfunc::checkParamCount($parent,2);
                $userid=$parent->current_user_id; 
				$role=$parent->current_user_role;
                
                //PAGINATION SETTINGS
                $limit_cond='';
                $data_arr=array();  
//                $limit_str=globalfunc::setPageLimit($parent,$parent->params[1]);
//                $limit_cond=($limit_str)?" LIMIT ".$limit_str:'';
            
                $sid_str= escape_str($parent->params[1]);  
                $sid_arr=@explode('?', $sid_str);
                $sid=escape_str($sid_arr[0]);
                //VALIDATION
                $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s JOIN ".TABLE_VIDEOSCHEDULEUSER." u ON s.id=u.sid" ,"s.id,s.organiser"," s.status='1' AND s.is_deleted=0 AND s.id='".$sid."' AND (s.`organiser`='".$userid."' OR u.userid='".$userid."')","1");
                if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
            
               
                $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGMSG." m JOIN ".TABLE_USER." u ON m.userid=u.userid" ,"SQL_CALC_FOUND_ROWS m.`sid`, m. `userid`,  m.`role`,  m.`msg` as message ,  m.`created_on` ,u.smpin,u.emp_code,CONCAT(u.fname,u.lname) as name,u.role,u.profile_photo"," m.sid='".$sid."' GROUP BY m.id  ORDER BY m.id ASC  ".$limit_cond,"");
            
                $tot = $parent->getQueryValue("select FOUND_ROWS() as total_records");
                $total=(count($tot)>0)?$tot[0]->total_records:0;
                
                if($get_list_arr['nr']>0)
                {
                    //CONNECT S3
                    $s3=awsfileserver::connectS3();
                    foreach($get_list_arr['result'] as $key=>$res)
                    {
                        $get_list_arr['result'][$key]->id=($res->role<=7)?$res->emp_code:$res->smpin;
                        if($res->profile_photo!='')
                        {
                            $get_list_arr['result'][$key]->profile=awsfileserver::getS3FileUrl($s3,S3_BUCKET,S3_PROFILE_IMAGE_URL.$res->profile_photo);                                  }else
                        {
                            $get_list_arr['result'][$key]->profile=USER_NOIMAGE_URL;
                        }
                    }
                }
                $data_arr=($get_list_arr['nr']>0)?$get_list_arr['result']:array();
            
                //LOG        
                $logstr='VIDEO TRAINING MSG LIST';			 
                globalfunc::insertUserLog($parent,$logstr); 
                
                $parent->response(array('response'=>'success', 'data'=>$data_arr ,'message'=>$this->page_data['success1']),200);
            break;
            
            case "POST": //INSERT
                globalfunc::checkParamCount($parent,1);
               
                $REQUEST_KEYS=array('sid'=>'number','msg'=>'string');
                globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
                $sid=escape_str($parent->_request['sid']); 
                $msg=escape_str($parent->_request['msg']); 
                $userid=$parent->current_user_id; 
                $role=$parent->current_user_role;
                //VALIDATION
                $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s JOIN ".TABLE_VIDEOSCHEDULEUSER." u ON s.id=u.sid" ,"s.id"," s.status='1' AND s.is_deleted=0 AND s.id='".$sid."' AND (s.`organiser`='".$userid."' OR u.userid='".$userid."')","1");
                if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
                
                $insert_msg= "INSERT INTO ".TABLE_VIDEOTRAININGMSG ." (`sid`, `userid`, `role`, `msg`, `created_on`) VALUES ('".$sid."','".$userid."','".$role."','".$msg."','".NOW."')";
                $parent->executeQuery($insert_msg);
                
                //LOG        
                $logstr='VIDEO TRAINING MSG INSERT';			 
                globalfunc::insertUserLog($parent,$logstr);
                
                $parent->response(array('response'=>'success', 'message'=>$this->page_data['success1']),200);  
            break;
            case "DELETE"://DELETE
                globalfunc::checkParamCount($parent,2);
                $deleteid= escape_str($parent->params[1]); 
                $userid=$parent->current_user_id; 
                $role=$parent->current_user_role;
                
                 //VALIDATION
                $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s JOIN ".TABLE_VIDEOSCHEDULEUSER." u ON s.id=u.sid" ,"s.id"," s.status='1' AND s.is_deleted=0 AND s.id='".$sid."' AND (s.`organiser`='".$userid."' OR u.userid='".$userid."')","1");
                if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
                
                $delete_msg= "DELETE FROM  ".TABLE_VIDEOTRAININGMSG ." WHERE id='".$deleteid."'";
                $parent->executeQuery($delete_msg);
            
                
                //LOG        
                $logstr='VIDEO TRAINING MSG DELETE';			 
                globalfunc::insertUserLog($parent,$logstr);
                $parent->response(array('response'=>'success', 'message'=>$this->page_data['success1']),200);  
            break;
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// NOTIFICATION TRIGGER //////////////////////////////////////////////// */
    private function notificationtriggervideotraining($parent,$trainingid,$extobj=NULL)
    {
        $schedule_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE ,"*","id='".$trainingid."'","1");
        
        if($extobj!=NULL)
        {
            if(isset($extobj->userid)&& is_array($extobj->userid))
            {                
                $excond=" AND u.userid IN(".implode(',',$extobj->userid).")";
            }
        }
        $ntype=($extobj!=NULL && isset($extobj->type))?$extobj->type:"";
        
        if($ntype=='removed')
        {
            $get_list_arr=$parent->selectQuery(TABLE_USER." u " ,"u.userid "," u.is_deleted=0 ".$excond."  ORDER BY u.userid ","");
        }else
        {
            $get_list_arr=$parent->selectQuery("(SELECT * FROM ".TABLE_VIDEOSCHEDULEUSER." WHERE sid='".$trainingid."' )sv JOIN ".TABLE_USER." u ON sv.userid=u.userid   " ,"u.userid "," u.is_deleted=0 ".$excond."  ORDER BY u.userid ","");
        }
        if($schedule_arr['nr']>0 && $get_list_arr['nr']>0)
        {
            
            if($schedule_arr['nr']>0)
            {                
                $obj=new stdClass();  
                $obj->id=$trainingid; 
                $notificationdata= json_encode($obj);
                $notificationtype='9';
               
                switch($ntype)
                {
                    case 'removed':
                        $notificationtitle="i-Learn - ".$schedule_arr['result'][0]->title ." cancelled for you";
                        $notificationtext="i-Learn - ".$schedule_arr['result'][0]->title." schdeuled on ".date('d-M-Y h:i A', strtotime($schedule_arr['result'][0]->fromdate))." is cancelled for you.";
                    break;   
                    case 'delete':
                        $notificationtitle="i-Learn - ".$schedule_arr['result'][0]->title ." cancelled";
                        $notificationtext="i-Learn - ".$schedule_arr['result'][0]->title." schdeuled on ".date('d-M-Y h:i A', strtotime($schedule_arr['result'][0]->fromdate))." is cancelled.";
                    break;    
                    default:
                        $notificationtitle="New i-Learn - ".$schedule_arr['result'][0]->title;
                        $notificationtext="New i-Learn - ".$schedule_arr['result'][0]->title." schdeuled on ".date('d-M-Y h:i A', strtotime($schedule_arr['result'][0]->fromdate)).".";
                    break;
                }
                $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);
                
                $ins_arr=array();
                foreach($get_list_arr['result'] as $res)
                {
                    $ins_arr[]=" ('".$notificationid."', '".$res->userid."', '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_user)
                    {
                        if(strtolower($res_user->devicetype)=='ios')
                        {
                            $usertokenarr['ios'][]=$res_user->token;
                        }else if(strtolower($res_user->devicetype)=='android')
                        {
                            $usertokenarr['android'][]=$res_user->token;
                        }
                    }

                    // globalfunc::sendUserNotification($data,$usertokenarr);
                }
            }
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// SCHEDULE USERS //////////////////////////////////////////////// */
    private function scheduleusers($parent)
    {
          
        globalfunc::checkMethodType($parent,array( 'POST','DELETE'));  
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        switch ($parent->get_request_method())
        { 
            case "POST": //INSERT
                globalfunc::checkParamCount($parent,1);
                projectfunc::authorizedRole($parent,array('3','4','5','6','7','14'));
            
                $REQUEST_KEYS=array('userid'=>'string','trainingid'=>'number');
                globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
                $userids= json_decode($parent->_request['userid']); 
                $trainingid=escape_str($parent->_request['trainingid']); 
                
               
                $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s " ,"s.id"," s.status='1' AND s.is_deleted=0 AND s.id='".$trainingid."' AND s.`organiser`='".$parent->current_user_id."' ","1");
                if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);               
                
                if(is_array($userids) && count($userids)>0)
                {
                    $ins_arr=array();
                    $uids=array();
                    foreach($userids as $userid)
                    {
                        $ins_arr[]=" ('".$trainingid."','".$userid."','1','".NOW."','".NOW."')";
                        $uids[]=$userid;
                    }
                    
                    //check already exist
                    $check_arr=$parent->selectQuery(TABLE_VIDEOSCHEDULEUSER ,"id","   sid='".$trainingid."'  AND userid IN (".@implode(",",$uids).")","1");
                    if($check_arr['nr']>0 )$parent->response(array('response'=>'failed','message'=>$this->page_data["error3"]),406);   
                    
                    
                    $insert_usr= "INSERT INTO ".TABLE_VIDEOSCHEDULEUSER ." (`sid`, `userid`, `status`, `created_on`, `modified_on`) VALUES ".@implode(',',$ins_arr);
                    $parent->executeQuery($insert_usr);
                    
                    //TRIGGER NOTIFICATION
                    $extobj=new stdClass();
                    $extobj->userid=$uids;
                    $this->notificationtriggervideotraining($parent,$trainingid,$extobj);
                }else
                {
                    $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
                    
                }
                
                //LOG        
                $logstr='VIDEO TRAINING USER INSERT';			 
                globalfunc::insertUserLog($parent,$logstr);
                
                $parent->response(array('response'=>'success', 'message'=>$this->page_data['success1']),200);  
                break;
            case "DELETE"://DELETE
                globalfunc::checkParamCount($parent,3);
                projectfunc::authorizedRole($parent,array('3','4','5','6','7','14'));
              
                $trainingid=escape_str($parent->params[1]);
                $userid= escape_str($parent->params[2]);
                
                
                $get_list_arr=$parent->selectQuery(TABLE_VIDEOTRAININGSCHEDULE." s " ,"s.id"," s.status='1' AND s.is_deleted=0 AND s.id='".$trainingid."' AND s.`organiser`='".$parent->current_user_id."' ","1");
                if(!$get_list_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error1"]),406);
                
                $delete_msg= "DELETE FROM  ".TABLE_VIDEOSCHEDULEUSER ." WHERE sid='".$trainingid."' and userid='".$userid."'";
                $parent->executeQuery($delete_msg);
                
                //TRIGGER NOTIFICATION
                $extobj=new stdClass();
                $extobj->userid=array($userid);
                $extobj->type='removed';
                $this->notificationtriggervideotraining($parent,$trainingid,$extobj);
                
                //LOG        
                $logstr='VIDEO TRAINING USER DELETE';			 
                globalfunc::insertUserLog($parent,$logstr);
                
                $parent->response(array('response'=>'success', 'message'=>$this->page_data['success1']),200);  
                break;
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// ROLE LIST //////////////////////////////////////////////// */
	private function role($parent)
	{  
        globalfunc::checkMethodType($parent,array('GET'));
        globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
            
        $role_str = "SELECT `id`, `rolename` FROM ".TABLE_ROLE." WHERE status=1 AND ( id=14 OR (id>3 AND id<8)) ORDER BY id ASC";
        $role_arr=$parent->getQueryValue($role_str);
        $arr=(count($role_arr)>0)?$role_arr:array();
        
        //LOG 
        $logstr='VIDEO TRAINING ROLE LIST';			 
        globalfunc::insertUserLog($parent,$logstr); 
        $parent->response(array('response'=>'success', 'data'=>$arr,'message'=>$this->page_data['success1']),200);  
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// ROLE USER //////////////////////////////////////////////// */
	private function getroleuser($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));
        globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
        
        $REQUEST_KEYS=array('role'=>'number' );
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        $role= escape_str($parent->_request['role']); 
        $value= escape_str($parent->_request['value']); 
        
        switch($role)
        {
            case "4"://ZM
                $query_str = "SELECT userid,emp_code,fname,lname,dealer_code, emailid as value FROM ".TABLE_USER." WHERE is_deleted=0 AND status='1' AND role='".$role."' ORDER BY fname ASC,userid ASC ";
                break;
            case "5"://TRAINER
                $query_str = "SELECT userid,emp_code,fname,lname,dealer_code,emp_code as value FROM ".TABLE_USER." WHERE is_deleted=0 AND status='1' AND role='".$role."' ORDER BY fname ASC,userid ASC ";
                break;
            case "6"://RM
                if($value!='')$cond=" AND d.zm_email='".$value."'";
                
                $query_str = "SELECT u.userid,u.emp_code,u.fname,u.lname,u.dealer_code, u.emailid as value FROM ".TABLE_USER." u JOIN ".DMS_DEALER." d ON u.emailid=d.rm_email  WHERE d.is_deleted=0 AND u.is_deleted=0 AND u.status='1' AND u.role='".$role."' ".$cond." GROUP BY u.userid ORDER BY u.fname ASC,u.userid ASC ";
                break;
            case "7"://AM
                if($value!='')$cond=" AND d.rm_email='".$value."'";
                
                $query_str = "SELECT u.userid,u.emp_code,u.fname,u.lname,u.dealer_code, u.emailid as value FROM ".TABLE_USER." u JOIN ".DMS_DEALER." d ON u.emailid=d.am_email WHERE d.is_deleted=0 AND u.is_deleted=0 AND u.status='1' AND u.role='".$role."' ".$cond." GROUP BY u.userid ORDER BY u.fname ASC,u.userid ASC ";
                break;
            case "14"://DEALER
                 if($value!='')$cond=" AND d.am_email='".$value."'";
                
                $query_str = "SELECT u.userid,u.emp_code,u.fname,u.lname,u.dealer_code, u.dealer_code as value FROM ".TABLE_USER." u JOIN ".DMS_DEALER." d ON d.dealer_code=u.dealer_code  WHERE  d.is_deleted=0 AND u.is_deleted=0 AND u.status='1' AND u.role='".$role."' ".$cond." GROUP BY u.userid ORDER BY u.fname ASC,u.userid ASC ";
                break;
            
        }
            
        $user_arr=$parent->getQueryValue($query_str);
        $arr=(count($user_arr)>0)?$user_arr:array();
        
        //LOG 
        $logstr='VIDEO TRAINING ROLE USER';			 
        globalfunc::insertUserLog($parent,$logstr); 
        $parent->response(array('response'=>'success', 'data'=>$arr,'message'=>$this->page_data['success1']),200);  
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    
    /* /////////////////////////////// RM LIST //////////////////////////////////////////////// */
	private function rmlist($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));
        globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
            
        $REQUEST_KEYS=array('role'=>'number','value'=>'string');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        $role= escape_str($parent->_request['role']);  
        $value=json_decode($parent->_request['value']);
            
        if(!is_array($value)&& count($value)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error5"]),406);
        
        if($role=='5')
        {
            $empcode_quotes = array_map("quotes_array", $value);
            $cond=" AND emp_code IN (".@implode(",",$empcode_quotes).")";

            $get_trainer_str = "SELECT  zone FROM ".DMS_HOUSER."  WHERE  status='1' ".$cond." LIMIT 1";              
            $trainer_arr=$parent->getQueryValue($get_trainer_str);

            $dcond=(count($trainer_arr)>0)?" AND zone='".$trainer_arr[0]->zone."'":" AND zone=''";
        }else
        {
            $email_quotes = array_map("quotes_array", $value);
            $dcond=" AND zm_email IN (".@implode(",",$email_quotes).")"; 
        }
        $query_str = "SELECT rm_name as name,rm_email as value FROM ".DMS_DEALER." WHERE status='1' AND is_deleted='0' ".$dcond." GROUP BY rm_email ";
           
        $user_arr=$parent->getQueryValue($query_str);
        $arr=(count($user_arr)>0)?$user_arr:array();
        
        //LOG 
        $logstr='VIDEO TRAINING RM LIST';			 
        globalfunc::insertUserLog($parent,$logstr); 
        $parent->response(array('response'=>'success', 'data'=>$arr,'message'=>$this->page_data['success1']),200);  
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// AM LIST //////////////////////////////////////////////// */
	private function amlist($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));
        globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
            
        $REQUEST_KEYS=array('role'=>'number','value'=>'string');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        $role= escape_str($parent->_request['role']); 
        $value=json_decode($parent->_request['value']);
        if(!is_array($value)&& count($value)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error5"]),406);
            
        $email_quotes = array_map("quotes_array", $value);
        $dcond=" AND rm_email IN (".@implode(",",$email_quotes).")"; 


        $query_str = "SELECT am_name as name,am_email as value FROM ".DMS_DEALER." WHERE status='1' AND is_deleted='0' ".$dcond." GROUP BY am_email ";
        $user_arr=$parent->getQueryValue($query_str);
        $arr=(count($user_arr)>0)?$user_arr:array();
        
        //LOG 
        $logstr='VIDEO TRAINING AM LIST';			 
        globalfunc::insertUserLog($parent,$logstr); 
        $parent->response(array('response'=>'success', 'data'=>$arr,'message'=>$this->page_data['success1']),200);  
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// DEALER LIST //////////////////////////////////////////////// */
	private function dealerlist($parent)
	{  
        globalfunc::checkMethodType($parent,array('POST'));
        globalfunc::checkParamCount($parent,1);
        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
            
        $REQUEST_KEYS=array('role'=>'number','value'=>'string');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        $role= escape_str($parent->_request['role']); 
        $value=json_decode($parent->_request['value']);
        if(!is_array($value)&& count($value)>0) $parent->response(array('response'=>'failed','message'=>$this->page_data["error5"]),406);
            
        $email_quotes = array_map("quotes_array", $value);
        $dcond=" AND am_email IN (".@implode(",",$email_quotes).")"; 


        $query_str = "SELECT dealer_name as name,dealer_code as value FROM ".DMS_DEALER." WHERE status='1' AND is_deleted='0' ".$dcond."";
        $user_arr=$parent->getQueryValue($query_str);
        $arr=(count($user_arr)>0)?$user_arr:array();
        
        //LOG 
        $logstr='VIDEO TRAINING DEALER LIST';			 
        globalfunc::insertUserLog($parent,$logstr); 
        $parent->response(array('response'=>'success', 'data'=>$arr,'message'=>$this->page_data['success1']),200);  
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// SCHEDULETRAINING LIST //////////////////////////////////////////////// */
	private function  scheduletraining($parent)
	{
        globalfunc::checkMethodType($parent,array('GET' ));
        globalfunc::checkAuthrozation($parent,array('type'=>'user')); 
        globalfunc::checkParamCount($parent,1);
        projectfunc::authorizedRole($parent,array('3'));
        
        $userid=$parent->current_user_id; 
        $role=$parent->current_user_role;    
        
        //PAGINATION SETTINGS
        $limit_cond='';
        $data_arr=array();  
        $limit_str=globalfunc::setPageLimit($parent,$parent->params[0]);
        $limit_cond=($limit_str)?" LIMIT ".$limit_str:'';
        
        
        $query_str = "SELECT SQL_CALC_FOUND_ROWS  s.*,CONCAT(u.fname,' ',u.lname) as organiser_name,u.emp_code FROM ".TABLE_VIDEOTRAININGSCHEDULE." s JOIN ".TABLE_USER." u ON u.userid=s.organiser  WHERE s.is_deleted='0' AND s.status=1 AND s.creator_id='".$userid."' ORDER BY s.fromdate DESC,s.id DESC ".$limit_cond;
        $get_list_arr = $parent->getQueryValue($query_str);
        
//        if(count($get_list_arr)>0)
//        {
//            foreach($get_list_arr as $key=>$res)
//            {
//                
//                $get_list_arr[$key]->organiser_name='';
//            }
//        }

        // Total records
        $rows_result = $parent->getQueryValue("SELECT FOUND_ROWS() as total_records");
        $total_records = (count($rows_result)>0)?$rows_result[0]->total_records:0; 
        
        $data_arr=(count($get_list_arr)>0)?$get_list_arr:array();
                
                
        //LOG        
        $logstr='VIDEO SCHEDULED LIST';			 
        globalfunc::insertUserLog($parent,$logstr);

        $last_page=($total_records)?ceil($total_records/$parent->current_limit)-1:0;
        $parent->response(array('response'=>'success', 'data'=>$data_arr,'total'=>$total_records,'last_page'=>$last_page,'current_page'=>$parent->current_page,'message'=>$this->page_data['success1']),200);
    }  
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////// SCHEDULETRAINING LIST //////////////////////////////////////////////// */
	private function  addtraining($parent)
	{
        globalfunc::checkMethodType($parent,array('POST' ));
        globalfunc::checkAuthrozation($parent,array('type'=>'user')); 
        globalfunc::checkParamCount($parent,1);
        projectfunc::authorizedRole($parent,array('3'));
        
        $REQUEST_KEYS=array('userid'=>'number','role'=>'number','title'=>'string','description'=>'string','fromdate'=>'date|Y-m-d H:i:s','todate'=>'date|Y-m-d H:i:s');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        
        $userid= escape_str($parent->_request['userid']); 
        $role=escape_str($parent->_request['role']);
        $title=escape_str($parent->_request['title']);
        $description=escape_str($parent->_request['description']);
        $fromdate=escape_str($parent->_request['fromdate']);
        $todate=escape_str($parent->_request['todate']);
       // $participant_role=isset($parent->_request['participant_role'])?escape_str($parent->_request['participant_role']):10;
        
        if(strtotime($fromdate)<NOW) $parent->response(array('response'=>'failed','message'=>$this->page_data["error4"]),406);
        if(strtotime($todate)<NOW) $parent->response(array('response'=>'failed','message'=>$this->page_data["error4"]),406);
        if(strtotime($fromdate)>strtotime($todate)) $parent->response(array('response'=>'failed','message'=>'from date should be greater than to date'),406);
        
        $dse=$parent->_request['dse'];
        $dse=json_decode($dse); //sending as string
        $channel=escape_str($parent->_request['channel']);
        $typeid=escape_str($parent->_request['typeid']);
        
        if(!(is_array($dse) && count($dse)>0)) $parent->response(array('response'=>'failed','message'=>$this->page_data["error2"]),406);
        
        //UPDATED FOR APP TEAM
        $channeltemp = explode("_",$channel);
        $gettrname="select emp_code from tbl__user where userid='".$userid."'";
        $trname_arr=$parent->getQueryValue($gettrname);                
        $channel = $trname_arr[0]->emp_code."_".$channeltemp[1]."_".$channeltemp[2];
        
        //INSERT 				
        $insert_str = "INSERT INTO ".TABLE_VIDEOTRAININGSCHEDULE."(typeid, `title`, `description`, `fromdate`, `todate`,channel, `status`, `organiser_role`, `organiser`, creator_id,`created_on`, `modified_on`) VALUES ('".$typeid."','".$title."','".$description."','".$fromdate."','".$todate."','".$channel."','1','".$role."','".$userid."','".$parent->current_user_id."','".NOW."','".NOW."')";
        $parent->executeQuery($insert_str);               
        $trainingid=$parent->lastInsertId();
            
        foreach($dse as $userid)
        {
            $ins_arr[]="('".$trainingid."', '".$userid."', 1,'".NOW."','".NOW."')";
        }
        $insert_str = "INSERT INTO ".TABLE_VIDEOSCHEDULEUSER." ( `sid`, `userid`, `status`, `created_on`, `modified_on`) VALUES ".@implode(",", $ins_arr);
        $parent->executeQuery($insert_str);                
        $this->notificationtriggervideotraining($parent,$trainingid);

        //LOG        
        $logstr='VIDEO TRAINING SCHEDULE';			 
        globalfunc::insertUserLog($parent,$logstr);

        $parent->response(array('response'=>'success','message'=>$this->page_data['success1']),200);
    }  
    /* //////////////////////////////////////////////////////////////////////////////////////////// */
}

?>