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


if(isset($_REQUEST["funName"])) {
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
	switch($fun) {
		  
        case "notificationlist":
        case "addnotification":
        case "publishnotification":
        case "deletenotification":
		case "notificationdetails":
            $fun();
        break;	
        default:
            $conn->message(false,"PAGE NOT FOUND");exit;
        break;		 
	}
}else
{
      $conn->message(false,"PAGE NOT FOUND");exit;
}

// Notification  List
function notificationlist () {
        
	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"]);
		if(isset($_SESSION["userid"])) {
			$query_str = "SELECT SQL_CALC_FOUND_ROWS *  FROM ".TABLE_NOTIFICATION."  WHERE  status IN (1,2) AND is_admin=1";

			// Search
			if (!empty($key)) {
				$query_str.= " and (notificationtitle like '%$key%' OR notificationtext like '%$key%') ";
			}

			$query_str.= " order by id DESC";

			// Pagination
			if (!empty($pn) and !empty($nr)) {
				// Navigation
    			$query_str.= " limit ".(($pn - 1) *  $nr).", ".$nr;
			}
            // echo $query_str;exit;
			$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;

			$arr['total_records'] = $total_records;
            $data_arr=$query->fetchAll(PDO::FETCH_OBJ);
            
            if(!(count($data_arr)>0))
            {
                $data_arr=array();
            }else
            {
                
                $query_str = "SELECT `id`, `rolename`  FROM ".TABLE_ROLE." WHERE status=1 ";
                $query = $conn->query($query_str);
                $role_arr = $query->fetchAll(PDO::FETCH_OBJ);
                if(count($role_arr)>0)
                {
                    foreach($role_arr as $res)
                    {
                        $data_role[$res->id]=$res;
                    }
                }

                
                foreach($data_arr as $skey=>$res_val)
                { 
                    $data_arr[$skey]->filter_role=($res_val->filter_role!='')?@explode(',',$res_val->filter_role):array();
					$data_arr[$skey]->filter_role_name=array();
					$role_data=array();
					if(count($data_arr[$skey]->filter_role)>0)
					{
						foreach($data_arr[$skey]->filter_role as $data)
						{
							$role_data[]=$data_role[$data];
						}
						$data_arr[$skey]->filter_role_name=$role_data;
					}
					
					$filter_zone_arr=array();
                    $data_arr[$skey]->filter_zone=($res_val->filter_zone!='')?@explode(',',$res_val->filter_zone):array();
					if(count($data_arr[$skey]->filter_zone)>0)
					{
						foreach($data_arr[$skey]->filter_zone as $res_zone)
						{
							$filter_zone_arr[]=array('zone'=>$res_zone);
						}
						$data_arr[$skey]->filter_zone=$filter_zone_arr;
					}
				
					
					$filter_region_arr=array();
                    $data_arr[$skey]->filter_region=($res_val->filter_region!='')?@explode(',',$res_val->filter_region):array();
					if(count($data_arr[$skey]->filter_region)>0)
					{
						foreach($data_arr[$skey]->filter_region as $res_region)
						{
							$filter_region_arr[]=array('city'=>$res_region);
						}
						$data_arr[$skey]->filter_region=$filter_region_arr;
					}
					
					$filter_dealer_arr=array();
                    $data_arr[$skey]->filter_dealer=($res_val->filter_dealer!='')?@explode(',',$res_val->filter_dealer):array();
					if(count($data_arr[$skey]->filter_dealer)>0)
					{
						$dealer_quotes = array_map("quotes_array", $data_arr[$skey]->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[$skey]->filter_dealer=$deal_arr;
					}
                }
            }

			$arr['notification'] = $data_arr;
			if(count($arr) != 0){
				 
                $conn->message(true,$conn->getMessage($lang,'notification','success1'),$arr );
			}else{
				$conn->message(false,$conn->getMessage($lang,'notification','error2'));
			}
		}
		else{
			$conn->message(false,$conn->getMessage($lang,'notification','error1'));
		}
	}
	catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'notification','error4'));
	}
}

// Add Notification
function addnotification () {
	global $conn;
	try {
        
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            
			$notificationtitle = escape_str($_REQUEST["notificationtitle"]);
			$notificationtext  = escape_str($_REQUEST["notificationtext"]);
            $ispublish  = escape_str($_REQUEST["ispublish"]);
            
            if(!($notificationtitle!='' && $notificationtext!='' ) ){ $conn->message(false, 'FIELDS MISSING');exit; }  
                        
            //FILTER
            $filter_role=escape_str($_REQUEST["filter_role"]);
            $filter_zone=escape_str($_REQUEST["filter_zone"]);
            $filter_region=escape_str($_REQUEST["filter_region"]);
            $filter_dealer=escape_str($_REQUEST["filter_dealer"]);
            $notificationtype='5';
            
            if($ispublish==1)
            {
                $status='1';
            }else
            {
                $status='2';
            }
            
        
            $insert = "INSERT INTO ".TABLE_NOTIFICATION." (`notificationtitle`, `notificationtext`, `notificationtype`, `filter_role`, `filter_zone`, `filter_region`, `filter_dealer`, `status`, `publisheddate`, `is_admin`, `created_on`, `modified_on`) VALUES ('".$notificationtitle."','".$notificationtext."','".$notificationtype."','".$filter_role."','".$filter_zone."','".$filter_region."','".$filter_dealer."','".$status."','".NOW."','1' , '".NOW."','".NOW."')"; 
        
            $insertquery = $conn->query($insert);
            $notification_id = $conn->lastinsetid();
            
            if($ispublish==1)
            {
                sendNotificationUser($notification_id);
            }
            $conn->message(true,$conn->getMessage($lang,'notification','success1'),getNotification ($bulletin_id));
        
		}else{
			$conn->message(false,$conn->getMessage($lang,'notification','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'notification','error4'));
	}
}

function publishnotification() {
	global $conn;
	try{
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
        
		if(isset($_SESSION["userid"])){
			$id = escape_str($_REQUEST["id"]);
            
			$updatestr = "UPDATE ".TABLE_NOTIFICATION." SET `status`= '1' WHERE id = '".$id."'";
			$updatequery = $conn->query($updatestr);
            
            if($updatequery)
            {
                sendNotificationUser($id);
            }
            
			if($updatequery) {
				 $conn->message(true,$conn->getMessage($lang,'notification','success1'));
			}
		}else{
			$conn->message(false,$conn->getMessage($lang,'notification','error1'));
		}
	}catch(PDOException $e){
		echo $e->getMessage();
	}
}


//GET NOTIFICATION

// Delete Notification
function deletenotification () {
	global $conn;
	try{
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
        
		if(isset($_SESSION["userid"])){
			$id = escape_str($_REQUEST["id"]);
            
			$deletestr = "UPDATE ".TABLE_NOTIFICATION." SET `status`= '0' WHERE id = '".$id."'";
			$deletequery = $conn->query($deletestr);
			if($deletequery) {
				 $conn->message(true,$conn->getMessage($lang,'notification','success1'));
			}
		}else{
			$conn->message(false,$conn->getMessage($lang,'notification','error1'));
		}
	}catch(PDOException $e){
		echo $e->getMessage();
	}
}
//GET NOTIFICATION
function getNotification ($bulletin_id)
{
	global $conn;
    $data_arr=array();
    
    if($id!='')
    {
        $data_arr=$conn->getQueryValue("SELECT * FROM ".TABLE_NOTIFICATION."   WHERE id = '".$id."' LIMIT 1");
        $data_arr=(count($data_arr)>0)?$data_arr[0]:array();
    }
    return $data_arr;
}


//GET SENDNOTIFICATIONUSER
function sendNotificationUser ($id)
{
    global $conn;        
    $query_str = "SELECT * FROM `".TABLE_NOTIFICATION."` WHERE id='".$id."'   LIMIT 1"; 
    $query_arr=$conn->getQueryValue($query_str);
    $notificationid=$id;
    if(count($query_arr)>0)
    {
        $notificationtype=$query_arr[0]->notificationtype;
//        $obj=new stdClass();
//        $obj->id=$query_arr[0]->bulletin_id;
//        $obj->bulletin_id=$query_arr[0]->bulletin_id;

        $notificationdata= json_encode(json_decode($query_arr[0]->notificationdata));
        //$notificationtype='5';
        
        $notificationtext=$query_arr[0]->notificationtitle;            
        //ROLE
        if($query_arr[0]->filter_role!='')
        {
            $role_arr=@explode(',',$query_arr[0]->filter_role); 
            if(count($role_arr)>0)
            {
                $user_cond.=" AND role IN (".$query_arr[0]->filter_role.")";
            }                
        }
        //ZONE
        if($query_arr[0]->filter_zone!='')
        {
            $zone_arr=@explode(',',$query_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($query_arr[0]->filter_region!='')
        {
            $region_arr=@explode(',',$query_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($query_arr[0]->filter_dealer!='')
        { 
            $dealer_arr=@explode(',',$query_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.=($query_arr[0]->user_type=='0')?" AND role>7 AND role<14":" AND role=15";      
        
        //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;
            }
			
        
            $data=array('notification_id'=>$query_arr[0]->id,'title'=>$query_arr[0]->notificationtitle,'message'=>$query_arr[0]->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 NOTIFICATION DETAILS
function notificationdetails (){
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            $id = escape_str($_REQUEST["id"]);
        
            //VALIDATION CHECK
            if(!($id!=''  )) $conn->message(false,$conn->getMessage($lang,'notification','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_notification_str = "SELECT * FROM `".TABLE_NOTIFICATION."` WHERE id='".$id."' AND status='1'  LIMIT 1";  
            $check_notification_arr=$conn->getQueryValue($check_notification_str);
            if(!(count($check_notification_arr)>0))
            {
                $conn->message(false,$conn->getMessage($lang,'notification','error3'));
            }       
            
             
            
            $check_notification_arr[0]->filter_role=($check_notification_arr[0]->filter_role!='')?@explode(',',$check_notification_arr[0]->filter_role):array();
            $check_notification_arr[0]->filter_role_name=array();
            $role_data=array();
            if(count($check_notification_arr[0]->filter_role)>0)
            {
                foreach($check_notification_arr[0]->filter_role as $data)
                {
                    $role_data[]=$data_role[$data];
                }
                $check_notification_arr[0]->filter_role_name=$role_data;
            }

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


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

            $filter_dealer_arr=array();
            $check_notification_arr[0]->filter_dealer=($check_notification_arr[0]->filter_dealer!='')?@explode(',',$check_notification_arr[0]->filter_dealer):array();
            if(count($check_notification_arr[0]->filter_dealer)>0)
            {
                $dealer_quotes = array_map("quotes_array", $check_notification_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_notification_arr[0]->filter_dealer=$deal_arr;
            }
        
        
            $arr=$check_notification_arr[0];
            $conn->message(true,$conn->getMessage($lang,'notification','success1'),$arr); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'notification','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'notification','error4'));
	}
}

?>