<?php
session_start();

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


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

    if ((!empty($_POST['accountId'])) && (!empty($_POST['amountUSD']))) {

        if ($conn) {
            try {

                $usr_accountId = $_POST['accountId'];
                $amountUSD = round($_POST['amountUSD'], 2);
                $accountId = $_SESSION['usr_accountId'];

                if (is_numeric($amountUSD) && $amountUSD > 0) {

                    $users_sql = "SELECT * FROM users WHERE accountId=? LIMIT 1";
                    $users_sth = $conn->prepare($users_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $users_sth->execute([$usr_accountId]);
                    $users = $users_sth->fetchAll();

                    if (count($users) > 0) {

                        $balance_sql = "SELECT * FROM wallet WHERE accountId=? LIMIT 1";

                        $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) {
                            $usr_balance = $value['balance'];

                            $acc_balance = round($usr_balance, 2);

                            $new_balance_calc = round(($acc_balance - $amountUSD), 2);

                            if ($new_balance_calc >= 0) {

                                $balance_upd_sql = "UPDATE wallet SET balance=? WHERE accountId=?";

                                $update_balance = $conn->prepare($balance_upd_sql)->execute([$new_balance_calc, $accountId]);

                                if ($update_balance) {


                                    $balance_sql = "SELECT * FROM wallet WHERE accountId=? LIMIT 1";

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

                                    foreach ($account_balances as $key => $value) {
                                        $usr_balance = $value['balance'];

                                        $acc_balance = round($usr_balance, 2);

                                        $new_balance_calc = round(($acc_balance + $amountUSD), 2);

                                        if ($new_balance_calc >= 0) {

                                            $balance_upd_sql = "UPDATE wallet SET balance=? WHERE accountId=?";

                                            $update_balance = $conn->prepare($balance_upd_sql)->execute([$new_balance_calc, $usr_accountId]);

                                            if ($update_balance) {

                                                $req_sql = "INSERT INTO transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";

                                                $trans_name = "Transfer";

                                                $conn->prepare($req_sql)->execute([$accountId, "Wallet (".$usr_accountId.")", $amountUSD, $trans_name, 0]);
                                                $conn->prepare($req_sql)->execute([$usr_accountId, "Wallet (".$accountId.")", $amountUSD, $trans_name, 1]);
                                                die("success");
                                                
                                            }else {
                                                die("An unexpected error occurred. Please try again.");
                                            }

                                        }else {
                                            die("You have unsufficient balance for this transfer.");
                                        }
                                    }


                                }else {
                                    die("An unexpected error occurred. Please try again.");
                                }

                            }else {
                                die("You have unsufficient balance for this transfer.");
                            }
                        }




                        $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) {
                            $usr_balance = $value['trade_amount'];

                            $acc_balance = round($usr_balance, 2);

                            $new_balance = round(($acc_balance + $amountUSD), 2);

                            $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);

                            if ($update_balance) {

                                $inv_sql = "INSERT INTO $history_account (accountId, type, trade_amount) VALUES (?,?,?)";

                                $create_inv = $conn->prepare($inv_sql)->execute([$accountId, $package, $amount_received]);

                                $req_sql = "INSERT INTO transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";

                                $trans_name = "Trade Created";

                                $create_history = $conn->prepare($req_sql)->execute([$accountId, $package, $amountUSD, $trans_name, 1]);

                                die("success");
                            } else {
                                die("Unable to update account balance!");
                            }
                        }
                    } else {
                        die('An unexpected error occurred. Connection failed');
                    }
                } else {
                    die('Please enter a valid amount.');
                }
            } catch (PDOException $e) {
                die('An unexpected error occurred. Connection failed');
            }
        } else {
            die('An unexpected error occurred. Connection failed.');
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}


function convertDate($date)
{
    $dt = str_replace('/', '-', $date);

    return date('Y-m-d', strtotime($dt));
}