<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: PushNotificationModel, v 1.0 2016/03/01 16:55:11
//All functions 
//
class PushNotificationModel extends Model{

public function listPushNotification($params=array()){
	extract($params);
	if ($limitTo)
		$selectFields .= " SQL_CALC_FOUND_ROWS ";	
	$sql=" 
		SELECT 
			".$selectFields."
			*
		FROM 
				".DB_PREFIX. "push_notifications AS pushnotification
               LEFT JOIN `" . DB_PREFIX . "push_notification_details` AS pushnotificationDet 
							ON (
								pushnotificationDet.notification_id = pushnotification.notification_id
								AND pushnotificationDet.languageID =" . (int) $languageIDs['Content'] . "
							)  
                                
		WHERE
			1
	";			
			if(isset($notification_title) && $notification_title!=''){
				$sql.= "
					AND
					pushnotificationDet.notification_title like '%".$this->escape($notification_title)."%'
					";
			}			
			if(isset($short_description) && $short_description!=''){
				$sql.= "
					AND
					pushnotificationDet.short_description ='".$short_description."'
					";
			}			
			if(isset($notification_image) && $notification_image!=''){
				$sql.= "
					AND
					pushnotificationDet.notification_image like '%".$this->escape($notification_image)."%'
					";
			}		
			if(isset($device_type) && $device_type!=''){
				$sql.= "
					AND
					pushnotification.device_type ='".$device_type."'
					";
			}			
			if(isset($status) && $status!=''){
				$sql.= "
					AND
					pushnotification.status ='".$status."'
					";
			}else {
				$sql.= "
					AND
					pushnotification.status !='delete'
					";
			}	

if($orderby && $sortby){
	$sql.="
		ORDER BY
			".substr($sortby, 5)." ".$orderby."
	";
}
if ($limitTo){
	$sql .= " 
	LIMIT  
		" . $limitFrom . ",
		" . $limitTo . "
	";
}
//echo $sql;exit;
return  $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
}

public function getPushNotification($params=array()){
	extract($params);
	$sql=" 
		SELECT 
			".$selectFields."
			*
		FROM 
				".DB_PREFIX. "push_notifications AS pushnotification
                LEFT JOIN `" . DB_PREFIX . "push_notification_details` AS pushnotificationDet 
							ON (
								pushnotificationDet.notification_id = pushnotification.notification_id
								AND pushnotificationDet.languageID =" . (int) $languageIDs['Content'] . "
							)                       
		WHERE
			pushnotification.notification_id = '".$notification_id."'
	";	

	$sql .= " 
	LIMIT  
		1
	";
	return  $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
		
}

public function changeStatus($params=array()){
	extract($params);
	$sql="
		UPDATE  
			".DB_PREFIX. "push_notifications 
		SET 
			status = '".$status."' 
		WHERE
			notification_id IN ('".implode("','",$notification_ids)."')
		";
	$this->ObjDatabase->setQuery($sql);	
			
}

public function insert($languageIDs,$notification_id=0){
$date	= date('Y-m-d H:i:s');
	if($notification_id>0){
                $sql="
			UPDATE 
				".DB_PREFIX. "push_notifications
			SET
				isAndroid = '".$this->escape($_POST['isAndroid'])."',isIphone = '".$this->escape($_POST['isIphone'])."'
			WHERE
				notification_id = '".$notification_id."'
		";
		$this->ObjDatabase->setQuery($sql);
                if ($this->isPushnotifWithLanguageIDExists($languageIDs['Current'], $notification_id)) {
                    $sql="
                            UPDATE 
                                    ".DB_PREFIX. "push_notification_details
                            SET
                                    notification_title = '".$this->escape($_POST['notification_title'])."',short_description = '".$this->escape($_POST['short_description'])."',notification_image = '".$this->escape($_POST['notification_image'])."'
                            WHERE
                                    notification_id = '".$notification_id."' AND languageID='".$languageIDs['Content']."'
                    ";
                    //echo $sql;exit;
                    $this->ObjDatabase->setQuery($sql);
                } else {
                    $sql = "
					INSERT INTO " . DB_PREFIX . "push_notification_details (
						`notification_title`,
                                                `notification_id`,
						`languageID`,
						`short_description`,
                                                `notification_image`
					) 
					VALUES 
						(
						'" . $this->escape($_POST['notification_title']) . "',
                                                '" . $notification_id . "',    
						'" . $languageIDs['Content'] . "',
						'" . $this->escape($_POST['short_description']) . "',
                                                '" . $this->escape($_POST['notification_image']) . "'
						)";
                $this->ObjDatabase->setQuery($sql);
                }
	}
	else{
           
              $allLanguages   = $languageIDs['AllList'];
              
              $sql="
			INSERT INTO ".DB_PREFIX. "push_notifications 
				(				createdDate,status,isAndroid,isIphone
				)
			VALUES
				(
				'".$date."','pending','".$this->escape($_POST['isAndroid'])."','".$this->escape($_POST['isIphone'])."'
				)
			";
		$this->ObjDatabase->setQuery($sql);	
		$notification_id = $this->ObjDatabase->getInsertId();
                foreach ($allLanguages as $language) {
                    $sql = "
                                            INSERT INTO " . DB_PREFIX . "push_notification_details (
                                                    `notification_title`,
                                                    `notification_id`,
                                                    `languageID`,
                                                    `short_description`,
                                                    `notification_image`
                                            ) 
                                            VALUES 
                                                    (
                                                    '" . $this->escape($_POST['notification_title']) . "',
                                                    '" . $notification_id . "',    
                                                    '" . $language . "',                                                    
                                                    '" . $this->escape($_POST['short_description']) . "',
                                                    '" . $this->escape($_POST['notification_image']) . "'
                                                    )";                    
                    $this->ObjDatabase->setQuery($sql);
                }
		
	}
	return $notification_id;
			
}
 function isPushnotifWithLanguageIDExists($currentLanguageID, $notification_id) {
        $sql              = "
					SELECT 
						* 
					FROM 
						`" . DB_PREFIX . "push_notification_details` 
					WHERE 
						`languageID` = '" . $currentLanguageID . "' 
						AND 
						`notification_id` = '" . $notification_id . "'";
        $resSelectProduct = $this->ObjDatabase->numberOfRecords($sql);
        if ($resSelectProduct)
            return true;
        else
            return false;
    }
public function sendpushnotification(){
    
    
        $sql = "SELECT
			pushdev.id,
			pushnotify.notification_id,
			NOW(),
			'unread'
		FROM 
				(SELECT * FROM ".DB_PREFIX. "push_devicetoken GROUP BY deviceToken) AS pushdev
		JOIN
				".DB_PREFIX. "push_notifications AS pushnotify
		WHERE
			pushnotify.status = 'pending'
			AND 
			pushdev.status ='enable'";
        $res = $this->ObjDatabase->readValues($sql);	
        
        if(!empty($res)) {
            foreach($res as $data) {
                $sqlCheck = "select * from ".DB_PREFIX. "notification_to_devices where id='".$data['id']."' and notificationID='".$data['notification_id']."'";
                
                $resCheck = $this->ObjDatabase->readValue($sqlCheck);
                if(empty($resCheck)) {
                    $sqlInsert="
                            INSERT INTO ".DB_PREFIX. "notification_to_devices
                                    (id,notificationID,date,status) values('".$data['id']."','".$data['notification_id']."',NOW(),'unread')";	
                   
                    $this->ObjDatabase->setQuery($sqlInsert);
                } 
        }
    }
}
public function cleanpushnotification(){
	$sql="
				DELETE 
				FROM 
					".DB_PREFIX. "notification_to_devices
				WHERE 
					date < NOW() - INTERVAL 2 WEEK ";
			
	$this->ObjDatabase->setQuery($sql);	
}
public function getpushnotificationfrontend($device,$type='',$languageIDs=array()){
    if(!empty($languageIDs)) {
        $currentLangID= $languageIDs['Current'];
    } else {
        $currentLangID= 1;
    }
	$sql="
		SELECT
			pushdev.id,
			pushnotify.notification_id,
			pushdev.deviceToken,
			DATE_FORMAT(pushnotify.notification_sent_date,'%d %b %Y') AS notification_sent_date, 
			pushnotifydet.notification_title,
			pushnotifydet.notification_image,
			pushnotifydet.short_description
		FROM 
				".DB_PREFIX. "notification_to_devices notify
		LEFT JOIN	".DB_PREFIX. "push_notifications AS pushnotify
			ON(
					pushnotify.notification_id=notify.notificationID					
			   )
                           LEFT JOIN	".DB_PREFIX. "push_notification_details AS pushnotifydet
			ON(
					pushnotifydet.notification_id=pushnotify.notification_id and pushnotifydet.languageID='".$currentLangID."'					
			   )
		LEFT JOIN	".DB_PREFIX. "push_devicetoken AS pushdev
			ON(
					pushdev.id=notify.id 
			   )
		WHERE 
			pushnotify.status = 'pending' 
			AND pushdev.status='enable' AND ";
		if ($device =='android')
		{
			$sql.= " 
			pushdev.deviceType = 'android'
			AND
			pushnotify.isAndroid ='yes'";
		}
		if ($device =='iphone')
		{
			$sql.= "
			pushdev.deviceType = 'iPhone'
			AND
			pushnotify.isIphone ='yes' 
			
                ";
                        
                }
                   if ($type !='')
		{
			$sql.= "
			and pushnotify.notification_id='".$type."' ";
			
		
		}
                
		return $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
}
	public function setpushnotificationStatus($notificationIds) {
	$sql="
			UPDATE 
				".DB_PREFIX. "push_notifications 
			SET
				notification_sent_date = NOW(),status = 'sent'
			WHERE
				status = 'pending'
				AND notification_id IN ('".implode("','",$notificationIds)."') ";
	
	$this->ObjDatabase->setQuery($sql);
}	

public function getUserDeviceToken($userId,$type){
    
    $sql = " SELECT `deviceToken` FROM `".DB_PREFIX. "push_devicetoken` WHERE `userID`='$userId' AND `deviceType`='$type' AND `status`='enable' ";
    
    $token= $this->ObjDatabase->readValues($sql);
    return $token;
}
public function getBusinessTokens($businessID,$type){
    
    $sql = " SELECT `deviceToken` FROM `".DB_PREFIX. "push_business_devicetoken` WHERE `userID`='$businessID' AND `deviceType`='$type' AND `status`='enable' ";
    
    $token= $this->ObjDatabase->readValues($sql);
    return $token;
}

}
		