<?php
session_start();

require("../includes/db_connect.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ((!empty($_POST['address'])) && (!empty($_POST['amount'])) && (!empty($_POST['withdrawal_method'])) && (!empty($_SESSION['withdraw_account']))  && (!empty($_SESSION['usr_accountId']))) {
        
        header('Content-Type: application/json');

        $address = $_POST['address'];
        $amount = $_POST['amount'];
        $withdrawal_method = $_POST['withdrawal_method'];

        $account = $_SESSION['withdraw_account'];
        $accountId = $_SESSION['usr_accountId'];

        $btcRate = $_SESSION['btcRate'] ?? 1;
        $bchRate = $_SESSION['bchRate'] ?? 1;
        $ethRate = $_SESSION['ethRate'] ?? 1;
        $ltcRate = $_SESSION['ltcRate'] ?? 1;
        $usdtRate = $_SESSION['usdtRate'] ?? 1;
        
        if($account == 'monthly') {
        $sql = "SELECT * FROM monthly_trade_history WHERE accountId=? AND status=? ORDER BY date DESC LIMIT 1";
        } else if($account == 'annual') {
        $sql = "SELECT * FROM annual_trade_history WHERE accountId=? AND status=? ORDER BY date DESC LIMIT 1";
        } else if($account == 'bot') {
        $sql = "SELECT * FROM bot_trade_history WHERE accountId=? AND status=? ORDER BY date DESC LIMIT 1";
        } else {
        $sql = "SELECT * FROM quarterly_trade_history WHERE accountId=? AND status=? ORDER BY date DESC LIMIT 1";
        }
        $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
        $sth->execute([$accountId, 1]);
        $history = $sth->fetchAll();

        if (count($history) > 0) {
            $close_date = $history[0]['closed_date'];
        }
    
        if (is_numeric($amount) && $amount > 0) {
            $amount = round($amount, 2);
            
            if ($account != "bot") {
                if (strtotime($close_date) > strtotime(date('Y-m-d H:i:s'))) {
                    $response = array("message" => "You can't withdraw until your trading term is over.");
                    die(json_encode($response));
                }
            }

            if ($amount < 1) {
                $response = array("message" => "Withdrawal amount cannot be less than " . number_format(1, 2) . " USD");
                die(json_encode($response));
            } else {
                $coin_amount = "default";

                if ($withdrawal_method == "BTC") {
                    $btc_amount = round(($amount / $btcRate), 8);
                    $coin_amount = $btc_amount;
                } else if ($withdrawal_method == "ETH") {
                    $eth_amount = round(($amount / $ethRate), 8);
                    $coin_amount = $eth_amount;
                } else if ($withdrawal_method == "USDT") {
                    $usdt_amount = round(($amount / $usdtRate), 8);
                    $coin_amount = $usdt_amount;
                }

                $account_type = 0;

                if ($account == "bonus") {
                    $balance_sql = "SELECT * FROM bonus_account_balances WHERE accountId=? LIMIT 1";
                } else if ($account == "monthly") {
                    $balance_sql = "SELECT * FROM monthly_trading_balances WHERE accountId=? LIMIT 1";
                } else if ($account == "annual") {
                    $account_type = 1;
                    $balance_sql = "SELECT * FROM annual_trading_balances WHERE accountId=? LIMIT 1";
                } else if ($account == "bot") {
                    $account_type = 2;
                    $balance_sql = "SELECT * FROM bot_trading_balances WHERE accountId=? LIMIT 1";
                }else {
                    $response = array("message" => "Invalid request!.");
                    die(json_encode($response));
                }

                $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $balance_sth->execute([$accountId]);
                $account_balances = $balance_sth->fetchAll();

                foreach ($account_balances as $key => $value) {
                    if ($account == "bonus") {
                        $usr_balance = $value['total_bonus'];
                    } else {
                        $usr_balance = $value['profit'];
                        $charges = $value['charges'];
                    }

                    $acc_balance = round($usr_balance, 2);

                    $new_balance_calc = $acc_balance - $amount;

                    if ($new_balance_calc >= 0) {

                        $sql = "SELECT * FROM app_settings WHERE action IN(?,?)";
                        $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);

                        $min_withdrawal = 0.00;
                        $max_withdrawal = 0.00;

                        if ($sth->execute(['min_withdrawal', 'max_withdrawal'])) {
                            while ($data = $sth->fetch(PDO::FETCH_ASSOC)) {
                                $action =  $data['action'];
                                $value =  $data['value'];
                                if ($action == "min_withdrawal") {
                                    $min_withdrawal = round($value, 2);
                                } else if ($action == "max_withdrawal") {
                                    $max_withdrawal = round($value, 2);
                                }
                            }
                        } else {
                            $response = array("message" => "An unexpected error occurred!.");
                            die(json_encode($response));
                        }

                        if ($amount < $min_withdrawal) {
                            $response = array("message" => 'Minimum withdrawal amount is ' . number_format($min_withdrawal, 2) . ' USD');
                            die(json_encode($response));
                        } else if ($amount > $max_withdrawal) {
                            $response = array("message" => 'Maximum withdrawal amount is ' . number_format($max_withdrawal, 2) . ' USD');
                            die(json_encode($response));
                        }
                        
                        if ($account == "bonus") {
                            $req_sql = "INSERT INTO bonus_account_withdrawals (accountId, method, coin_amount, usd, coin_address, status) VALUES (?,?,?,?,?,?)";
                        } else {
                            $req_sql = "INSERT INTO withdrawals (accountId, account, account_type, method, coin_amount, usd, coin_address, status) VALUES (?,?,?,?,?,?,?,?)";
                        }

                        if ($account == "bonus") {
                            $create_request = $conn->prepare($req_sql)->execute([$accountId, $withdrawal_method, $coin_amount, $amount, $address, 0]);
                            $withdrawal_id = $conn->lastInsertId();
                        } else {
                            $create_request = $conn->prepare($req_sql)->execute([$accountId, $account, $account_type, $withdrawal_method, $coin_amount, $amount, $address, 0]);
                            $withdrawal_id = $conn->lastInsertId();
                        }
                        if ($create_request) {
                            if ($account == "bonus") {
                                $response = array("message" => "Withdrawal request submitted.", "url" => "account");
                                die(json_encode($response));
                            }
                            $charges_amount = $amount / 100 * $charges;
                            $response = array("message" => "success", "url" => "charges-deposit?withdraw_id=$withdrawal_id&amount=$amount&charges=$charges_amount");
                            die(json_encode($response));
                        } else {
                            $response = array("message" => "An unexpected error occurred. Please try again.");
                            die(json_encode($response));
                        }
                    } else {
                        $inf_b = "You have insufficent balance. ";
                        $response = array("message" => $inf_b);
                        die(json_encode($response));
                    }
                }
            }
        } else {
            $response = array("message" => "Please enter a valid amount.");
            die(json_encode($response));
        }
    } else {
        $response = array("message" => "Invalid user information.");
        die(json_encode($response));
    }
} else {
    $response = array("message" => "Invalid request.");
    die(json_encode($response));
}