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


if(isset($_REQUEST["funName"])) {
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
	switch($fun) {
        case "contentlist":
        case "addcontent":
        case "updatecontent":
        case "deletecontent":
        case "uploadcontentfile":    
            $fun();
        break;	
        default:
            $conn->message(false,"PAGE NOT FOUND");exit;
        break;		 
	}
}else
{
      $conn->message(false,"PAGE NOT FOUND");exit;
}

// Supplier List
function contentlist () {
        
	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']);
        $assettopicid = escape_str($_REQUEST['assettopicid']);
        
		if(isset($_SESSION["userid"])) {
			$query_str = "SELECT SQL_CALC_FOUND_ROWS c.*,t.topicname FROM ".TABLE_ASSET_CONTENT." c  LEFT JOIN ".TABLE_ASSET_TOPIC." t ON t.assettopicid=c.assettopicid WHERE c.is_deleted = 0 ";

			// Search
			if (!empty($key)) {
				$query_str.= " and ((t.topicname like '%".$key."%') OR (c.title like '%".$key."%')   ) ";
			}
            
            if (!empty($cateid)) {
				$query_str.= " and  t.cateid='".$cateid."'";
			}
            
            if (!empty($assettopicid)) {
				$query_str.= " and  c.assettopicid='".$assettopicid."'";
			}

			$query_str.= " order by c.contentid ASC ";

			// Pagination
			if (!empty($pn) and !empty($nr)) {
				// Navigation
    			$query_str.= " limit ".(($pn - 1) *  $nr).", ".$nr;
			}
            // echo $query_str;exit;
			$query = $conn->query($query_str);
            //$arr['qry'] = $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);
			
			$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;
				}
			}
        
            if(count($data_arr)>0)
            {
                require (dirname(__FILE__).'/awsfileserver.php'); 
                $s3=awsfileserver::connectS3();
                foreach($data_arr as $skey=>$res_val)
                {                    
                    //$check_str = "SELECT * FROM ".TABLE_USER_COMPLETE_CONTENT." WHERE contentid = '".$res_val->contentid."' LIMIT 1";
                    //$check_query = $conn->query($check_str);                    
                    //$data_arr[$skey]->is_edit=($check_query->rowCount()>0)?"0":"1";   
					$data_arr[$skey]->is_edit=1;					
                    
                    $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;
					}
					
                    $data_arr[$skey]->filetypeid='1';
                    $data_arr[$skey]->file=getContentfile($res_val->contentid,$s3);
                    $data_arr[$skey]->filetypeid=(count($data_arr[$skey]->file)>0)?$data_arr[$skey]->file[0]->filetypeid:'1';
                }
            }
            
			$arr['content'] = $data_arr;
			if(count($arr) != 0){
				//$conn->message(true, $pageData->successMsg[0], $arr);
                $conn->message(true,$conn->getMessage($lang,'content','success1'),$arr );
			}else{
				$conn->message(false,$conn->getMessage($lang,'content','error2'));
			}
		}
		else{
			$conn->message(false,$conn->getMessage($lang,'content','error1'));
		}
	}
	catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'content','error4'));
	}
}

// ADD CONTENT
function addcontent () {
	global $conn;
	try {
        
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
			
			 
            
            $assettopicid = escape_str($_REQUEST["assettopicid"]);
			$title = escape_str($_REQUEST["title"]);
			$description = escape_str($_REQUEST["description"]);
            $uploaddate=CUR_DATE;
            $segment =(isset($_REQUEST["segment"]))?escape_str($_REQUEST["segment"]):0;
        
            if(!($title!='' && $description!=''  ) ){ $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"]);
        
            if(!($assettopicid!='' && $title!='') ){ $conn->message(false, 'FIELDS MISSING');exit; }               
            $filetypeid = escape_str($_REQUEST["filetypeid"]);
             
			$status = 1;      
            //FILE UPLOAD
            if(isset($_FILES['file_en_us']) && $_FILES['file_en_us']['name'])
            {
                $obj = new stdClass();
                $obj->filekey = 'file_en_us';
                $obj->size = '512'; //IN MB
                $obj->type = array('pdf','mp4');	
                $conn->validateFile($obj);			
                $obj->path = "../".S3_TOPICS_URL;
                $obj->filename = 'content_'.date('Ymd')."_".uniqid();			
                $en_us_file = $conn->uploadFile($obj);
                
                $filesize=$_FILES['file_en_us']['size'];
               
                switch($filetypeid)
                {
                    case '1':
                        $filetype='PDF';
                        break;
                    case '2':
                        $filetype='MP4';
                        break;
                }
                
                

                //S3 UPLOAD
                //S3 LIB
                require (dirname(__FILE__).'/awsfileserver.php'); 

                //S3 OBJ
                $s3=awsfileserver::connectS3();
                awsfileserver::checkupload($s3,S3_BUCKET,S3_TOPICS_URL.$en_us_file,dirname(__FILE__)."/../".S3_TOPICS_URL.$en_us_file);

                //DELETE AFTER MOVE TO S3
                @unlink(dirname(__FILE__).'/../'.S3_TOPICS_URL.$en_us_file);
            }else
            {
                $conn->message(false,$conn->getMessage($lang,'content','error3'));	
            }
            
            //FILE UPLOAD
            if(isset($_FILES['thumb_en_us']) && $_FILES['thumb_en_us']['name'])
            {
                $obj = new stdClass();
                $obj->filekey = 'thumb_en_us';
                $obj->size = '10'; //IN MB
                $obj->type = array('jpg','jpeg','png');	
                $conn->validateFile($obj);			
                $obj->path = "../".S3_TOPICS_URL;
                $obj->filename = 'thumbimage_'.date('Ymd')."_".uniqid();			
                $thumb_en_us_file = $conn->uploadFile($obj);
                
                $filesize=$_FILES['thumb_en_us']['size'];
               
                //S3 UPLOAD
                //S3 LIB
                require_once (dirname(__FILE__).'/awsfileserver.php'); 

                //S3 OBJ
                $s3=awsfileserver::connectS3();
                awsfileserver::checkupload($s3,S3_BUCKET,S3_TOPICS_URL.$thumb_en_us_file,dirname(__FILE__)."/../".S3_TOPICS_URL.$thumb_en_us_file);

                //DELETE AFTER MOVE TO S3
                @unlink(dirname(__FILE__).'/../'.S3_TOPICS_URL.$thumb_en_us_file);
            }else
            {
                $conn->message(false,$conn->getMessage($lang,'content','error5'));	
            }
        
			$insert = "INSERT INTO ".TABLE_ASSET_CONTENT." (`assettopicid`,segment, `title`, `description`, `uploaddate`, `filter_role`, `filter_zone`, `filter_region`, `filter_dealer`, `version`, `status`, `is_deleted`, `created_on`, `modified_on`) VALUES ('".$assettopicid."','".$segment."','".$title."','".$description."','".$uploaddate."','".$filter_role."','".$filter_zone."','".$filter_region."','".$filter_dealer."','1','".$status."','0','".NOW."','".NOW."')";
            $insertquery = $conn->query($insert);
            $contentid = $conn->lastinsetid();
                    
            //DEFAULT ENGLISH FILE UPLOAD
            $insert_file = "INSERT INTO ".TABLE_ASSET_FILE." ( `contentid`, `language_id`, `filepath`, `thumbpath`, `filetypeid`, `filetype`, `filesize`, `filequality`, `created_on`, `modified_on`) VALUES ('".$contentid."','1','".$en_us_file."','".$thumb_en_us_file."','".$filetypeid."','".$filetype."','".$filesize."','HIGH','".NOW."','".NOW."')";
            $insertquery = $conn->query($insert_file);
            
			 
            //SEND NOTIFICATION
            sendContentNotification ($contentid);
             
        
            $conn->message(true,$conn->getMessage($lang,'content','success1'),getContent($contentid));        
		}else{
			$conn->message(false,$conn->getMessage($lang,'content','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$e->getMessage());
	}
}

// UPDATE  CONTENT
function updatecontent () {
	global $conn;
	try {
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            $contentid = escape_str($_REQUEST["contentid"]);
            
			$assettopicid = escape_str($_REQUEST["assettopicid"]);
			$title = escape_str($_REQUEST["title"]);
			$description = escape_str($_REQUEST["description"]);
            $uploaddate=CUR_DATE;      
            $segment =(isset($_REQUEST["segment"]))?escape_str($_REQUEST["segment"]):0;
            
            //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"]);
            
            if(!($contentid!='' && $assettopicid!=''   && $title!='') ){ $conn->message(false, 'FIELDS MISSING');exit; }               
        
            $query_str = "SELECT contentid FROM ".TABLE_ASSET_CONTENT." WHERE contentid = '".$contentid."'  AND is_deleted='0' LIMIT 1";
            $query = $conn->query($query_str);
            $arr = $query->fetchAll(PDO::FETCH_OBJ);
        
            if(count($arr)== 1)
            {       
                $update_str = "UPDATE ".TABLE_ASSET_CONTENT." SET `assettopicid`='".$assettopicid."',segment='".$segment."',`title`='".$title."', `description`='".$description."', `uploaddate`='".CUR_DATE."', `filter_role`='".$filter_role."', `filter_zone`='".$filter_zone."', `filter_region`='".$filter_region."', `filter_dealer`='".$filter_dealer."', `version`=version+1  ,`modified_on`='".NOW."' WHERE contentid = '".$contentid."'";

                $conn->query($update_str);
                $conn->message(true,$conn->getMessage($lang,'content','success1'),getContent ($contentid));
            }
            else
            {
                $conn->message(false,$conn->getMessage($lang,'content','error5'));
            }
        }else{
			$conn->message(false,$conn->getMessage($lang,'content','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'content','error4'));
	}
}

// DELETE CONTENT
function deletecontent () {
	global $conn;
	try{
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
        
		if(isset($_SESSION["userid"])){
			$contentid = escape_str($_REQUEST["contentid"]);
            
			$deletestr = "UPDATE ".TABLE_ASSET_CONTENT." SET `is_deleted` = '1' WHERE contentid = '".$contentid."' ";
			$deletequery = $conn->query($deletestr);
			if($deletequery) {
				 $conn->message(true,$conn->getMessage($lang,'content','success1'));
			}
		}else{
			$conn->message(false,$conn->getMessage($lang,'content','error1'));
		}
	}catch(PDOException $e){
		echo $e->getMessage();
	}
}

function uploadcontentfile()
{
    global $conn;
    try {
        
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
                    
		if(isset($_SESSION["userid"]))
        {            
            $contentid = escape_str($_REQUEST["contentid"]);
                    
            if(!($contentid!='') ){ $conn->message(false, 'CONTENT ID MISSING');exit; }               
            
            $filetypeid = escape_str($_REQUEST["filetypeid"]);
            $language_id = escape_str($_REQUEST["language_id"]);
            
            //CHECK LANGUAGE
            $query_str = "SELECT * FROM ".TABLE_MASTER_LANGUAGE." WHERE language_id = '".$language_id."'  AND is_deleted='0' LIMIT 1";
            $query = $conn->query($query_str);
            $langarr = $query->fetchAll(PDO::FETCH_OBJ);
            
            if(!(count($langarr)>0))
            {
                 $conn->message(false,$conn->getMessage($lang,'content','error8'));	
            }
            
            switch($filetypeid)
            {
                case '1':
                    $filetype='PDF';
                    break;
                case '2':
                    $filetype='MP4';
                    break;
            }
            
            //CHECK CONTENT EXIT
            $query_str = "SELECT contentid FROM ".TABLE_ASSET_CONTENT." WHERE contentid = '".$contentid."'  AND is_deleted='0' LIMIT 1";
            $query = $conn->query($query_str);
            $arr = $query->fetchAll(PDO::FETCH_OBJ);
            
            $query_str = "SELECT * FROM ".TABLE_ASSET_FILE." WHERE language_id = '".$language_id."' AND contentid = '".$contentid."' LIMIT 1";
            $query = $conn->query($query_str);
            $filearr = $query->fetchAll(PDO::FETCH_OBJ);
            
            
            if(count($arr)== 1)
            {
                if(count($filearr)>0)
                {
                    if((!(isset($_FILES['file']) && $_FILES['file']['name']))  && (!(isset($_FILES['thumb']) && $_FILES['thumb']['name'])))
                    {
                        $conn->message(false,$conn->getMessage($lang,'content','error3'));	
                    }
                    if($filearr[0]->filetypeid!=$filetypeid){    $conn->message(false,$conn->getMessage($lang,'content','error7'));	  }
                
                }else
                {
                    if(!(isset($_FILES['file']) && $_FILES['file']['name']))
                    {
                        $conn->message(false,$conn->getMessage($lang,'content','error3'));	
                    }
                    if(!(isset($_FILES['thumb']) && $_FILES['thumb']['name']))
                    {
                        $conn->message(false,$conn->getMessage($lang,'content','error5'));	
                    }
                }
               
                //FILE UPLOAD
                $file='';
                $thumb_file='';
                if(isset($_FILES['file']) && $_FILES['file']['name'])
                {
                    $obj = new stdClass();
                    $obj->filekey = 'file';
                    $obj->size = '512'; //IN MB
                    $obj->type = array('pdf','mp4');	
                    $conn->validateFile($obj);			
                    $obj->path = "../".S3_TOPICS_URL;
                    $obj->filename = 'content_'.date('Ymd')."_".uniqid();			
                    $file = $conn->uploadFile($obj);

                    $filesize=$_FILES['file']['size'];

                    //S3 UPLOAD
                    //S3 LIB
                    require (dirname(__FILE__).'/awsfileserver.php'); 

                    //S3 OBJ
                    $s3=awsfileserver::connectS3();
                    awsfileserver::checkupload($s3,S3_BUCKET,S3_TOPICS_URL.$file,dirname(__FILE__)."/../".S3_TOPICS_URL.$file);

                    //DELETE AFTER MOVE TO S3
                    @unlink(dirname(__FILE__).'/../'.S3_TOPICS_URL.$file);
                } 
                //FILE UPLOAD
                if(isset($_FILES['thumb']) && $_FILES['thumb']['name'])
                {
                    $obj = new stdClass();
                    $obj->filekey = 'thumb';
                    $obj->size = '10'; //IN MB
                    $obj->type = array('jpg','jpeg','png');	
                    $conn->validateFile($obj);			
                    $obj->path = "../".S3_TOPICS_URL;
                    $obj->filename = 'thumbimage_'.date('Ymd')."_".uniqid();			
                    $thumb_file = $conn->uploadFile($obj);

                    //S3 UPLOAD
                    //S3 LIB
                    require_once (dirname(__FILE__).'/awsfileserver.php'); 

                    //S3 OBJ
                    $s3=awsfileserver::connectS3();
                    awsfileserver::checkupload($s3,S3_BUCKET,S3_TOPICS_URL.$thumb_file,dirname(__FILE__)."/../".S3_TOPICS_URL.$thumb_file);

                    //DELETE AFTER MOVE TO S3
                    @unlink(dirname(__FILE__).'/../'.S3_TOPICS_URL.$thumb_file);
                } 
                 
                $filecond='';
                if(count($filearr)>0)
                {
                    $filecond.=($file!='')?"  `filepath` ='".$file."',  `filesize`= '".$filesize."',":'';
                    $filecond.= ($thumb_file!='')?" `thumbpath` ='".$thumb_file."',":'';
                    $update_file = "UPDATE ".TABLE_ASSET_FILE." SET  ".$filecond."  `modified_on`='".NOW."' WHERE id='".$filearr[0]->id."'";
                    $conn->query($update_file); 
                    if($file!='')
                    {
                
                        //DELETE OLD FILE
                        //awsfileserver::deleteobject($s3,S3_BUCKET,S3_TOPICS_URL.$filearr[0]->filepath);
                    }
                    if($thumb_file!='')
                    {
                
                        //DELETE OLD FILE
                        //awsfileserver::deleteobject($s3,S3_BUCKET,S3_TOPICS_URL.$filearr[0]->thumbpath);
                    }
                   
                }else{
                    //INSERT FILE
                    $insert_file = "INSERT INTO ".TABLE_ASSET_FILE." ( `contentid`, `language_id`, `filepath`, `thumbpath`, `filetypeid`, `filetype`, `filesize`, `filequality`, `created_on`, `modified_on`) VALUES ('".$contentid."','".$language_id."','".$file."','".$thumb_file."','".$filetypeid."','".$filetype."','".$filesize."','HIGH','".NOW."','".NOW."')";                        $conn->query($insert_file);  
                }
                
 
                $conn->message(true,$conn->getMessage($lang,'content','success1'));     
            }else
            {
                $conn->message(false,$conn->getMessage($lang,'content','error6'));
            }
		}else{
			$conn->message(false,$conn->getMessage($lang,'content','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'content','error4'));
	}
}

//GET CONTENT
function getContent ($contentid)
{
	global $conn;
    $data_arr=array();
    if($contentid!='')
    {       
        $data_arr=$conn->getQueryValue("SELECT c.*,t.topicname FROM ".TABLE_ASSET_CONTENT." c  LEFT JOIN ".TABLE_ASSET_TOPIC." t ON t.assettopicid=c.assettopicid WHERE c.contentid = '".$contentid."' LIMIT 1");
        //$data_arr=(count($data_arr)>0)?$data_arr[0]:array();
        
        if(count($data_arr)>0)
        {
            $check_str = "SELECT * FROM ".TABLE_USER_COMPLETE_CONTENT." WHERE contentid = '".$data_arr[0]->contentid."' LIMIT 1";
            $check_query = $conn->query($check_str);                    
            $data_arr[0]->is_delete=($check_query->rowCount()>0)?"0":"1";     

            $data_arr[0]->filter_role=($data_arr[0]->filter_role!='')?@explode(',',$data_arr[0]->filter_role):array();
            $data_arr[0]->filter_zone=($data_arr[0]->filter_zone!='')?@explode(',',$data_arr[0]->filter_zone):array();
            $data_arr[0]->filter_region=($data_arr[0]->filter_region!='')?@explode(',',$data_arr[0]->filter_region):array();
            $data_arr[0]->filter_dealer=($data_arr[0]->filter_dealer!='')?@explode(',',$data_arr[0]->filter_dealer):array();
            
            $data_arr[0]->file=getContentfile($data_arr[0]->contentid,$s3);            
            $data_arr[0]->filetypeid=(count($data_arr[0]->file)>0)?$data_arr[0]->file[0]->filetypeid:'1';
        }else
        {
            $data_arr=array();
        }        
        
    }
    return $data_arr;
}

// GET CONTENT FILE
function getContentfile ($contentid,$s3=null)
{
	global $conn;
    $data_arr=array();
    if($contentid!='')
    {       
        $data_arr=$conn->getQueryValue("SELECT f.* FROM ".TABLE_ASSET_FILE." as f JOIN ".TABLE_MASTER_LANGUAGE." as l ON f.language_id=l.language_id  WHERE f.contentid = '".$contentid."' ");
        //$data_arr=(count($data_arr)>0)?$data_arr[0]:array();
        
        if(count($data_arr)>0)
        {
            if(!$s3)
            {
                require_once (dirname(__FILE__).'/awsfileserver.php'); 
                $s3=awsfileserver::connectS3();
            }
            
            foreach($data_arr as $key=>$res_val)
            {
                $filepath_url='';
                if($res_val->filepath!='')
                { 
                    $obj = new stdClass();
                    $obj->key_name=S3_TOPICS_URL.$res_val->filepath;			
                    $url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                    $filepath_url=$url;
                }
                $data_arr[$key]->filepath_url=$filepath_url;
                
                $thumbpath_url='';
                if($res_val->thumbpath!='')
                { 
                    $obj = new stdClass();
                    $obj->key_name=S3_TOPICS_URL.$res_val->thumbpath;			
                    $url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                    $thumbpath_url=$url;
                }
                $data_arr[$key]->thumbpath_url=$thumbpath_url;
                
            }
        }else
        {
            $data_arr=array();
        }        
        
    }
    return $data_arr;
}

//SEND CONTENT NOTIFICATION
function sendContentNotification ($contentid)
{
    global $conn;    
    $content_str = "SELECT a.*,t.user_type FROM `".TABLE_ASSET_CONTENT."` a join ".TABLE_ASSET_TOPIC." t ON  a.assettopicid=t.assettopicid WHERE a.contentid='".$contentid."' AND a.status='1' AND a.is_deleted='0' LIMIT 1"; 
    $content_arr=$conn->getQueryValue($content_str);

    if(count($content_arr)>0)
    {
        $obj=new stdClass();
        $obj->id=$content_arr[0]->contentid;
        $obj->contentid=$content_arr[0]->contentid;
        $obj->assettopicid=$content_arr[0]->assettopicid;
        $notificationdata= json_encode($obj);
        $notificationtype='1';

        $notificationtitle='New Content published '.$content_arr[0]->title;
        $notificationtext='New Content published '.$content_arr[0]->title;
        
        $user_cond='';
        //ROLE
        if($content_arr[0]->filter_role!='')
        {
            $role_arr=@explode(',',$content_arr[0]->filter_role); 
            if(count($role_arr)>0)
            {
                $user_cond.=" AND role IN (".@implode(',',$role_arr).")";
            }                
        }
        //ZONE
        if($content_arr[0]->filter_zone!='')
        {
            $zone_arr=@explode(',',$content_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($content_arr[0]->filter_region!='')
        {
            $region_arr=@explode(',',$content_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($content_arr[0]->filter_dealer!='')
        { 
            $dealer_arr=@explode(',',$content_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.=($content_arr[0]->user_type=='0')?" AND role>7 AND role<14":" AND role=15";   
        switch ($content_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 role>2 AND 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($notificationtitle)."','".escape_str($notificationtext)."','".$notificationdata."','".$notificationtype."', '1','".NOW."','".NOW."','".NOW."')");

            $notificationid=$conn->lastinsetid();
            $data=array('notification_id'=>$notificationid,'title'=>$notificationtitle,'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);
                }
                
            }
        }
    }    
}


?>