<?php
// Starting session and including necessary files
session_start();
include_once('_db.php');

// Debug session and POST values
error_log("Session UserID on withdrawal_process.php: " . $_SESSION['userid']);
error_log("POST UserID: " . $_POST['userid']);
error_log("POST Wallet Type: " . $_POST['wallet_type']);  // Debugging wallet type

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $userid = $_SESSION['userid'];  // Retrieving the user ID
    $withdrawalAmount = $_POST['amount'];
    $enteredPassword = $_POST['password'];
    $walletType = $_POST['wallet_type'];  // Get the wallet type from POST data

    // Prepare to fetch account balance and password
    $stmt = $conn->prepare("SELECT account_balance, password FROM user_login WHERE userid = ?");
    $stmt->bind_param("s", $userid);  // Binding as integer
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    // Password verification and balance check
    if (!password_verify($enteredPassword, $row['password'])) {
        $_SESSION['withdrawal_error'] = "Incorrect password. Please try again.";
    } elseif ($withdrawalAmount > $row['account_balance']) {
        $_SESSION['withdrawal_error'] = "Insufficient balance. Please enter an amount less than or equal to your account balance.";
    } else {
        $conn->begin_transaction();
        try {
            // Deduct the withdrawal amount from the user's account balance
            $newAccountBalance = $row['account_balance'] - $withdrawalAmount;

            // Update account balance
            $stmt = $conn->prepare("UPDATE user_login SET account_balance = ? WHERE userid = ?");
            $stmt->bind_param("ds", $newAccountBalance, $userid);  // Binding new balance as double and userid as integer
            $stmt->execute();

            // Prepare to insert withdrawal record
            $wid = uniqid();
            $walletAddress = $_POST['wallet_address'];

            // Insert withdrawal record including wallet_type
            $stmt = $conn->prepare("INSERT INTO withdrawals (wid, userid, wallet_address, amount, wallet_type) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $wid, $userid, $walletAddress, $withdrawalAmount, $walletType);  // Correct binding
            $stmt->execute();

            $conn->commit();
            $_SESSION['withdrawal_success'] = "Withdrawal request submitted successfully. $withdrawalAmount USD will be sent to your wallet address: $walletAddress after confirmation.";
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['withdrawal_error'] = "Error processing withdrawal. Please try again later.";
        }
    }
}

header("Location: withdrawals.php");
exit();
?>
