<?php
include "Connection.php";
$conn = new Connection();
        

if(isset($_REQUEST["funName"])) {
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
	switch($fun) {
        
		case "surveylist":
        case "addsurvey":
        case "editsurvey":
        case "surveydetails":    
        case "deletesurvey":    
        case "surveypushnotificationbackend":    
			$fun();      
		break;
        
        default:
            $conn->message(false,"PAGE NOT FOUND");exit;
        break;	
	}
}else
{
      $conn->message(false,"PAGE NOT FOUND");exit;
}
        
//Getting SURVEY LIST
function surveylist () {
	global $conn;
	try { 
        
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
        
		$pn = escape_str($_REQUEST["pn"]);
		$nr = escape_str($_REQUEST["nr"]);
		$key = escape_str($_REQUEST["key"]);
		$cateid = escape_str($_REQUEST['cateid']);
        //$trainingid = escape_str ($_REQUEST["trainingid"]);
        
		if(isset($_SESSION["userid"])) {
            
            $excond='';
        
            if ($key!='') {
				$excond .= " AND a.assessmentname like '%".$key."%'  ";
			}
            //PAGINATION
            if (!empty($pn) and !empty($nr)) {
				// Navigation
    			$limitcond = " limit ".(($pn - 1) *  $nr).", " . $nr;
			}
            
            $query_str = "SELECT `id`, `rolename`  FROM ".TABLE_ROLE." WHERE status=1 ".$cond;        
			$role_arr = $conn->getQueryValue($query_str);
			if(count($role_arr)>0)
			{
				foreach($role_arr as $res)
				{
					$data_role[$res->id]=$res;
				}
			}
            
			$query_str = "SELECT SQL_CALC_FOUND_ROWS a.`assessmentid`, a.`assessmentname`,a.`description`,a.`assessmenttype`,a.`assettypeid`,a. `assessmenttimetype` ,a.`assessmenttime`,a.`randomcond`,a.`created_on`,a.publisheddate,a.enddate,a.assessmentnotification,a.attemptslimit,a.`filter_role`, a.`filter_zone`, a.`filter_region`, a.`filter_dealer` FROM ".TABLE_ASSESSMENT." a  WHERE a.assettypeid='2' AND a.status='1' ".$excond." ORDER BY a.assessmentid DESC ".$limitcond;
            $query = $conn->query($query_str);

			// Total records
			$rows_query = $conn->query("SELECT FOUND_ROWS() as total_records");
			$rows_result = $rows_query->fetchAll(PDO::FETCH_OBJ);
			$total_records = $rows_result[0]->total_records;
            $assessment_arr= $query->fetchAll(PDO::FETCH_OBJ);
            
            if(count($assessment_arr)>0)
            {
                foreach($assessment_arr as $akey=>$res_assess)
                {
                    $assessment_arr[$akey]->publishedtime=date('H:i',strtotime($res_assess->publisheddate));
                    $assessment_arr[$akey]->endtime=date('H:i',strtotime($res_assess->endtime));
                            
                    $assessment_arr[$akey]->publisheddate=date('Y-m-d',strtotime($res_assess->publisheddate));
                    $assessment_arr[$akey]->enddate=date('Y-m-d',strtotime($res_assess->enddate));
                    
                    //EDITABLE CHECK
                    $check_result_str = "SELECT id FROM `".TABLE_ASSESSMENT_USER."` WHERE assessmentid='".$assessmentid."'  LIMIT 1";  
                    $check_result_arr=$conn->getQueryValue($check_result_str);                    
                    $assessment_arr[$akey]->is_edit=(count($check_result_arr)>0)?"0":"1";
                    
                    $assessment_arr[$akey]->filter_role=($res_assess->filter_role!='')?@explode(',',$res_assess->filter_role):array();
					$assessment_arr[$akey]->filter_role_name=array();
					$role_data=array();
					if(count($assessment_arr[$akey]->filter_role)>0)
					{
						foreach($assessment_arr[$akey]->filter_role as $data)
						{
							$role_data[]=$data_role[$data];
						}
						$assessment_arr[$akey]->filter_role_name=$role_data;
					}
					
					$filter_zone_arr=array();
                    $assessment_arr[$akey]->filter_zone=($res_assess->filter_zone!='')?@explode(',',$res_assess->filter_zone):array();
					if(count($assessment_arr[$akey]->filter_zone)>0)
					{
						foreach($assessment_arr[$akey]->filter_zone as $res_zone)
						{
							$filter_zone_arr[]=array('zone'=>$res_zone);
						}
						$assessment_arr[$akey]->filter_zone=$filter_zone_arr;
					}
				
					
					$filter_region_arr=array();
                    $assessment_arr[$akey]->filter_region=($res_assess->filter_region!='')?@explode(',',$res_assess->filter_region):array();
					if(count($assessment_arr[$akey]->filter_region)>0)
					{
						foreach($assessment_arr[$akey]->filter_region as $res_region)
						{
							$filter_region_arr[]=array('city'=>$res_region);
						}
						$assessment_arr[$akey]->filter_region=$filter_region_arr;
					}
					
					$filter_dealer_arr=array();
                    $assessment_arr[$akey]->filter_dealer=($res_assess->filter_dealer!='')?@explode(',',$res_assess->filter_dealer):array();
					if(count($assessment_arr[$akey]->filter_dealer)>0)
					{
						$dealer_quotes = array_map("quotes_array", $assessment_arr[$akey]->filter_dealer);  

						$query_str = "SELECT `dealer_code`, `dealer_name` FROM ".DMS_DEALER." WHERE status='1' AND is_deleted='0' AND dealer_code IN (".@implode(',',$dealer_quotes).") GROUP BY dealer_code ";
						$query = $conn->query($query_str);
						$deal_arr = $query->fetchAll(PDO::FETCH_OBJ);
			
						$assessment_arr[$akey]->filter_dealer=$deal_arr;
					}
        
                }
            }
            if (!empty($pn) and !empty($nr)){    
                $arr['total_records'] = $total_records;
            }
			$arr['survey'] = $assessment_arr;
			if(count($arr) != 0){
				$conn->message(true,$conn->getMessage($lang,'survey','success1'), $arr); 
			}else{
				$conn->message(false,$conn->getMessage($lang,'survey','error2'));
			}
		}
		else{
			$conn->message(false,$conn->getMessage($lang,'survey','error1'));
		}
	}
	catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'survey','error4'));
	}
}
//ADD SURVEY
function addsurvey () {
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            
            $assessmentname = escape_str($_REQUEST["assessmentname"]);			
			//$assessmenttype = escape_str($_REQUEST["assessmenttype"]);
            $assessmenttype = 1;
            $assessmenttimetype = escape_str($_REQUEST["assessmenttimetype"]);
            $assessmenttime =($assessmenttimetype=='1')? escape_str($_REQUEST["assessmenttime"]):'0';
            $randomcond=escape_str($_REQUEST["randomcond"]);
            $assessmentnotification=escape_str($_REQUEST["assessmentnotification"]); //COMMA SEPERATE            
            if($assessmentnotification!='')
            {
                $assessmentnotification_arr=@explode(',',$assessmentnotification);
                
                foreach($assessmentnotification_arr as $days)
                {
                    if($days!='')
                    {
                        if(!is_numeric($days)){  $conn->message(false,$conn->getMessage($lang,'survey','error9'));   }
                    }
                }
            }
            
            $total_question=escape_str($_REQUEST["total_question"]);
            $atype=0;            
            $attemptslimit= 1;
            //$attemptslimit= escape_str($_REQUEST["attemptslimit"]);
            $publisheddate= escape_str($_REQUEST["publisheddate"]);
            $enddate=escape_str($_REQUEST["enddate"]);
            
            $publishedtime=escape_str($_REQUEST["publishedtime"]);
            $endtime=escape_str($_REQUEST["endtime"]);
            
            if($publishedtime!='' && $endtime!='')
            {
                $publisheddate.=" ".$publishedtime;
                $enddate.=" ".$endtime;
            }else
            {
                $publisheddate.=" 00:00:00";
                $enddate.=" 23:59:59";
            }
            $user_type =(isset($_REQUEST["user_type"]))?escape_str($_REQUEST["user_type"]):0;
            
            $filter_role=(is_string ($_REQUEST["filter_role"]))?escape_str($_REQUEST["filter_role"]):'';
            //$filter_role=@implode(',',$_REQUEST["filter_role"]);
            
            $filter_zone=(is_string ($_REQUEST["filter_zone"]))?escape_str($_REQUEST["filter_zone"]):'';
            //$filter_zone=@implode(',',$_REQUEST["filter_zone"]);
            
            $filter_region=(is_string ($_REQUEST["filter_region"]))?escape_str($_REQUEST["filter_region"]):'';
            //$filter_region=@implode(',',$_REQUEST["filter_region"]);
            
            $filter_dealer=(is_string ($_REQUEST["filter_dealer"]))?escape_str($_REQUEST["filter_dealer"]):'';
            
                        
            //assessmenttime validation
            $filter_options=array('options' => array( 'min_range' => 0));
            if(!( filter_var( $assessmenttime, FILTER_VALIDATE_INT, $filter_options ) !== FALSE)) {   echo $conn->message(false,'Assessment Time should be integer and above 0');exit; }
        
            $question_arr=json_decode($_REQUEST["question_json"]); //question_json  [{ "qid":10,"is_mandatory":1},{ "qid":12,"is_mandatory":1}]
            
            //VALIDATION CHECK
            if(!(  $assessmentname!='' && $assessmenttype!=''  && $randomcond!='' && $assessmentnotification!='' &&  $_REQUEST["question_json"]!='' && $attemptslimit!='' && $publisheddate!='' && $enddate!='' && $attemptslimit!=''  && count($question_arr)>0 && $total_question!='' && $total_question>0))
            {
                $conn->message(false,$conn->getMessage($lang,'survey','error5'));
            }   
            
            //VALIDATE QUESTION COUNT
            if(count($question_arr)<$total_question) $conn->message(false,$conn->getMessage($lang,'survey','error6'));
        
            //INSERT ASSESSMENT
            $insert_qry = "INSERT INTO ".TABLE_ASSESSMENT ." ( `atype`,`user_type`, `assessmentname`, `description`,   `assessmenttype`, `assettypeid`, `assessmenttimetype` , `assessmenttime`,  `attemptslimit`, `publisheddate`, `enddate`, `randomcond`, `filter_role`, `filter_zone`, `filter_region`, `filter_dealer`,`assessmentnotification`,`total_question` ,`status`, `creatorid`, `created_on`, `modified_on`) VALUES ( '".$atype."','".$user_type."','".$assessmentname."', '".$description."','".$assessmenttype."', '2','".$assessmenttimetype."','".$assessmenttime."','".$attemptslimit."','".$publisheddate."', '".$enddate."','".$randomcond."','".$filter_role."','".$filter_zone."','".$filter_region."','".$filter_dealer."','".$assessmentnotification."','".$total_question."','1','".$_SESSION["userid"]."', '".NOW."', '".NOW."')"; 
			$conn->query($insert_qry);
			$assessmentid = $conn->lastinsetid();
        
            //INSERT ASSESSMENT QUESTION
            if(count($question_arr)>0)
            {                
                $insert_question_arr=array();
                foreach($question_arr as $res_ques)
                {
                    $insert_ques_arr[]="('".$assessmentid."', '".$res_ques->qid."', '".$res_ques->is_mandatory."','".$_SESSION["userid"]."', '".NOW."', '".NOW."')";
                }               
                $insert_ques_qry = "INSERT INTO `".TABLE_ASSESSMENT_QUESTION."`(  `assessmentid`,  `qid`, `is_mandatory`, `creatorid`, `created_on`, `modified_on`) VALUES ".@implode(',',$insert_ques_arr); 
                $conn->query($insert_ques_qry);
            }
			
			sendAssessmentNotification($assessmentid);
                    
            $conn->message(true,$conn->getMessage($lang,'survey','success1'),getAssessment($assessmentid)); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'survey','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'survey','error4'));
	}
}

//EDIT SURVEY
function editsurvey () {
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            $assessmentid = escape_str($_REQUEST["assessmentid"]);
            $assessmentname = escape_str($_REQUEST["assessmentname"]);        
            $assessmenttype = 1;
            $assessmenttimetype = escape_str($_REQUEST["assessmenttimetype"]);
            $assessmenttime =($assessmenttimetype=='1')? escape_str($_REQUEST["assessmenttime"]):'0';
            $randomcond=escape_str($_REQUEST["randomcond"]);
            $assessmentnotification=escape_str($_REQUEST["assessmentnotification"]); //COMMA SEPERATE
            if($assessmentnotification!='')
            {
                $assessmentnotification_arr=@explode(',',$assessmentnotification);
                
                foreach($assessmentnotification_arr as $days)
                {
                    if($days!='')
                    {
                        if(!is_numeric($days)){  $conn->message(false,$conn->getMessage($lang,'survey','error9'));   }
                    }
                }
            }
            $total_question=escape_str($_REQUEST["total_question"]);        
            $question_arr=json_decode($_REQUEST["question_json"]); //question_json  [{ "qid":10,"is_mandatory":1},{ "qid":12,"is_mandatory":1}]
                        
            $attemptslimit= 1;
            $publisheddate= escape_str($_REQUEST["publisheddate"]);
            $enddate=escape_str($_REQUEST["enddate"]);
            
            $publishedtime=escape_str($_REQUEST["publishedtime"]);
            $endtime=escape_str($_REQUEST["endtime"]);
            if($publishedtime!='' && $endtime!='')
            {
                $publisheddate.=" ".$publishedtime;
                $enddate.=" ".$endtime;
            }else
            {
                $publisheddate.=" 00:00:00";
                $enddate.=" 23:59:59";
            }
            
            $filter_role=(is_string ($_REQUEST["filter_role"]))?escape_str($_REQUEST["filter_role"]):'';
            //$filter_role=@implode(',',$_REQUEST["filter_role"]);
            
            $filter_zone=(is_string ($_REQUEST["filter_zone"]))?escape_str($_REQUEST["filter_zone"]):'';
            //$filter_zone=@implode(',',$_REQUEST["filter_zone"]);
            
            $filter_region=(is_string ($_REQUEST["filter_region"]))?escape_str($_REQUEST["filter_region"]):'';
            //$filter_region=@implode(',',$_REQUEST["filter_region"]);
            
            $filter_dealer=(is_string ($_REQUEST["filter_dealer"]))?escape_str($_REQUEST["filter_dealer"]):'';
        
             //VALIDATION CHECK
            if(!($assessmentid!='' && $assessmentname!='' && $assessmenttype!=''  && $randomcond!='' && $assessmentnotification!='' && $attemptslimit!=''  && $publisheddate!='' && $enddate!=''  && $_REQUEST["question_json"]!=''  && count($question_arr)>0 && $total_question!='' && $total_question>0))
            {
                $conn->message(false,$conn->getMessage($lang,'survey','error5'));
            }
            
            //assessmenttime validation
            $filter_options=array('options' => array( 'min_range' => 0));
            if(!( filter_var( $assessmenttime, FILTER_VALIDATE_INT, $filter_options ) !== FALSE)) {   echo $conn->message(false,'Assessment Time should be integer and above 0');exit; }
            
            //VALIDATE QUESTION COUNT
            if(count($question_arr)<$total_question) $conn->message(false,$conn->getMessage($lang,'survey','error6'));
            
            //CHECK ASSESSMENT USER ALREADY ADDED
            $check_result_str = "SELECT id FROM `".TABLE_ASSESSMENT_USER."` WHERE assessmentid='".$assessmentid."'  LIMIT 1";  
            $check_result_arr=$conn->getQueryValue($check_result_str);
            if(count($check_result_arr)>0)
            {
                $conn->message(false,$conn->getMessage($lang,'survey','error7'));
            }
        
            //UPDATE  ASSESSMENT
            $update_qry = "UPDATE ".TABLE_ASSESSMENT."  SET `assessmentname`='".$assessmentname."' , `description`='".$description."',assessmenttimetype='".$assessmenttimetype."', `assessmenttime`='".$assessmenttime."' ,attemptslimit='".$attemptslimit."',`publisheddate`='".$publisheddate."', `enddate`='".$enddate."', `randomcond`='".$randomcond."',`filter_role`='".$filter_role."', `filter_zone`='".$filter_zone."', `filter_region`='".$filter_region."', `filter_dealer`='".$filter_dealer."', `assessmentnotification`='".$assessmentnotification."',total_question='".$total_question."', `modified_on`='".NOW."' WHERE assessmentid='".$assessmentid."'"; 
			$conn->query($update_qry);       
            
        
            //INSERT ASSESSMENT QUESTION
            if(count($question_arr)>0)
            {
                //DELETE OLD SUPPLIER DATA
                $delete_ques_qry = "DELETE FROM ".TABLE_ASSESSMENT_QUESTION." WHERE assessmentid='".$assessmentid."'"; 
                $conn->query($delete_ques_qry);
                
                $insert_question_arr=array();
                foreach($question_arr as $res_ques)
                {
                    $insert_ques_arr[]=" ('".$assessmentid."','".$res_ques->qid."', '".$res_ques->is_mandatory."','".$_SESSION["userid"]."',  '".NOW."', '".NOW."')";
                }               
                $insert_ques_qry = "INSERT INTO `".TABLE_ASSESSMENT_QUESTION."`(  `assessmentid`, `qid`, `is_mandatory`, `creatorid`, `created_on`, `modified_on`) VALUES ".@implode(',',$insert_ques_arr); 
                $conn->query($insert_ques_qry);
            }
                    
            $conn->message(true,$conn->getMessage($lang,'survey','success1'),getAssessment($assessmentid)); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'survey','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'survey','error4'));
	}
}
// DELETE SURVEY  
function deletesurvey () {
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            $assessmentid = escape_str($_REQUEST["assessmentid"]);
        
            //VALIDATION CHECK
            if(!($assessmentid!=''  )) $conn->message(false,$conn->getMessage($lang,'survey','error5'));
        
            
            //CHECK ASSESSMENT USER ALREADY ADDED
            $check_result_str = "SELECT id FROM `".TABLE_ASSESSMENT_USER."` WHERE assessmentid='".$assessmentid."'   LIMIT 1";  
            $check_result_arr=$conn->getQueryValue($check_result_str);
            if(count($check_result_arr)>0)  $conn->message(false,$conn->getMessage($lang,'survey','error8'));
        
            
            //DELETE TABLE_ASSESSMENT
            $update_qry = "UPDATE ".TABLE_ASSESSMENT."  SET `status`='0' WHERE assessmentid='".$assessmentid."'"; 
			$conn->query($update_qry);             
        
            $conn->message(true,$conn->getMessage($lang,'survey','success1')); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'survey','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'survey','error4'));
	}
}
        

function sendAssessmentNotification ( $assessmentid )
{
    
    global $conn;        
    $assessment_str = "SELECT * FROM `".TABLE_ASSESSMENT."` WHERE assessmentid='".$assessmentid."' AND assettypeid='2'  LIMIT 1"; 
    $assessment_arr=$conn->getQueryValue($assessment_str);

    if(count($assessment_arr)>0)
    {
        $obj=new stdClass();
        $obj->id=$assessment_arr[0]->assessmentid;
        $obj->assessmentid=$assessment_arr[0]->assessmentid;

        $notificationdata= json_encode($obj);
        $notificationtype='3';
        
        $publisheddate=$assessment_arr[0]->publisheddate;
        $enddate=$assessment_arr[0]->enddate;

        $notificationtext="New Feedback - `".$assessment_arr[0]->assessmentname."` assigned for date : ".date('dS M h:i A',strtotime($assessment_arr[0]->publisheddate))." - ".date('dS M h:i A',strtotime($enddate));            
        //ROLE
        if($assessment_arr[0]->filter_role!='')
        {
            $role_arr=@explode(',',$assessment_arr[0]->filter_role); 
            if(count($role_arr)>0)
            {
                $user_cond.=" AND role IN (".$assessment_arr[0]->filter_role.")";
            }                
        }
        //ZONE
        if($assessment_arr[0]->filter_zone!='')
        {
            $zone_arr=@explode(',',$assessment_arr[0]->filter_zone); 
            if(count($zone_arr)>0)
            {
                $zone_quotes = array_map("quotes_array", $zone_arr);                   
                $user_cond.=" AND dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE zone IN (".@implode(',',$zone_quotes)."))";
            }
        }
        //REGION
        if($assessment_arr[0]->filter_region!='')
        {
            $region_arr=@explode(',',$assessment_arr[0]->filter_region);
            if(count($region_arr)>0)
            {
                $region_quotes = array_map("quotes_array", $region_arr);
                $user_cond.=" AND dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE city IN (".@implode(',',$region_quotes)."))";
            }
        }
        //DEALER
        if($assessment_arr[0]->filter_dealer!='')
        { 
            $dealer_arr=@explode(',',$assessment_arr[0]->filter_dealer);
            if(count($dealer_arr)>0)
            {
                $dealer_quotes = array_map("quotes_array", $dealer_arr);
                $user_cond.=" AND dealer_code IN (".@implode(',',$dealer_quotes).")";
            }
        }
        
        $user_cond.=($assessment_arr[0]->user_type=='0')?" AND role>7 AND role<14":" AND role=15";        
        
		switch($assessment_arr[0]->segment)
        {
            case '1':$user_cond.=' AND (segment=0 OR segment=1)';
                break;
            case '2':$user_cond.=' AND (segment=0 OR segment=2)';
                break;
            default: //$user_cond.=' AND segment=0';
			break;
        }
		

        //CHECK USER EXIST FOR NOTIFICATION 
		$check_user_str = " SELECT userid FROM ".TABLE_USER." WHERE   status='1' AND is_deleted='0' ".$user_cond;
        
        $check_user_arr = $conn->getQueryValue($check_user_str);  
        $user_arr=array();    
        if(count($check_user_arr)>0)
        {
			foreach ($check_user_arr as $res_user)
            {
                $user_arr[]=$res_user->userid;
            }
			 
            //INSERT NOTITFICATION
            $conn->executeQuery("INSERT INTO `".TABLE_NOTIFICATION."` (  `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('".escape_str($assessment_arr[0]->assessmentname)."','".escape_str($notificationtext)."','".$notificationdata."','".$notificationtype."' ,'1','".NOW."','".NOW."','".NOW."')");

            $notificationid=$conn->lastinsetid();
            $data=array('notification_id'=>$notificationid,'title'=>$assessment_arr[0]->assessmentname,'message'=>$notificationtext,'notificationtype'=>$notificationtype,'notificationdata'=>$notificationdata,'created_date'=>NOW);

            if(count($user_arr)>0)
            {
                $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)
                {
                    $conn->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 = $conn->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;
						}
					}

                    // $conn->sendUserNotification($data,$usertokenarr);
                }
                
            }
        }
    }
}

// GET ASSESSMENT
function getAssessment($assessmentid)
{
	global $conn;
    $data_arr=array();
    if($assessmentid!='')
    { 
        
        $query_str = "SELECT `id`, `rolename`  FROM ".TABLE_ROLE." WHERE status=1 ";        
        $role_arr = $conn->getQueryValue($query_str);
        if(count($role_arr)>0)
        {
            foreach($role_arr as $res)
            {
                $data_role[$res->id]=$res;
            }
        }
        
        $data_arr=$conn->getQueryValue( "SELECT a.`assessmentid`, a.`assessmentname`,a.`description`,a.`assessmenttype`,a.`assettypeid`,a. `assessmenttimetype` ,a.`assessmenttime`,a.`randomcond`,a.`created_on`,a.publisheddate,a.enddate, a.`filter_role`, a.`filter_zone`, a.`filter_region`, a.`filter_dealer`  FROM ".TABLE_ASSESSMENT." a  WHERE a.assettypeid='2' AND a.status='1' AND a.assessmentid='".$assessmentid."' LIMIT 1");
        
        if(count($data_arr)>0)
        {
            $check_result_str = "SELECT id FROM `".TABLE_ASSESSMENT_USER."` WHERE assessmentid='".$assessmentid."' LIMIT 1";  
            $check_result_arr=$conn->getQueryValue($check_result_str); 
            $data_arr[0]->is_edit=(count($check_result_arr)>0)?"0":"1";
        
            $data_arr[0]->publishedtime=date('H:i',strtotime($data_arr[0]->publisheddate));
            $data_arr[0]->endtime=date('H:i',strtotime($data_arr[0]->enddate));
            
            $data_arr[0]->publisheddate=date('Y-m-d',strtotime($data_arr[0]->publisheddate));
            $data_arr[0]->enddate=date('Y-m-d',strtotime($data_arr[0]->enddate));
            
            $data_arr[0]->filter_role=($data_arr[0]->filter_role!='')?@explode(',',$data_arr[0]->filter_role):array();
            $data_arr[0]->filter_role_name=array();
            $role_data=array();
            if(count($data_arr[0]->filter_role)>0)
            {
                foreach($data_arr[0]->filter_role as $data)
                {
                    $role_data[]=$data_role[$data];
                }
                $data_arr[0]->filter_role_name=$role_data;
            }

            $filter_zone_arr=array();
            $data_arr[0]->filter_zone=($data_arr[0]->filter_zone!='')?@explode(',',$data_arr[0]->filter_zone):array();
            if(count($data_arr[0]->filter_zone)>0)
            {
                foreach($data_arr[0]->filter_zone as $res_zone)
                {
                    $filter_zone_arr[]=array('zone'=>$res_zone);
                }
                $data_arr[0]->filter_zone=$filter_zone_arr;
            }


            $filter_region_arr=array();
            $data_arr[0]->filter_region=($data_arr[0]->filter_region!='')?@explode(',',$data_arr[0]->filter_region):array();
            if(count($data_arr[0]->filter_region)>0)
            {
                foreach($data_arr[0]->filter_region as $res_region)
                {
                    $filter_region_arr[]=array('city'=>$res_region);
                }
                $data_arr[0]->filter_region=$filter_region_arr;
            }

            $filter_dealer_arr=array();
            $data_arr[0]->filter_dealer=($data_arr[0]->filter_dealer!='')?@explode(',',$data_arr[0]->filter_dealer):array();
            if(count($data_arr[0]->filter_dealer)>0)
            {
                $dealer_quotes = array_map("quotes_array", $data_arr[0]->filter_dealer);  

                $query_str = "SELECT `dealer_code`, `dealer_name` FROM ".DMS_DEALER." WHERE status='1' AND is_deleted='0' AND dealer_code IN (".@implode(',',$dealer_quotes).") GROUP BY dealer_code ";
                $query = $conn->query($query_str);
                $deal_arr = $query->fetchAll(PDO::FETCH_OBJ);

                $data_arr[0]->filter_dealer=$deal_arr;
            }
        }
        
        $data_arr=(count($data_arr)>0)?$data_arr[0]:array();
    }
    return $data_arr;
}


function surveydetails (){
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            $assessmentid = escape_str($_REQUEST["assessmentid"]);
        
            //VALIDATION CHECK
            if(!($assessmentid!=''  )) $conn->message(false,$conn->getMessage($lang,'survey','error2'));
        
            $query_str = "SELECT `id`, `rolename`  FROM ".TABLE_ROLE." WHERE status=1 ";        
            $role_arr = $conn->getQueryValue($query_str);
            if(count($role_arr)>0)
            {
                foreach($role_arr as $res)
                {
                    $data_role[$res->id]=$res;
                }
            }
            
            
            $check_assessment_str = "SELECT * FROM `".TABLE_ASSESSMENT."` WHERE assessmentid='".$assessmentid."' AND status='1' AND assettypeid='2' LIMIT 1";  
            $check_assessment_arr=$conn->getQueryValue($check_assessment_str);
            if(!(count($check_assessment_arr)>0))
            {
                $conn->message(false,$conn->getMessage($lang,'survey','error3'));
            }       
            
            $check_assessment_arr[0]->publishedtime=date('H:i',strtotime($check_assessment_arr[0]->publisheddate));
            $check_assessment_arr[0]->endtime=date('H:i',strtotime($check_assessment_arr[0]->enddate));
            
            $check_assessment_arr[0]->publisheddate=date('Y-m-d',strtotime($check_assessment_arr[0]->publisheddate));
            $check_assessment_arr[0]->enddate=date('Y-m-d',strtotime($check_assessment_arr[0]->enddate));
            $check_assessment_arr[0]->question_arr=array();
            
            $assessment_ques_str = "SELECT  `assessmentid`, `qid`, `is_mandatory` FROM `".TABLE_ASSESSMENT_QUESTION."` WHERE assessmentid='".$assessmentid."' ";  
            $assessment_ques_arr=$conn->getQueryValue($assessment_ques_str);
            
            $check_assessment_arr[0]->question_arr=(count($assessment_ques_arr)>0)?$assessment_ques_arr:array();
            $check_assessment_arr[0]->questionList=array();
            $check_assessment_arr[0]->is_mandatory=array();
            if(count($assessment_ques_arr)>0)
            {
                foreach($assessment_ques_arr as $res_asses)                    
                {
                    $qid=$res_asses->qid;
                    $questionList[$qid]=true;
                    $is_mandatory[$qid]=$res_asses->is_mandatory;
                }
                
                $check_assessment_arr[0]->questionList=$questionList;
                $check_assessment_arr[0]->is_mandatory=$is_mandatory;
            }
            
            $check_assessment_arr[0]->filter_role=($check_assessment_arr[0]->filter_role!='')?@explode(',',$check_assessment_arr[0]->filter_role):array();
            $check_assessment_arr[0]->filter_role_name=array();
            $role_data=array();
            if(count($check_assessment_arr[0]->filter_role)>0)
            {
                foreach($check_assessment_arr[0]->filter_role as $data)
                {
                    $role_data[]=$data_role[$data];
                }
                $check_assessment_arr[0]->filter_role_name=$role_data;
            }

            $filter_zone_arr=array();
            $check_assessment_arr[0]->filter_zone=($check_assessment_arr[0]->filter_zone!='')?@explode(',',$check_assessment_arr[0]->filter_zone):array();
            if(count($check_assessment_arr[0]->filter_zone)>0)
            {
                foreach($check_assessment_arr[0]->filter_zone as $res_zone)
                {
                    $filter_zone_arr[]=array('zone'=>$res_zone);
                }
                $check_assessment_arr[0]->filter_zone=$filter_zone_arr;
            }


            $filter_region_arr=array();
            $check_assessment_arr[0]->filter_region=($check_assessment_arr[0]->filter_region!='')?@explode(',',$check_assessment_arr[0]->filter_region):array();
            if(count($check_assessment_arr[0]->filter_region)>0)
            {
                foreach($check_assessment_arr[0]->filter_region as $res_region)
                {
                    $filter_region_arr[]=array('city'=>$res_region);
                }
                $check_assessment_arr[0]->filter_region=$filter_region_arr;
            }

            $filter_dealer_arr=array();
            $check_assessment_arr[0]->filter_dealer=($check_assessment_arr[0]->filter_dealer!='')?@explode(',',$check_assessment_arr[0]->filter_dealer):array();
            if(count($check_assessment_arr[0]->filter_dealer)>0)
            {
                $dealer_quotes = array_map("quotes_array", $check_assessment_arr[0]->filter_dealer);  

                $query_str = "SELECT `dealer_code`, `dealer_name` FROM ".DMS_DEALER." WHERE status='1' AND is_deleted='0' AND dealer_code IN (".@implode(',',$dealer_quotes).") GROUP BY dealer_code ";
                $query = $conn->query($query_str);
                $deal_arr = $query->fetchAll(PDO::FETCH_OBJ);

                $check_assessment_arr[0]->filter_dealer=$deal_arr;
            }
        
            $arr=$check_assessment_arr[0];
            $conn->message(true,$conn->getMessage($lang,'survey','success1'),$arr); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'survey','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'survey','error4'));
	}
}
function surveypushnotificationbackend()
{
    global $conn;
    $assessmentid = escape_str($_REQUEST["assessmentid"]);		
    $lang='en_us';
    sendAssessmentNotification ($assessmentid);
    $conn->message(true,$conn->getMessage($lang,'assessment','success1'),array()); 
}

?>