<?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());
//Send birthfday message if time is 06:00:00
if(date('H:m',time())=='06:00') {
	$query="SELECT * FROM contacts WHERE birthday LIKE '%$date%' ORDER BY id ASC";
	$result = mysqli_query($server,$query);
	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');") ;
		}
	}
}

//Check for due Shortcode subscriptions
$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);
	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);
	}
}

//Expire SMS credits that are due
$query="SELECT * FROM `transactions` WHERE `validity` > 0 AND `status` = 'completed' 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'];
	$date = $rows['date'];
	$validity = $rows['validity'];
	if( (strtotime($date)+(60*60*24*$validity)) <= time()) {
		mysqli_query($server, "UPDATE `transactions` SET `status` =  'expired' WHERE `id` = '$id'");
	}

}

//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
if(date('H:m',time())=='00:00') {
	$type = 'Full system database backup';
	backup_tables();	
}

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

