<?php 
// get the data base first
include('db_conx.php');

$id = $_SESSION['id'];

// getting the customers balance from the database in case there is a reduction and the session havent be restarted.
	$sql = "SELECT * FROM confidential_table WHERE id = ' $id' ";
	$query = $db_conx->query($sql);
	$row = $query->fetch_assoc();
	$amount_bal = $row['avaliable_balance'];

	// getting the values passed from the ajax 
	$name_bank = $db_conx->real_escape_string(trim($_POST['name_bank']));
	$swift_code = $db_conx->real_escape_string(trim($_POST['swift_code']));
	$name_bene = $db_conx->real_escape_string(trim($_POST['name_bene']));
	$account_bene = $db_conx->real_escape_string(trim($_POST['account_bene']));
	$trans_amount = $db_conx->real_escape_string(trim($_POST['trans_amount']));
	$description = $db_conx->real_escape_string(trim($_POST['description']));
	
	// checking for empty fields 
	if(empty($name_bank) || empty($name_bene) || empty($swift_code) || empty($account_bene) || empty($trans_amount) ){
		// echo "error";
	}else{
		// getting the receivers information with the account number
		$sql_payee = "SELECT * FROM confidential_table WHERE account_no = '$account_bene' ";
		$result_payee = $db_conx->query($sql_payee);
		$resultcheck_payee = mysqli_num_rows($result_payee);

		if($result_payee){
			$row_payee= mysqli_fetch_assoc($result_payee);
			$payee_acc_no = $row_payee['account_no'];
			$payee_id = $row_payee['id'];
			$payee_current_amt = $row_payee['avaliable_balance'];
			$new_payee_amount = $trans_amount + $payee_current_amt;

			// updating the receiver's amount 
			$sql_5 = "UPDATE confidential_table SET avaliable_balance = '$new_payee_amount' WHERE account_no = '$account_bene' ";
			$result_5 = $db_conx->query($sql_5);
			if($result_5){
				// creating a transaction id 
			$transaction_id = rand(1,100099999);

			echo $transaction_id;
			$new_amount = $amount_bal - $trans_amount;

			// now we have to check if the amount is higher than what the person have in his account ...
			
			if ( $trans_amount > $amount_bal){
				echo 'low_amount';

				}else{
					// updating the customer's account
					$sql_6 = "UPDATE confidential_table SET avaliable_balance = '$new_amount' WHERE id = '$id' ";
					$result_6 = $db_conx->query($sql_6);
					if ($result_6) {
						$sql_1 = "INSERT INTO transfer(u_id,name_bank,swift_code,b_name,b_acc_no,amount,t_time,ref,trans_status,mode,description) VALUES('$id','$name_bank','$swift_code','$name_bene','$account_bene','$trans_amount','$current_time','$transaction_id','1','transfer','$description')";
						$result = $db_conx->query($sql_1);
						if ($result) {
							// echo "success";
						}else{
							// echo "error";
						}
					}else{// end for result six
						// echo "error";
					}

				}

		



			}//end for result five 

		} //end if for result_payee
	} // end for checking for empty fields 


	
?>