
<?php
	$hostname_conMarketer = "localhost";
	$database_conMarketer = "ki223469_temp";
	$username_conMarketer = "ki223469_temp";
	$password_conMarketer = "m0bi.2018$";
	$database = "ki223469_temp";  
	
	$conMarketer = mysql_connect($hostname_conMarketer, $username_conMarketer, $password_conMarketer) or trigger_error("Con Error:".mysql_error(),E_USER_ERROR); 

	mysql_select_db($database) or trigger_error(mysql_error());


$result = mysql_query("SELECT * FROM `airtime_sending_records` WHERE status != 'Sent' ORDER BY r_id DESC limit 1"); 
while($row = mysql_fetch_array($result))
{
	$customer_id = $row['customer_id'];
    $recipient = $row['recipient'];
    $airtime_sent = $row['airtime_sent'];
	
	//Strip Airtime Currency Type
	$airtime_curr = substr($airtime_sent,0,4);
	
	//Strip spaces from airtime amount
	$amount_ini = preg_replace("/[^0-9.]/", "", $airtime_sent);
	
	//Round airtime to whole number for doing reversal calculation
	$amount = round($amount_ini);
	
	refundAirtime($customer_id,$recipient,$amount,$airtime_curr);
}

function refundAirtime($customer_id,$recipient,$amount,$airtime_curr ){
   
    //--Get API Account - ShopID
    $row = mysql_query("select API_account from `airtime_sending_credentials` where customer_id = '$customer_id'") or die (mysql_error());	
	$rows = mysql_fetch_array($row);
	$api_account = $rows['API_account'];
	
	//--Refund the actual airtime sent 
	mysql_query("update currency_credits set amount = amount + '$amount' where shopid = '$account_id' ") or die(mysql_error());
	
	//--Insert into credit top up history
	mysql_query("Insert into `credit_topup` (credit_amount, credit_units, description, shop_id, current_balance_totals) values ('$amount','$airtime_curr','Airtime Refund','$api_account','$amount')") or die(mysql_error());
	
	//--Table to store credit refunds 
	mysql_query("Insert into `airtime_refund` (customer_id, refund_amount, refund_reason) values ('$customer_id','$amount','Airtime Refund')") or die(mysql_error());
	
	
}


?>