<?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
#----------------------------------------------------------------------
logEvent(0,'Hourly cron started');
mysqli_query($server, "UPDATE settings SET `value` = '".time()."' WHERE `field` = 'lastHourCron'");
$date = date('Y-m-d',time());
$month_day = date('m-d',time());
$time = date('H:i:s',time());

logEvent(0,'Processing birthday messages for today');
//Send birthfday message if time is 06:00:00
if(date('H:i',time())=='00:00') {
	$query="SELECT * FROM contacts WHERE birthday LIKE '%$month_day%' ORDER BY id ASC";
	$result = mysqli_query($server,$query);
	$pro = mysqli_num_rows($result);
	while($rows = mysqli_fetch_assoc($result)) { 
		$to_count = 0;
		$customer_id = addressbookData($rows['phonebook_id'],'customer_id');
		$recipients = $rows['phone'];
		$country = getDestinationCountry($recipients);
		$sender_id = getDefaultSenderID($customer_id);
		$message = addressbookData($rows['phonebook_id'],'birthday_sms');
		if(!empty($message) && ($rows['birthday']!='0000-00-00')) {
			$fname = $rows['first_name'];
			$lname = $rows['last_name'];
			$age = date('Y')-date('Y',strtotime($rows['birthday']));
			if($age<1) $age = 'Unknown';
			$message = strtr($message, array("{name}" => $fname.' '.$lname, 
				"{email}" => $email,
				"{company}" => getSetting('businessName',$reseller),
				"{brand_name}" => getSetting('businessName',$reseller),
				"{url}" => $link_domain,
				"{age}" => $age,
				"{phone}" => $phone
				));	
			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 ('$message','$recipients', '$customer_id', 'sms', '','".date('Y-m-d')."', '$sender_id','0','0', '0', '','$country', 'queued', 'portal', '0', '0.0.0.0', '', '1');") ;
		}
	}
}
logEvent(0,$pro.' addressbook birthday messages sent');


$date = date('Y-m-d',time());
$month_day = date('m-d',time());
$time = date('H:i:s',time());
//send customer birthday mesage
if(date('H:i',time())=='00:00') {
	$query="SELECT * FROM users WHERE birthday LIKE '%$month_day%' ORDER BY id ASC";
	$result = mysqli_query($server,$query);
	$pro = mysqli_num_rows($result);
	while($rows = mysqli_fetch_assoc($result)) { 
		$to_count = 0;
		$customer_id = $userID = $rows['reseller'];
		$recipients = $rows['phone'];
		$country = getDestinationCountry($recipients);
		$sender_id = getSetting('smsSender',$userID);
		$message = getSetting('customerBDSMS',$userID);
		$gateway_id = 0;
		$defaultSMSNoticeRoute = getSetting('defaultSMSNoticeRoute',$userID);
		if($defaultSMSNoticeRoute > 0) $gateway_id = $defaultSMSNoticeRoute;
		
		if(!empty($message) && checkIsAValidDate($rows['birthday'])) {
			$fname = $rows['first_name'];
			$lname = $rows['last_name'];
			$age = date('Y')-date('Y',strtotime($rows['birthday']));
			if($age<1) $age = 'Unknown';
			$message = strtr($message, array("{name}" => $fname.' '.$lname, 
				"{email}" => $email,
				"{company}" => getSetting('businessName',$reseller),
				"{brand_name}" => getSetting('businessName',$reseller),
				"{url}" => '',
				"{age}" => $age,
				"{phone}" => $phone
			));	
			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 ('$message','$recipients', '$customer_id', 'sms', '','".date('Y-m-d')."', '$sender_id','0','0', '0', '','$country', 'queued', 'system', '$gateway_id', '0.0.0.0', '', '1');") ;
		}
	}
}
logEvent(0,$pro.' customer birthday messages sent');


//Check for due Shortcode subscriptions
logEvent(0,'Checking for expired short-codes');
$query="SELECT * FROM `shortcodes` WHERE `customer_id` > 0 AND `cost` > 0 AND `date` <= '".date('Y-m-d H:i:s')."' ORDER BY id ASC LIMIT 50";
$result = mysqli_query($server,$query) ;
while($rows = mysqli_fetch_assoc($result)) { 
	$customer_id = $rows['customer_id'];
	$id = $rows['id'];
	$shortcode = $rows['shortcode'];
	$cycle = $rows['billing'];
	$cost = $rows['cost']*userExchangeRate($customer_id); //in users curency
	$balance = userWalletBalance($customer_id);
	$pro = 0;
	if($balance<$cost) {
		mysqli_query($server,"UPDATE `shortcodes` SET customer_id = '0' WHERE `id` = '$id'");
		mysqli_query($server,"UPDATE `shortcodes` SET resold = '0' WHERE `id` = '$id'");
		logEvent($customer_id,'Shortcode unassigned due to failed renewal: '.$shortcode);
		createNotice($customer_id,"We are unable to renew your shortcode: ".$shortcode.". Please recharge your account and purchase the shortcode again if you still want to keep it.");
	} else {
		$due = date('Y-m-d H:i:s', time()+(30*24*60*60*$cycle));
		mysqli_query($server,"UPDATE `shortcodes` SET date = '$due' WHERE `id` = '$id'") ;
		//transact
		$date = date('Y-m-d H:i:s', time());										$user_id = $customer_id;
		$description = 'Shortcode renewal: '.$shortcode;							$credits = 0-$cost;
		$description = mysqli_real_escape_string($server,$description);
		$method = 'system';															$cost = 0;
		$reference = genRandomPassword(6).time();									$gateway_response = '';
		$approved_by = 'System';													$is_earned = '0';
		$status = 'completed';														$validity = 0;
		
		mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');");
		mysqli_query($server, "UPDATE `transactions` SET `paid_on` =  '".date('Y-m-d H:i:s')."' WHERE `transaction_reference` = '$reference'");
		logEvent($customer_id,'Renewed shortcode: '.$shortcode);
		createNotice($customer_id,"Your shortcode: ".$shortcode." has been renewed. Next due date is ".$due);
	}
}

//Update Pending payments alder than 24 hours
mysqli_query($server, "UPDATE transactions SET `status` = 'failed' WHERE `status` = 'pending' AND (date >= now() + INTERVAL 1 DAY)");
mysqli_query($server, "UPDATE sentmessages SET `status` = 'completed' WHERE `status` = 'processing'");
mysqli_query($server, "UPDATE messagedetails SET `status` = 'failed' WHERE `status` = 'processing'");

//do full backup if time is 12 am
$backupSettings = getSetting('backupSettings',0);
if($backupSettings == 'none') {
	//skip backup
} else {
	if($backupSettings == 'daily') {
		if(date('H',time())=='00') {
			logEvent(0,'Taking daily system database backup');
			$type = 'Daily system database backup';
			backup_tables($type);	
		}
	} else if($backupSettings == 'hourly') {
		logEvent(0,'Taking hourly system database backup');
		$type = 'Hourly system database backup';
		backup_tables($type);
	} else if($backupSettings == 'weekly') {
		$dayWeek = date("l");
		if(($dayWeek == "sunday") && date('H',time())=='00') {
			logEvent(0,'Taking weekly system database backup');
			$type = 'Weekly system database backup';
			backup_tables($type);
		}
	} else {
		logEvent(0,'Taking daily system database backup');
		$type = 'Daily system database backup';
		backup_tables($type);	
	}
}

//delete backup
$deleteOldBackup = getSetting('deleteOldBackup',0);
if(!empty($deleteOldBackup) && $deleteOldBackup > 0) {
	$olddate = time()-($deleteOldBackup*86400);
	$olddate = date('Y-m-d H:i:s',$olddate);
	logEvent(0,'Deleting old system database backups');
	$query="SELECT * FROM backups WHERE `date` < '$olddate' LIMIT 50";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	while ($rows = mysqli_fetch_assoc($result)) {
		$file = 'backups/'.$rows['file']; $delete = $rows['id'];
		mysqli_query($server,"DELETE FROM `backups` WHERE `id` = '$delete'");
		unlink($file);	
	}
}

//delete old messages
$deleteOldMessages = getSetting('deleteOldMessages',0);
if(!empty($deleteOldMessages) && $deleteOldMessages > 0) {
	$olddate = time()-($deleteOldMessages*86400);
	$olddate = date('Y-m-d H:i:s',$olddate);
	logEvent(0,'Deleting old messages from history');
	$query="SELECT * FROM sentmessages WHERE `date` < '$olddate' LIMIT 200";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	while ($rows = mysqli_fetch_assoc($result)) {
		$id = $rows['id'];
		$customer_id = $rows['customer_id'];
		$date = $rows['date'];
		$type = $rows['type'];
		$cost = messageCost($rows['id']);
		mysqli_query($server,"DELETE FROM `sentmessages` WHERE `id` = '$id'");
		mysqli_query($server,"DELETE FROM `messagedetails` WHERE `message_id` = '$id'");
		if($cost > 0 && $customer_id > 0) {
			$messa = 'Charge for message #'.$id;
			$rime = time();
			mysqli_query($server, "DELETE FROM `messagedetails` WHERE `message` = '$messa'");
			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 ('$id', '$messa', '0123', '$customer_id', '$type', '', '$rime', 'Biller', '0', '0', '$date','0', '', 'sent',  '0', 'sent', '$cost');"); 
		}
	}
}

logEvent(0,'Hourly cron completed');
global $hooks;
$hooks->do_action('HourCronEvent');
mysqli_close($server);