<?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
#----------------------------------------------------------------------

//Make sure no duplicates 
function IsProcessRunning($pid) {
    return shell_exec("ps aux | grep " . $pid . " | wc -l") > 2;
}

function AmIRunning($process_file) {
    $pid_running = false;
    $pid = 0;
    if (file_exists($process_file)) {
        $data = file($process_file);
        foreach ($data as $pid) {
            $pid = (int)$pid;
            if ($pid > 0 && IsProcessRunning($pid)) {
                $pid_running = $pid;
                break;
            }
        }
    }
    if ($pid_running && $pid_running != getmypid()) {
        if (file_exists($process_file)) {
            file_put_contents($process_file, $pid);
        }
        return true;
    } else {
        file_put_contents($process_file, getmypid());
        return false;
    }
}
mysqli_query($server, "UPDATE settings SET `value` = '".time()."' WHERE `field` = 'lastMinuteCron'");
/*
 * Make sure there is only one instance running at a time
 */
if(!defined('DS')) define('DS', DIRECTORY_SEPARATOR); 
$lockdir = BASEPATH;
$script_name = basename(__FILE__, '.php');
$process_file = $lockdir . '' . $script_name . '.pid';
$am_i_running = AmIRunning($process_file);
if ($am_i_running) {  exit; }

logEvent(0,'Minute cron started');

//Send 60 individual message recipients
$limit = 100;
if(getSetting('sendRate',0)>0) { 
	$limit = getSetting('sendRate',0);
}
$query="SELECT * FROM messagedetails WHERE status LIKE '%queued%' ORDER BY id ASC LIMIT ".$limit;
$result = mysqli_query($server,$query) or die(mysqli_error($server));
while($rows = mysqli_fetch_assoc($result)) { 
	//create hook variables
		$vars = array(
					 "id"=>$rows['id'], 
					 "sender_id"=>$rows['sender_id'], 
					 "to"=>$rows['recipient'],
					 "message"=>$rows['message'], 
					 "customer_id"=>$rows['customer_id'],
					 "type"=>$rows['type'], 
					 "media"=>$rows['media']
					 );
		$_SESSION['EventVals'] = $vars;
	global $hooks; $hooks->do_action('BeforeProcessMessage');
	sendSMS($rows['id']);
	$hooks->do_action('AfterMessageProcess');
}

//process pending messages
$query="SELECT * FROM sentmessages WHERE status LIKE '%queued%' ORDER BY id ASC LIMIT 6";
$result = mysqli_query($server,$query) or die(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']."'");
	$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 = 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`) 
			VALUES ('$rows[id]', '".mysqli_real_escape_string($server,$rows['message'])."','$recipient', '$rows[customer_id]', '$rows[type]', '$rows[media]', '$now', '$rows[sender_id]', '0', '$rows[duration]', '$datetime','$country', 'Unknown', 'queued',  '$gateway_id', '', '0');"); $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 = 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`) 
				VALUES ('$rows[id]', '$rows[message]','$recipient', '$rows[customer_id]', '$rows[type]', '$rows[media]', '$now', '$rows[sender_id]', '$list', '$rows[idduration]', '$datetime','$country', 'Unknown', 'queued',  '$gateway_id', '', '0');"); $error = mysqli_error($server);
			}
		}
	}
	mysqli_query($server, "UPDATE sentmessages SET `status` = 'completed' WHERE `id` = '".$rows['id']."'");
}
//process 10 scheduled messages
$now=date('Y-m-d H:i:s',time());
$query="SELECT * FROM scheduledmessages WHERE status LIKE '%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`) 
	VALUES ('$rows[message]','$rows[recipients]', '$rows[customer_id]', '$rows[type]', '$rows[media]','".date('Y-m-d')."', '$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]');") ;
	//check repeat
	$repeat = strtolower($rows['repeats']);
	if(strlen($repeat>2)) {
		$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
$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]'");	
}

logEvent(0,'Minute cron completed');
global $hooks;
$hooks->do_action('MinuteCronEvent');
mysqli_close($server);
file_put_contents($process_file, '');