<?php
session_start();

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

function closed_date($type) {
    $currentDate = date('Y-m-d');
    $nextDate = '';

    switch ($type) {
        case 'monthly':
            $nextDate = date('Y-m-d', strtotime($currentDate . ' +31 days'));
            break;
        case 'quarterly':
            $nextDate = date('Y-m-d', strtotime($currentDate . ' +92 days'));
            break;
        case 'annually':
            $nextDate = date('Y-m-d', strtotime($currentDate . ' +366 days'));
            break;
        default:
            return "Invalid type argument.";
    }

    return $nextDate;
}

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) {

                $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 - $amount), 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) {
                            $closed_date = closed_date('annually');
                            $req_sql = "INSERT INTO annual_trade_history (accountId, type, trade_amount, closed_date) VALUES (?,?,?,?)";

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


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

                            $create_request = $conn->prepare($req_sql)->execute([$accountId, "Trade (Annual)", $amount, $closed_date, $trade_history_id]);

                            if ($create_request) {
                                $balance_sql = "SELECT * FROM annual_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 annual_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("An unexpected error occurred. Please try again.");
                        }
                    }else {
                        die("Insufficient funds!");
                    }
                }
            } 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.');
}