<?php
session_start();

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

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

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

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

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

            $balance_sql = "SELECT * FROM quarterly_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) {
                    $type = round($value['type'], 2);
                    $trade_amount = round($value['trade_amount'], 2);
                    $date = $value['date'];

                    $usr_profit = round($value['profit'], 2);

                    $profit_calc = round(($usr_profit + $profit), 2);

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

                    $sql = 'UPDATE quarterly_trade_history SET profit=?,recent_profit=?,recent_date=? WHERE id =? AND accountId=?';

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

                    $trade_history_id = $conn->lastInsertId();

                    $inv_sql = "INSERT INTO quarterly_trade_transactions (accountId, type, trade_amount,trade_history_id, profit, recent_profit, recent_date, date) VALUES (?,?,?,?,?,?,?,?)";
                    $create_inv = $conn->prepare($inv_sql)->execute([$accountId, "+Profit", $trade_amount,$tradeId, $profit_calc, $profit, $datetime, $date]);

                    $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();

                    $status = 2;
                    send_balance_mail($profit, $status,"quarterly Trading",$accountId);

                    foreach ($account_balances as $key => $value) {
                        $usr_balance = $value['profit'];

                        $acc_balance = round($usr_balance, 2);

                        $new_balance = round(($acc_balance + $profit), 2);

                        $new_balance_sql = "UPDATE quarterly_trading_balances SET profit=? WHERE accountId=?";
                        $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);

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

function send_balance_mail ($amount, $status, $account_type,$accountId) {
  global $conn;

  $usr_sql = "SELECT * FROM users WHERE accountId =? LIMIT 1";
  $usr_sth = $conn->prepare($usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
  $usr_sth->execute([$accountId]);
  $users = $usr_sth->fetchAll();

  if (count($users) > 0) {
    foreach ($users as $key => $value) {
      $email = $value['email'];

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, "accountId=$accountId&email=$email&amount=$amount&status=$status&account_type=$account_type");
      curl_setopt($ch, CURLOPT_URL, 'https://www.rocketta.io/email/send_balance_mail');
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
      curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
      curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
      curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
      curl_exec($ch);
      curl_close($ch);
    }

  }

}