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

    // Idempotency check
    if (isset($_SESSION['last_withdraw_time']) && (time() - $_SESSION['last_withdraw_time']) < 30) {
        echo "withdrawal_in_progress";
        exit();
    }
    $_SESSION['last_withdraw_time'] = time();

    $user = isset($_SESSION['chap']) ? $_SESSION['chap'] : null;

    if (!$user) {
        echo "User not logged in.";
        exit;
    }

    if (isset($_POST['amount']) && isset($_POST['coin']) && isset($_POST['address'])) {

        $with_meth = mysqli_real_escape_string($mysqli, $_POST['coin']);       
        $address = mysqli_real_escape_string($mysqli, $_POST['address']);       
        $amount = mysqli_real_escape_string($mysqli, $_POST['amount']);
        $date_trans = date("j/m/Y");

        $sql = mysqli_query($mysqli, "SELECT * FROM users WHERE email = '$user'");
        
        if (!$sql) {
            echo "SQL Error: " . mysqli_error($mysqli);
            exit;
        }

        $row = mysqli_fetch_assoc($sql);

        if (!$row) {
            echo "User not found.";
            exit;
        }

        $balance = $row['checking_balance'];

        if ($amount > $balance) {
            echo "broke";
        } else {
            $query = mysqli_query($mysqli, "INSERT INTO withdraw (user, amount, method, address, status, date_trans) VALUES ('$user', '$amount', '$with_meth', '$address', 'pending','$date_trans')");

            if ($query) {
                echo "success";
            } else {
                echo "Error: " . mysqli_error($mysqli);
            }
        }
    } else {
        echo $address, $with_meth ,$amount;
    }
?> 
