<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
global $server;

# ---------------------------------------------------------------------
#  Add all cron scripts here
#  This script will be executed each time cron job is executed
#----------------------------------------------------------------------

if(!function_exists("transplateError")) {
	function transplateError($respomn) {
		$healthy = ["1703", "1704", "1705", "1707", "1708", "1709", "1711", "1713", "1712"];
		$yummy   = ["Invalid recipient recipient", "Invalid Sender ID", "Sender ID not allowed", "Server unavailable", "server unavailable", "Server busy", "Gateway error. Contact support", "Message blocked by Network", "Sender ID blocked by Network"];
		$newPhrase = str_replace($healthy, $yummy, $respomn);
		return $newPhrase;
	}
}
		
//apply delay
if(isset($_REQUEST['delay']) && is_numeric($_REQUEST['delay'])) {
    $delay = round($_REQUEST['delay']);
    sleep($delay);
}

function getLastProcessedMessage() {
    global $server;
    $query="SELECT id FROM messagedetails WHERE (status = 'queued' OR status = 'Queued') ORDER BY id ASC LIMIT 1"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result);
	return $row['id']+0;
}
mysqli_query($server, "UPDATE settings SET `value` = '".time()."' WHERE `field` = 'lastMinuteCron'");
//update invalid customers
$currency_id = getSetting('defaultCurrency',0); 
mysqli_query($server, "UPDATE  `users` SET  `currency_id` =  '$currency_id' WHERE `currency_id` = '0' LIMIT 50");

logEvent(0,'Minute cron started');

$limit = 100;
if(getSetting('sendRate',0)>0) { 
	$limit = getSetting('sendRate',0);
}

//update pagination
$getLastProcessedMessage = getLastProcessedMessage();
if(isset($_GET['lst'])) {
    echo $getLastProcessedMessage; 
}
$oldCronPage = getSetting('LastCronPage',0);
if(empty($oldCronPage) || $oldCronPage <1) {
    $oldCronPage = getLastProcessedMessage();
}

$LastCronPage = $oldCronPage + $limit;

if($oldCronPage > 0) {
    logEvent(0,'Processing queued messages '.$oldCronPage.' - '.$LastCronPage);
    $query="SELECT * FROM messagedetails WHERE (status = 'queued' OR status = 'Queued') AND id >= $oldCronPage ORDER BY id ASC LIMIT $limit;";    
    if(isset($_REQUEST['gateway_id']) && is_numeric($_REQUEST['gateway_id'])) {;
        $gateway_id = mysqli_real_escape_string($server,$_REQUEST['gateway_id']);	
        $query="SELECT * FROM messagedetails WHERE (status = 'queued' OR status = 'Queued') AND id >= $oldCronPage AND gateway_id = '$gateway_id' ORDER BY id ASC LIMIT $limit;";    
    }
    if(isset($_REQUEST['customer_id']) && is_numeric($_REQUEST['customer_id'])) {
        $customer_id = 	mysqli_real_escape_string($server,$_REQUEST['customer_id']);
        $query="SELECT * FROM messagedetails WHERE (status = 'queued' OR status = 'Queued') AND id >= $oldCronPage AND customer_id = '$customer_id' ORDER BY id ASC LIMIT $limit;";    
    }
    if(isset($_GET['lst'])) {
        echo '<br>'.$query; die();
    }
    $result = mysqli_query($server,$query) or die(mysqli_error($server));
    $countnh = mysqli_num_rows($result);
    if($countnh > 0) {
        if($countnh < $limit) {
            $LastCronPage = $oldCronPage + $countnh;
        }
        saveSettings('LastCronPage',$LastCronPage,0);
    } else {
        saveSettings('LastCronPage',$getLastProcessedMessage,0);
    }
	$toosP = $toosT = array();
	$costssP = $costssT = array();
	$IDsP = $IDsT = array();
    while($rows = mysqli_fetch_assoc($result)) { 
		$pageCount = countPage($rows['message'],$rows['type'],$rows['duration']);
		$cost = smsCost($rows['recipient'],$rows['type'],$rows['country_id'],$pageCount,$rows['customer_id'],$rows['gateway_id']);
    	//create hook variables
    		$vars = array(
    					 "id"=>$rows['id'], 
    					 "sender_id"=>$rows['sender_id'], 
    					 "to"=>$rows['recipient'],
    					 "gateway_id"=>$rows['gateway_id'],
    					 "message"=>$rows['message'], 
    					 "customer_id"=>$rows['customer_id'],
    					 "type"=>$rows['type'], 
    					 "media"=>$rows['media']
    					 );
    		$_SESSION['EventVals'] = $vars;
    	global $hooks; $hooks->do_action('BeforeProcessMessage');
		$groupID = $rows['message'];
		$bulkMessage = $rows['message'];
		$bulkSenderID = $rows['sender_id'];
		if($rows['gateway_id'] == 6) {	//transactional
			$costssT[] = $cost;
			$toosT[] = $rows['recipient'];
			$IDsT[] = $rows['id'];
		} else if($rows['gateway_id'] == 57) {  //premium
			$costssP[] = $cost;
			$toosP[] = $rows['recipient'];
			$IDsP[] = $rows['id'];
		} else {
    		sendSMS($rows['id']);
		}
    	$hooks->do_action('AfterMessageProcess');
    }
	// send bulk message 
	if(count($toosP) > 0) {
		$to = implode(",",$toosP);
		$base_url = "https://kullsms.com/customer/api/?username=care@ynetinteractive.com&password=8Yh45nRTuwQ";
		$base_url = "https://kullsms.com/customer/api/?response=json&username=care@ynetinteractive.com&password=8Yh45nRTuwQ";
		$success_word = '1701';
		$request_type = 'POST';
		$authentication = 0;

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,"https://kullsms.com/customer/api/");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, 
				  http_build_query(array('username' => 'care@ynetinteractive.com',
										'password' => '8Yh45nRTuwQ',
										'response' => 'json',
										'sender' => $bulkSenderID,
										'mobiles' => $to,
										'message' => "$bulkMessage")));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$response = curl_exec($ch);
		if(curl_error($ch)) {
			$response = curl_error($ch);	
		}
		curl_close ($ch);
		if(!$response) {
			$status = 'Connection to Gateway Failed.';  //. curl_error($ch)
			$ids = explode(',', $IDsP);
			foreach($ids as $message_id){
				if($id > 0) {
					mysqli_query($server, "UPDATE  `messagedetails` SET `status` = 'failed', 	`cost` = '0', `dlr` = 'failed', 	`notice` = '$status' WHERE `id` = '$message_id'");
				}
			}
		} else {
			 	$responses = json_decode($response,true);
				$response = $responses['result'];
				$datetime = date("Y-m-d H:i:s",time());
				if((stripos(strtolower($response),strtolower($success_word)) !== false)) {
					$Gcost = $responses['cost'];
					$Gcost = correctNumber($Gcost);
					$status = 'sent';
				   if($Gcost > 3.2 && $cost < 4) {
					   $cost = 4.43;
				   }
				   	mysqli_query($server, "UPDATE  `messagedetails` SET `status` = 'sent', 
					`cost` = '$cost', 
					`datetime` = '$datetime', 
					`dlr` = 'sent' WHERE `message_id` = '$groupID' AND recipient = '$mobile'");	
			   } else {
				  $status = transplateError($response);
				  $status = mysqli_real_escape_string($server,$status);
				  mysqli_query($server, "UPDATE  `messagedetails` SET `status` = 'failed', 
				  `cost` = '0', 
				  `dlr` = 'failed', 
				  `notice` = '$status' WHERE `message_id` = '$groupID' AND recipient = '$mobile'");
			   }
		}
		
	} //end count toosP
}

//process pending messages
$query="SELECT * FROM sentmessages WHERE (status = 'queued' OR status = 'Queued') ORDER BY id ASC LIMIT 6";
$result = mysqli_query($server,$query) or error_log(mysqli_error($server));
while($rows = mysqli_fetch_assoc($result)) { 
	mysqli_query($server, "UPDATE sentmessages SET `status` = 'processing' WHERE `id` = '".$rows['id']."'");
	mysqli_query($server, "UPDATE sentmessages SET `sent_on` = '".date('Y-m-d H:i:s')."' WHERE `id` = '".$rows['id']."'");
	//correct media url
	if( strpos($rows['media'],'undefined' ) !== false) {
		$new_media = str_replace('undefined', '', $rows['media']);
		mysqli_query($server, "UPDATE sentmessages SET `media` = '$new_media' WHERE `id` = '".$rows['id']."'");
	}
	$to = $rows['recipients'];
	$countryCode = countryPhoneCode($rows['country']);
	if(!empty($rows['file'])) {
		$to .= ','.getFileContacts($rows['file']);
	}
	if(!empty($rows['phonebook_id'])) {
		$addressbook = explode(',', $rows['phonebook_id']);
		foreach ($addressbook as $list){
			$to .= ','.getContacts($list,'phonebook');	
		}
	}
	$tos = explode(',', $to);
	foreach($tos as $recipient){
		if(!empty($recipient)) {
			$recipient = str_replace('+', '', $recipient);
			$recipient = alterPhone($recipient,$countryCode);
			$datetime = date('Y-m-d H:i:s');
			$now = time();
			$country = getDestinationCountry($recipient);
			$gateway_id = getDestinationRoute($rows['type'],$recipient,$rows['customer_id'],$rows['gateway_id']);
			//just incase...
			mysqli_query($server, "DELETE FROM messagedetails WHERE message_id = '$rows[id]' AND recipient = '$recipient'");
			
			mysqli_query($server, "INSERT INTO messagedetails (`message_id`, `message`,`recipient`, `customer_id`, `type`, `media`, `date`, `sender_id`, `marketinglist_id`, `duration`, `datetime`,`country_id`, `operator`, `status`, `gateway_id`, `notice`, `cost`, `language`) 
			VALUES ('$rows[id]', '".mysqli_real_escape_string($server,$rows['message'])."','$recipient', '$rows[customer_id]', '$rows[type]', '$rows[media]', '$now', '".mysqli_real_escape_string($server,$rows['sender_id'])."', '0', '$rows[duration]', '$datetime','$country', 'Unknown', 'queued',  '$gateway_id', '', '0', '$rows[language]');"); $error = mysqli_error($server);
		}
	} 
	if(!empty($rows['marketinglist_id'])) {
		$to='';
		$marketinglist_id = explode(',', $rows['marketinglist_id']);
		foreach ($marketinglist_id as $list){
			$to .= ','.getContacts($list,'marketing');	
		}
		$tos = explode(',', $to);
		foreach($tos as $recipient){
			if(!empty($recipient)) {
				$recipient = str_replace('+', '', $recipient);
				$recipient = alterPhone($recipient,$countryCode);
				$datetime = date('Y-m-d H:i:s');
				$now = time();
				$country = getDestinationCountry($recipient);
				$gateway_id = getDestinationRoute($rows['type'],$recipient,$rows['customer_id'],$rows['gateway_id']);
				//just incase...
				mysqli_query($server, "DELETE FROM messagedetails WHERE message_id = '$rows[id]' AND recipient = '$recipient'");
				
				mysqli_query($server, "INSERT INTO messagedetails (`message_id`, `message`,`recipient`, `customer_id`, `type`, `media`, `date`, `sender_id`, `marketinglist_id`, `duration`, `datetime`,`country_id`, `operator`, `status`, `gateway_id`, `notice`, `cost`, `language`) 
				VALUES ('$rows[id]', '".mysqli_real_escape_string($server,$rows['message'])."','$recipient', '$rows[customer_id]', '$rows[type]', '$rows[media]', '$now', '".mysqli_real_escape_string($server,$rows['sender_id'])."', '$list', '$rows[idduration]', '$datetime','$country', 'Unknown', 'queued',  '$gateway_id', '', '0', '$rows[language]');"); $error = mysqli_error($server);
			}
		}
	}
	mysqli_query($server, "UPDATE sentmessages SET `status` = 'completed' WHERE `id` = '".$rows['id']."'");
}

if(!isset($_REQUEST['gateway_id']) && !isset($_REQUEST['customer_id']) && !isset($_REQUEST['delay'])) {
    //process 10 scheduled messages
    logEvent(0,'Processing scheduled messages');
    $now=date('Y-m-d H:i:s',time());
    $query="SELECT * FROM scheduledmessages WHERE (status = 'queued' OR status = 'Queued') AND `schedule_date` <= '$now' ORDER BY id ASC LIMIT 10";
    $result = mysqli_query($server,$query);
    while($rows = mysqli_fetch_assoc($result)) { 
    	$to_count = 0;
    	mysqli_query($server, "UPDATE scheduledmessages SET `status` = 'processed' WHERE `id` = '".$rows['id']."'");
    	mysqli_query($server, "INSERT INTO sentmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`sent_from`, `gateway_id`, `ip`, `notice`, `to_count`, `language`) 
    	VALUES ('".mysqli_real_escape_string($server,$rows['message'])."','$rows[recipients]', '$rows[customer_id]', '$rows[type]', '$rows[media]','".date('Y-m-d H:i:s')."', '".mysqli_real_escape_string($server,$rows['sender_id'])."', '$rows[phonebook_id]','$rows[marketinglist_id]', '$rows[duration]', '$rows[file]','$rows[country]', 'queued', 'portal', '$rows[gateway_id]', '0.0.0.0', '', '$rows[to_count]', '$rows[language]');") ;
    	//check repeat
    	if(!empty($rows['repeats']) && $rows['repeats']!='0') {
    		$repeat = strtolower($rows['repeats']);
    		$schedule_date = $rows['schedule_date'];
    		$new_schedule = $schedule_date;
    		switch ($repeat) {
    			case 'yearly':
    			$new_schedule = strtotime($schedule_date)+(60*60*24*365);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    			case 'monthly':
    			$new_schedule = strtotime($schedule_date)+(60*60*24*30);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    			case 'weekly':
    			$new_schedule = strtotime($schedule_date)+(60*60*24*7);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    			case 'daily':
    			$new_schedule = strtotime($schedule_date)+(60*60*24);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    			case 'every 12 hours':
    			$new_schedule = strtotime($schedule_date)+(60*60*12);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    			case 'every 6 hours':
    			$new_schedule = strtotime($schedule_date)+(60*60*6);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    			case 'every 3 hours':
    			$new_schedule = strtotime($schedule_date)+(60*60*3);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    			case 'every hour':
    			$new_schedule = strtotime($schedule_date)+(60*60*1);
    			$new_schedule=date('Y-m-d H:i:s',$new_schedule);
    			break;
    		}
    		mysqli_query($server,"UPDATE scheduledmessages SET `schedule_date` = '$new_schedule' WHERE `id` = '".$rows['id']."'");
    		mysqli_query($server,"UPDATE scheduledmessages SET `status` = 'queued' WHERE `id` = '".$rows['id']."'");
    	}
    }
    
    //process pending emails
    logEvent(0,'Processing queued emails');
    $query="SELECT * FROM emails WHERE `status` = 'queued' LIMIT 1";
    $result = mysqli_query($server,$query) ;
    $n = 0;
    while ($rows = mysqli_fetch_assoc($result)) {	
    	mysqli_query($server, "UPDATE  `emails` SET  `status` =  'processing' WHERE `id` = '$rows[id]'");	
    	set_time_limit(0);
    	$n += 1;
    	$message = $rows['message'];
    	$to = $rows['recipient'];
    	$subject = $rows['subject'];
    	$user = $rows['customer_id'];
    	$emailList = explode(',', $to);
    	foreach($emailList as $emailAdd) {
    		sendEmail(getSetting('smtpUsername',$user),getSetting('businessName',$user),$subject,$emailAdd,$message);
    	}
    	mysqli_query($server, "UPDATE  `emails` SET  `status` =  'sent' WHERE `id` = '$rows[id]'");	
    }
    
    //cancel billed failed messages
    mysqli_query($server, "UPDATE messagedetails SET `cost` = '0' WHERE `status` = 'failed'");
    mysqli_query($server, "UPDATE messagedetails SET `notice` = '' WHERE `status` = 'sent'");
    
    logEvent(0,'Minute cron completed');
    global $hooks;
    $hooks->do_action('MinuteCronEvent');
} else {
	logEvent(0,'Custom Minute cron completed');	
}
mysqli_close($server);