<?php
session_start();

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

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

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

        $accountId = $_SESSION['usr_accountId'];

        $amount = $_POST['amount'];

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

            $amount = round($amount, 2);

            if ($amount >= 1700) {
                $req_sql = "INSERT INTO quarterly_trade_history (accountId, type, trade_amount) VALUES (?,?,?)";

                $create_request = $conn->prepare($req_sql)->execute([$accountId, "Pioneer (Quarterly)", $amount]);
                $trade_history_id = $conn->lastInsertId();


                $req_sql = "INSERT INTO quarterly_trade_transactions (accountId, type, trade_amount, trade_history_id) VALUES (?,?,?,?)";

                $create_request = $conn->prepare($req_sql)->execute([$accountId, "Pioneer (Quarterly)", $amount,$trade_history_id]);

                if ($create_request) {
                    $balance_sql = "SELECT * FROM quarterly_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);

                        $trade_sql = "UPDATE quarterly_trading_balances SET trade_amount=? WHERE accountId=?";

                        $conn->prepare($trade_sql)->execute([$new_balance_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.');
}