<?php
session_start();

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

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

    if ((!empty($_POST['amount'])) && (!empty($_POST['leverage'])) && isset($_SESSION['usr_accountId'])) {

        $accountId = $_SESSION['usr_accountId'];

        $amount = $_POST['amount'];
        $leverage = $_POST['leverage'];

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

            $amount = round($amount, 2);
            $closing_date = closed_date();

            if ($amount >= 1700) {

                $margin = 0;

                switch ($leverage) {
                    case '1:50':
                        $margin = $amount * 50;
                        break;
                    case '1:100':
                        $margin = $amount * 100;
                        break;
                    case '1:200':
                        $margin = $amount * 200;
                        break;
                    case '1:500':
                        $margin = $amount * 500;
                        break;
                    case '1:1000':
                        $margin = $amount * 1000;
                        break;
                    default:
                        die('Invalid request!');
                }

                $margin = round($margin, 2);

                $req_sql = "INSERT INTO demo_trade_history (accountId, type, trade_amount, closed_date, has_leverage, leverage, margin) VALUES (?,?,?,?,?,?,?)";

                $create_request = $conn->prepare($req_sql)->execute([$accountId, "Trade", $amount, $closing_date, 1, $leverage, $margin]);

                $req_sql = "INSERT INTO demo_trade_transactions (accountId, type, trade_amount, closed_date, has_leverage, leverage, margin) VALUES (?,?,?,?,?,?,?)";

                $create_request = $conn->prepare($req_sql)->execute([$accountId, "Trade", $amount, $closing_date, 1, $leverage, $margin]);

                if ($create_request) {
                    $balance_sql = "SELECT * FROM demo_trading_balances 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_trade_amount = round($value['trade_amount']);
                        $new_balance_calc = round(($usr_trade_amount + $amount), 2);

                        $usr_margin = round($value['margin']);
                        $new_margin_calc = round(($usr_margin + $margin), 2);

                        $trade_sql = "UPDATE demo_trading_balances SET trade_amount=?, margin=? WHERE accountId=?";
                        $conn->prepare($trade_sql)->execute([$new_balance_calc, $new_margin_calc, $accountId]);
                        die("success");
                    }
                } else {
                    die("An unexpected error occurred. Please try again.");
                }
            } else {
                die('Trade amount cannot be less than ' . number_format(1700, 2) . " USD");
            }
        } else {
            die('Please enter a valid amount.');
        }
    } else {
        die('An unexpected error occurred. Connection failed.');
    }
} else {
    die('An unexpected error occurred. Connection failed.');
}

function closed_date() {
    $currentDate = date('Y-m-d');
    $nextDate = date('Y-m-d', strtotime($currentDate . ' +31 days'));
    return $nextDate;
}