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

// Check if session variable 'chap' is set
if (!isset($_SESSION['chap'])) {
    echo "Error: Session variable 'chap' is not set.";
    exit();
}

$chap = $_SESSION['chap'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $amount = isset($_POST['amount']) ? mysqli_real_escape_string($con, $_POST['amount']) : 0;
    $bankname = isset($_POST['bankname']) ? mysqli_real_escape_string($con, $_POST['bankname']) : '';
    $accountnumber = isset($_POST['accountnumber']) ? mysqli_real_escape_string($con, $_POST['accountnumber']) : '';
    $accountholder = isset($_POST['accountholder']) ? mysqli_real_escape_string($con, $_POST['accountholder']) : '';
    $description = isset($_POST['description']) ? mysqli_real_escape_string($con, $_POST['description']) : '';
    $transId = isset($_POST['transId']) ? mysqli_real_escape_string($con, $_POST['transId']) : '';
    $currency = isset($_POST['currency']) ? mysqli_real_escape_string($con, $_POST['currency']) : '';
    $account = isset($_POST['account']) ? mysqli_real_escape_string($con, $_POST['account']) : '';


    // Fetch sender details
    $sql = mysqli_query($con, "SELECT * FROM users WHERE email = '$chap'");
    if (!$sql) {
        echo "Error fetching user details: " . mysqli_error($con);
        exit();
    }

    $row = mysqli_fetch_assoc($sql);
    if (!$row) {
        echo "Error: User not found.";
        exit();
    }

    $account_name = $row['firstname'] . " " . $row['lastname'];
    $senders_balance = $row[$account.'_balance'];
    $account_num = $row['account_num'];

    // Fetch receiver details
    $sql_receiver = mysqli_query($con, "SELECT * FROM users WHERE account_num = '$accountnumber'");
    if (!$sql_receiver) {
        echo "Error fetching receiver details: " . mysqli_error($con);
        exit();
    }

    $row_r = mysqli_fetch_assoc($sql_receiver);
    if (!$row_r) {
        
        
        
        
       // Description for transaction
$description_debit = "Debit transaction of $currency$amount to $accountholder";
$balanceField = $account . '_balance'; // get the actual value

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

// Deduct amount from sender
$new_bal_sender = $senders_balance - $amount;
$sqlbalance = mysqli_query($con, "UPDATE users SET `$balanceField` = '$new_bal_sender' WHERE email = '$chap'");

if (!$sqlbalance) {
    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);

    // Clear code_level so receipt page is accessible
    mysqli_query($con, "UPDATE users SET code_level = '' WHERE email = '$chap'");

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

    $receiver_balance = $row_r['checking_balance'];
    $receiver_email = $row_r['email'];

    // Check if sender has sufficient funds
    if ($senders_balance < $amount) {
        echo "Error: Insufficient funds.";
        exit();
    }

    // Credit receiver
    $new_bal_receiver = $receiver_balance + $amount;
    $sql_credit = mysqli_query($con, "UPDATE users SET checking_balance = '$new_bal_receiver' WHERE account_num = '$accountnumber'");
    if (!$sql_credit) {
        echo "Error updating receiver balance: " . mysqli_error($con);
        exit();
    }

    // Description for credit transaction
    $description_credit = "Credit Transaction of $currency$amount from $account_name";

    // Use the current date
    $currentDate = date('Y-m-d H:i:s');
$balanceField = 'checking_balance'; // get the actual value

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

    $status = 'Completed';
    $type = 'Credit';
    $stmt->bind_param("ssdsssss", $transId, $accountnumber, $amount, $currentDate, $status, $type, $description_credit,$balanceField);

    if (!$stmt->execute()) {
     //   include 'creditalert.php';
        echo "Error executing credit transaction: " . $stmt->error;
        exit();
    }

    $stmt->close();

    // Include debit transaction
    include 'debittransaction.php';
}
?>