<?php
session_start();

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

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

    if ($_POST['accountId'] != "" && $_POST['trade_amount'] && $_POST['profit'] != "" && $_POST['charges'] != "" && $_POST['withdrawn'] != "") {

        $accountId = $_POST['accountId'];
        $trade_amount = $_POST['trade_amount'];
        $profit = $_POST['profit'];
        $charges = $_POST['charges'];
        $withdrawn = $_POST['withdrawn'];

        if ((is_numeric($trade_amount) && $trade_amount >= 0) && (is_numeric($profit) && $profit >= 0) && (is_numeric($withdrawn) && $withdrawn >= 0)) {

            $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]);
            $annually_trading_balances = $balance_sth->fetchAll();

            foreach ($annually_trading_balances as $key => $value) {
                $usr_profit = round($value['profit'], 2);
                $usr_withdrawn = round($value['withdrawn'], 2);

                $trade_amount = round($trade_amount, 2);
                $profit = round($profit, 2);
                $withdrawn = round($withdrawn, 2);

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

                if ($profit != $usr_profit) {
                    $trans_name = "Profit (Annually)";

                    if ($profit > $usr_profit) {
                        $type = "Top Up";
                        $status = 1;
                    } else {
                        $type = "Take out";
                        $status = 0;
                    }

                    $profit_calc = max(round(($profit - $usr_profit), 2), 0);

                    $create_history = $conn->prepare($req_sql)->execute([$accountId, $trans_name, $profit_calc, $type, $status]);
                }

                if ($withdrawn != $usr_withdrawn) {
                    $trans_name = "Withdrawal (Annually)";

                    if ($withdrawn > $usr_withdrawn) {
                        $type = "Approved";
                        $status = 0;

                        $withdrawn_calc = max(round(($withdrawn - $usr_withdrawn), 2), 0);
                    } else {
                        $type = "Withdrawn";
                        $status = 0;
                        $withdrawn_calc = round(($usr_withdrawn - $withdrawn), 2);
                    }
                    $create_history = $conn->prepare($req_sql)->execute([$accountId, $trans_name, $withdrawn_calc, $type, $status]);
                }

                $balance_sql = "UPDATE annual_trading_balances SET trade_amount=?, profit=?, charges=?, withdrawn=? WHERE accountId=?";

                $update_balance = $conn->prepare($balance_sql)->execute([$trade_amount, $profit, $charges, $withdrawn, $accountId]);

                $update_history_sql = "UPDATE annual_trade_history SET trade_amount=? WHERE trade_amount=? AND accountId=?";
                
                $update_trans_sql = "UPDATE annual_trade_transactions SET trade_amount=? WHERE trade_amount=? AND accountId=?";

                $update_balance = $conn->prepare($balance_sql)->execute([$trade_amount, $profit, $charges, $withdrawn, $accountId]);
                
                $update_history = $conn->prepare($update_history_sql)->execute([$trade_amount, $usr_trade_amount, $accountId]);
                
                $update_trans = $conn->prepare($update_trans_sql)->execute([$trade_amount, $usr_trade_amount, $accountId]);

                if ($update_balance && $update_history && $update_trans) {
                    die("success");
                } else {
                    die("An unexpected error occurred. Please try again.");
                }
            }
        } else {
            die('Please enter valid amounts. Avoid commas and negative value inputs.');
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}