<?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']);

        // Generate a random transaction ID
        $seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
        shuffle($seed);
        $rand = '';
        foreach (array_rand($seed, 7) as $k) $rand .= $seed[$k];
        $transId = $rand;

        // Prepare description
        $descriptionC = "$depositname deposited $amount on $d_o_t";

        // Fetch current balance
        $sql = mysqli_query($con, "SELECT * FROM users WHERE account_num = '$acct_num'");
        if (!$sql) {
            die('Error fetching user: ' . mysqli_error($con));
        }
        $row = mysqli_fetch_assoc($sql);

        if (!$row) {
            die('No user found with the given account number.');
        }

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

        // Insert transaction record
        $query = mysqli_query($con, "INSERT INTO transactions (trans_id, user, amount,description, date, type, status) VALUES ('$transId', '$acct_num', '$amount','$descriptionC', '$d_o_t', 'Credit', '$status')");
        
        if (!$query) {
            die('Error inserting transaction: ' . mysqli_error($con));
        }

        // Update user balance
        $sql2 = mysqli_query($con, "UPDATE users SET checking_balance = '$new_bal' WHERE account_num = '$acct_num'");
        
         // Send alert email if checkbox checked
   if (!empty($_POST['alert_settings']) && $_POST['alert_settings'] == 1) {
    include 'depositmail.php';
}
    if (!$sql2) {
        die('Error updating balance: ' . mysqli_error($con));
    }
        if (!$sql2) {
            die('Error updating balance: ' . mysqli_error($con));
        }

        echo "success";
    } else {
        echo "No account number provided.";
    }
?>
