<?php



session_start(); 
    $u_uname = '';
    if (isset($_COOKIE['auth_token']))
    {
        $u_uname = $_COOKIE['auth_token'];
    }else{
        header("location:../login.php");
    }

include '../include/pay_connection.php';

$user_id = mysqli_real_escape_string($updater, $_POST['user_id']);
$amount = $_POST['amount'];
$payment = mysqli_real_escape_string($updater, $_POST['payment']);

// Fetch the current wallet balance
$query = "SELECT wallet_balance  FROM users WHERE user_id = '$user_id'"; 
$result = mysqli_query($updater, $query);

if ($result) {
    
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $wallet_balance = $row['wallet_balance'];
        $opening_balance = $wallet_balance;
        // $full_name = $row['full_name'];

        if ($payment === 'debit') {
            
            if ($amount > $wallet_balance) {
                header("location:../money_transfer.php?error=5");
                // echo "No sufficient balance in the wallet Balance.";
            } else {
                $new_balance = $wallet_balance - $amount;
                $update_query = "UPDATE users SET wallet_balance = '$new_balance' WHERE user_id = '$user_id'";
                if (mysqli_query($updater, $update_query)) {
                    //transaction _history
                    
                    $insert_query = "INSERT INTO transaction_history (`user_id`, `amount`,`remark`, `reason`, `status`, `opening_balance`, `closing_balance`) 
                                     VALUES ('$user_id', '$amount', 'debit by admin','debit', 'success', '$opening_balance', '$new_balance')";
                    mysqli_query($inserter, $insert_query);
                    header("location:../money_transfer.php?success=3");
                    // echo "Amount debited successfully.";
                } else {
                    echo "Error updating balance: ";
                }
            }
        } elseif ($payment === 'credit') {
           
            $new_balance = $wallet_balance + $amount;
            $update_query = "UPDATE users SET wallet_balance = '$new_balance' WHERE user_id = '$user_id'";
            if (mysqli_query($updater, $update_query)) {
                //transaction_hisotry
                
               $insert_query = "INSERT INTO transaction_history (`user_id`, `amount`, `remark`, `reason`,`status`, `opening_balance`, `closing_balance`) 
                                 VALUES ('$user_id', '$amount', 'credit by admin', 'credit','success', '$opening_balance', '$new_balance')";
                mysqli_query($inserter, $insert_query);
                header("location:../money_transfer.php?success=4");
                // echo "Amount credited successfully.";
            } else {
                echo "Error updating balance: " ;
            }
        }
    } 
}

mysqli_close($updater);

     


?>