<?php

if( $_SERVER['REQUEST_METHOD'] != 'POST' ) exit( "Bad Access Model" );


$data = array();
$error = null;


$token_nums = implode("", array_merge(range(0,9), range(0,9), range(0,9)));
$token_nums = str_shuffle($token_nums);


if( !isset($_POST['data']) ):

	## Transaction Record

	$data['tx_no'] = substr($token_nums, 0, 8);
	$data['tx_type'] = 'debit';
	$data['amount'] = (float)$_POST['amount'];
	$data['beneficiary'] = $_POST['beneficiary'];
	$data['bank_name'] = $_POST['bank_name'];
	$data['sender_name'] = "{$__user['fname']} {$__user['lname']}";
	$data['method'] = $_POST['method'];
	$data['country'] = $_POST['country'] ?? $__user['country'];
	$data['date'] = date("Y/m/d");
	$data['description'] = $_POST['description'];
	$data['to_accno'] = $_POST['tacctno'];
	$data['account'] = $__user['acctno'];
	$data['comments'] = $_POST['comments'];
	$data['charges'] = round((float)$data['amount'] * (float)$settings->get('charges') * 0.01, 2);
	$data['status'] = 'SUCCESS';

else:

	$data = json_decode( base64_decode( $_POST['data'] ), true );
	
endif;


## EMAIL OTP;
	require_once __dir__ . '/for-im-email-otp.php';
## /EMAIL OTP;

## EMAIL OTP;
	require_once USERS_DIR . '/transfer-codes.php';
## /EMAIL OTP;

// ----------------------------------------------------------------

## Total Debit
$TOTAL = round($data['amount'] + $data['charges'], 2);

## Transaction History Query
$TX_SQL = sQuery::insert( 'tbl_transaction', $data );

// ----------------------------------------------------------------

## Account Debit Query;
$DEBIT_SQL = "
	UPDATE `tbl_users` 
	SET `balance` = balance - {$TOTAL} 
	WHERE id = '{$__user['id']}'
";

## Account Credit Query;
$CREDIT_SQL = "
	UPDATE `tbl_users` 
	SET `balance` = balance + {$data['amount']} 
	WHERE acctno = '{$data['to_accno']}'
";

if( !empty($_POST['save_beneficiary']) ) {
	$bc_info = array(
		"name" => $data['beneficiary'],
		"bank" => $data['bank_name'],
		"account" => $data['to_accno'],
		"method" => $data['method'],
		"userid" => $__user['id'],
		"country" => $data['country']
	);
	$BXSQL = sQuery::select( "beneficiaries", "bank = '{$bc_info['bank']}' AND account = '{$bc_info['account']}'" );
	$_exists = $link->query( $BXSQL )->num_rows;
	if( !$_exists ) $SAVE_BX = sQuery::insert( 'beneficiaries', $bc_info );
};


// -----------------------------------------------------------------

### [BEGIN PROCESSING] ###

if( empty($__user['active']) ) 
	
	$error = ucfirst( "{$data['method']} Transfer is not activated on this account. <br> Please contact account manager " );
	
else {

	foreach( $data as $key => $value ) {
		if( empty($value) && !in_array($key, ["comments", "status", "description", "charges"]) ) {
			$error = "One or more relevant field is required";
			break;
		}
	};

	if( empty($error) && (float)$__user['balance'] < $data['amount'] ) $error = "Insufficient account balance";

};

/*
 *
 *
*/


if( empty($error) ) {
	
	$debit = $link->query( $DEBIT_SQL );
	$credit = $link->query( $CREDIT_SQL );
	
	if( !$debit || !$credit ): $error = "Transaction could not be completed";
	
	else:
		
		$history = $link->query( $TX_SQL );
		
		## save beneficiary;
		if( isset($SAVE_BX) ) $link->query( $SAVE_BX );
		
		$__user = help::get_user($__user['email']); // reset user variable
		
		$mailer = new mailer();
		$mailer->Subject = "Debit Alert";
		$mailer->addAddress($__user['email']);
		$mailer->Body = "
			<section>
				Dear {$__user["fname"]}, <br>
				A Debit transaction of {$currency}{$data['amount']} occured in your account on {$data['date']} at the charges of {$currency}{$data['charges']}. <br>
				Available balance: {$currency}{$__user['balance']} 
			</section>
		";
		$mailer->send();
		
	endif;
	
};

/*
 *
 *
 *
*/


if( !empty($error) ) {
	
	$_SESSION['transfer_error'] = $error;
	
	$return_location = help::url( PANEL_DIR ) . "/{$data['method']}.php";
	
	header("location: {$return_location}");
	
	exit();
	
} else $_SESSION['transfer_log'] = $data;



