<?php
// Description for transaction
$description_debit = "Debit transaction of $currency$amount to $accountholder";

// Use the current date function
$currentDate = date('Y-m-d H:i:s');

// Deduct amount from sender
$new_bal_sender = $senders_balance - $amount;
$balanceFielde = $account . '_balance'; // e.g., "checking_balance" or "bsl_balance"
$sql = mysqli_query($con, "UPDATE users SET `$balanceFielde` = '$new_bal_sender' WHERE email = '$chap'");

if (!$sql) {
    echo "Error updating sender balance: " . mysqli_error($con);
    exit();
}

// Insert debit transaction
$stmt = $con->prepare("INSERT INTO transactions (trans_id, user, amount, date, status, type, description,account) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
if (!$stmt) {
    echo "Error preparing debit transaction: " . mysqli_error($con);
    exit();
}


$status = 'Completed';
$type = 'Debit';
$stmt->bind_param("ssdsssss", $transId, $account_num, $amount, $currentDate, $status, $type, $description_debit,$balanceField);

if ($stmt->execute()) {
    include 'alert.php';

    // Send transfer confirmation email (does not block on failure)
    include_once __DIR__ . "/../../includes/email_helper.php";
    sendTransferConfirmation($con, $chap, $transId);

    echo 'success';
} else {
    echo "Error executing debit transaction: " . $stmt->error;
}
$stmt->close();
?>
