<?php
session_start();

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

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

    if ($_POST['accountId'] != "" && $_POST['tradeId'] != "") {

        $accountId = $_POST['accountId'];
        $tradeId = $_POST['tradeId'];

        $balance_sql = "SELECT * FROM bot_trade_history WHERE accountId=? AND id=? LIMIT 1";
        $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
        $balance_sth->execute([$accountId, $tradeId]);
        $history = $balance_sth->fetchAll();

        if (count($history) > 0) {

            foreach ($history as $key => $value) {
                $usr_trade = round($value['trade_amount'], 2);

                $datetime = date('Y-m-d H:i:s');

                $sql = 'UPDATE bot_trade_history SET status=?, closed_date=? WHERE id =? AND accountId=?';

                $stmt = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $stmt->execute([0, $datetime, $tradeId, $accountId]);

                $balance_sql = "SELECT * FROM bot_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_balance = $value['trade_amount'];

                    $acc_balance = round($usr_balance, 2);

                    $new_balance = max((round(($acc_balance - $usr_trade), 2)), 0);

                    $new_balance_sql = "UPDATE bot_trading_balances SET trade_amount=? WHERE accountId=?";
                    // $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);
                    $update_balance = true;
                    if ($update_balance) {
                        sendTradeExpiredMail($accountId,'monthly');
                        die("success");
                    } else {
                        die("An unexpected error occurred. Please try again!");
                    }
                }
            }
        } else {
            die("Invalid request!");
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}