<?php
session_start();

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

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

  if((!empty($_POST['accountId'])) && (!empty($_POST['amountUSD'])) && (!empty($_POST['amountBTC'])) && (!empty($_POST['account'])) ) {

    $accountId = $_POST['accountId'];
    $amountUSD = $_POST['amountUSD'];
    $amountBTC = $_POST['amountBTC'];
    $approve_account = $_POST['account'];

    if (is_numeric($amountUSD) && $amountUSD > 0 && (is_numeric($amountUSD) && $amountBTC >= 0)) {

      $amountUSD = round($amountUSD, 2);
      $amountBTC = round($amountBTC, 8);

      if ($approve_account == "monthly") {
        $balance_sql = "SELECT * FROM monthly_trading_balances WHERE accountId=? LIMIT 1";
      }else if ($approve_account == "annually") {
        $balance_sql = "SELECT * FROM annual_trading_balances WHERE accountId=? LIMIT 1";
      }else {
        die("Invalid request! 2");
      }

      $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['profit'];

        // $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');

        if ($approve_account == "ultimate") {
          $acc_balance = round($usr_balance, 8);

          $new_balance = round(($acc_balance+$amountBTC), 8);
        }else {
          $acc_balance = round($usr_balance, 2);

          $new_balance = round(($acc_balance+$amountUSD), 2);
        }


        if ($approve_account == "ultimate") {

          if ($amountBTC != @$usr_profit) {
            $trans_name = "Profit";
            $profit_calc = max(round(($amountBTC - @$usr_profit), 2), 0);

            if ($amountBTC > @$usr_profit) {
              $type = "Top Up";
              $status = 1;
              send_balance_mail($profit_calc, "1", "ultimate account profit");
            }else {
              /*$type = "Take out";
              $status = 0;
              send_balance_mail($profit_calc, "0", "bot account profit");*/
            }

          }

        }else {

          if ($amountUSD != @$usr_profit) {
            $trans_name = "Profit";
            $profit_calc = max(round(($amountUSD - @$usr_profit), 2), 0);

            if ($amountUSD > @$usr_profit) {
              $type = "Top Up";
              $status = 1;
              send_balance_mail($profit_calc, "1", $approve_account." account profit");
            }else {
              /*$type = "Take out";
              $status = 0;
              send_balance_mail($profit_calc, "0", "bot account profit");*/
            }

          }

        }


        if ($approve_account == "monthly") {
          $balance_sql = "UPDATE monthly_trading_balances SET profit=? WHERE accountId=?";
        }else if ($approve_account == "annually") {
          $balance_sql = "UPDATE annual_trading_balances SET profit=? WHERE accountId=?";
        }

        $update_balance = $conn->prepare($balance_sql)->execute([$new_balance, $accountId]);

        if ($update_balance) {

          if ($approve_account == "monthly") {
            // $req_sql = "INSERT INTO monthly_trade_transactions (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";
            $req_sql = "INSERT INTO monthly_trade_transactions (accountId, type, trade_amount, profit, recent_profit, recent_date, date) VALUES (?,?,?,?,?,?,?)";
          }else if ($approve_account == "annually") {
            // $req_sql = "INSERT INTO annual_trade_transactions (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";
            $req_sql = "INSERT INTO annual_trade_transactions (accountId, type, trade_amount, profit, recent_profit, recent_date, date) VALUES (?,?,?,?,?,?,?)";
          }

          // $create_history = $conn->prepare($req_sql)->execute([$accountId, "Profit", $amountUSD, "Top up", 1]);
          $create_history = $conn->prepare($req_sql)->execute([$accountId, $type, $trade_amount, $profit_calc, $acc_balance, $datetime, $date]);

          if ($create_history) {

            die("success");

          }else {
            die("An unexpected error occurred. Please try again.");
          }


        }else {
          die("An unexpected error occurred. Please try again.");
        }


      }

    }else {
      die('Please enter a valid amount.');
    }

  }else {
    die('Invalid user information.');
  }

}else {
  die('Invalid request.');
}


function send_balance_mail ($amount, $status, $account_type) {
  global $accountId, $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);
    }

  }

}

?>
