<?php
	include"../../connect/db.php"; 

 	 	if( isset($_POST['rbank']) ){

	 		$rbank = mysqli_real_escape_string($con,$_POST['rbank']);
	 		$accno = mysqli_real_escape_string($con,$_POST['accno']);
	 		$rname = mysqli_real_escape_string($con,$_POST['rname']);
	 		$transtype = mysqli_real_escape_string($con,$_POST['transtype']);
	 		$amt = mysqli_real_escape_string($con,$_POST['amt']);
	 		$desc = mysqli_real_escape_string($con,$_POST['desc']);
	 		$chap =  mysqli_real_escape_string($con,$_POST['sacct']);
	 		$d_o_t = date("Y-m-d");	

            $seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'); // and any other characters
            shuffle($seed); // probably optional since array_is randomized; this may be redundant
            $rand = '';
            foreach (array_rand($seed, 7) as $k) $rand .= $seed[$k];								            
	        $transId =  $rand; 

	 		$sql = mysqli_query($con,"SELECT currency,email,f_name,l_name,amount FROM users WHERE account_num = '$accno' ");
				
				$row = mysqli_fetch_assoc($sql);

	 			$kunle = mysqli_query($con,"SELECT currency,email,f_name,l_name,amount FROM users WHERE account_num = '$chap' ");

	 				$krow = mysqli_fetch_assoc($kunle) ;

	 				$chapsmail = $row['email'];

					$theotherchap = $row['email'];

					$violin = mysqli_query($con,"INSERT INTO transfer (rname, rbname, account_num, transtype, amt, description, user, status) VALUES ('$rname', '$rbank', '$accno', '$transtype', '$amt', '$desc', '$chap', 'success') ");

					if( $violin ){


				        $descriptionR = "Bank Transfer Of ".$krow['currency']."".$amt." From ".$krow['f_name']." ".$krow['l_name']." Reference ".$transId ;

				        $descriptionC = "Bank Transfer Of ".$row['currency']."".$amt."  to ".$row['f_name']." ".$row['l_name']." Reference ".$transId ;		        

			 			$seyi = mysqli_query( $con,"INSERT INTO transactions (trans_id, user, description, d_o_t, type, status) VALUES ('$transId', '$chapsmail', '$descriptionC', '$d_o_t', 'Debit', 'SUCCESS' ) " );

			 			if( $seyi ){

			 				$segun = mysqli_query( $con,"INSERT INTO transactions (trans_id, user, description, d_o_t, type, status) VALUES ('$transId', '$theotherchap', '$descriptionR', '$d_o_t', 'Credit', 'SUCCESS' ) " );

			 				if( $segun ){
			 					$debit_new_amt = $krow['amount'] - $amt ;
			 					$credit_new_amt = $row['amount'] + $amt ;

			 					$credit_tran = mysqli_query($con,"UPDATE users SET amount = '$credit_new_amt' WHERE email = '$theotherchap' ");

			 					$debit_tran = mysqli_query($con,"UPDATE users SET amount = '$debit_new_amt' WHERE email = '$chap' ");

			 					if( $debit_tran && $credit_tran ){
			 						echo "success";
			 					}
			 					else{
			 						echo "error";
			 					}
			 				}
			 				else{
			 					echo "error";
			 				}
			 			}
			 			

					}
					else{
						echo "error";
					}

 		}
 		else{
 			echo "error";
 		}

 ?>