<?php
	session_start();
	include"../../connect/db.php"; 

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

		$acct_num = mysqli_real_escape_string($con,$_POST['acct_num']);
		$amount = mysqli_real_escape_string($con,$_POST['amount']);
		$depositname = mysqli_real_escape_string($con,$_POST['depositname']);
		$currency = mysqli_real_escape_string($con,$_POST['currency']);
		$d_o_t = mysqli_real_escape_string($con,$_POST['d_o_t']);
		$status = mysqli_real_escape_string($con,$_POST['status']);

        $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;

        $descriptionC = "$depositname $amount on $d_o_t";

        $sql = mysqli_query($con,"SELECT * FROM users WHERE account_num = '$acct_num' ");
           $row = mysqli_fetch_assoc($sql);

        $email = $row['email'];
 $balance = $row['checking_balance'];
        $amounts = preg_replace('/[^0-9\.]/', '', $amount); // Ensure amount is a valid number
        $new_bal =  $balance - $amounts;

        	$query = mysqli_query($con,"INSERT INTO transactions (trans_id,amount, user, description, date, type, status) VALUES ('$transId', '$amount','$acct_num', '$descriptionC', '$d_o_t', 'Debit', '$status'  ) ");
// Update user balance
        $sql2 = mysqli_query($con, "UPDATE users SET checking_balance = '$new_bal' WHERE account_num = '$acct_num'");
        	if( $query ){
        // Send alert email if checkbox checked
   if (!empty($_POST['alert_settings1']) && $_POST['alert_settings1'] == 1) {
    include 'withdrawmail.php';
}
    if (!$sql2) {
        die('Error updating balance: ' . mysqli_error($con));
    }
        if (!$sql2) {
            die('Error updating balance: ' . mysqli_error($con));
        }



        	   // include 'withdrawmail.php';
        		echo "success";
        	}
        	else{
        		echo "error";
        	}
	}
	else{
		echo "error";
	}
 ?>  