<?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'];
        $usr_invested = $value['trade_amount'];
        $usr_withdrawn = $value['withdrawn'];
        $datetime = date('Y-m-d H:i:s');
        $date = $value['date'];
        $trade_amount = round($value['trade_amount'], 2);

        // if ($approve_account == "ultimate") {
        //   $acc_balance = round($usr_balance, 8);
        //   $acc_invested = round($usr_invested, 8);
        //   $acc_withdrawn = round($usr_withdrawn, 8);
        //   $new_balance_calc = ($acc_invested - ($acc_withdrawn + $amountBTC)) + $acc_balance;
        // }else if ($approve_account == "bot") {

        //   $acc_balance = round($usr_balance, 2);
        //   $acc_withdrawn = round($usr_withdrawn, 2);
        //   $new_balance_calc = $acc_balance - ($acc_withdrawn + $amountUSD);

        // }else  {
          $acc_balance = round($usr_balance, 2);
          $acc_invested = round($usr_invested, 2);
          $acc_withdrawn = round($usr_withdrawn, 2);
          $new_balance_calc = ($acc_invested - ($acc_withdrawn + $amountUSD)) + $acc_balance;
        // }

        if ($new_balance_calc >= 0) {

          // if ($approve_account == "ultimate") {
          //   $new_withdrawn = round(($acc_withdrawn+$amountBTC), 8);

          // }else {

            $new_withdrawn = round(($acc_withdrawn+$amountUSD), 2);
          // }


          // if ($approve_account == "bot") {
          //   if ($amountUSD != $usr_withdrawn) {
          //     $trans_name = "Withdrawal";

          //     if ($amountUSD > $usr_withdrawn) {
          //       /*$type = "Approved";
          //       $status = 0;

          //       $withdrawn_calc = max(round(($amountUSD - $usr_withdrawn), 2), 0);
          //       send_balance_mail($withdrawn_calc, "0", "bot account withdrawal");*/

          //     }else {
          //       $type = "Withdrawn";
          //       $status = 0;
          //       $withdrawn_calc = round(($usr_withdrawn - $amountUSD), 2);
          //       send_balance_mail($amountUSD, "0", "bot account withdrawal");

          //     }

          //   }
          // }else if ($approve_account == "ultimate") {

          //   if ($amountBTC != $usr_withdrawn) {
          //     $trans_name = "Withdrawal";

          //     if ($amountBTC > $usr_withdrawn) {
          //       /*$type = "Approved";
          //       $status = 0;

          //       $withdrawn_calc = max(round(($amountBTC - $usr_withdrawn), 8), 0);
          //       send_balance_mail($withdrawn_calc, "0", "ultimate account withdrawal");*/

          //     }else {
          //       $type = "Withdrawn";
          //       $status = 0;
          //       $withdrawn_calc = round(($usr_withdrawn - $amountBTC), 8);
          //       send_balance_mail($amountUSD, "0", "ultimate account withdrawal");

          //     }

          //   }

          // }else {

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

              if ($amountUSD > $usr_withdrawn) {
                /*$type = "Approved";
                $status = 0;

                $withdrawn_calc = max(round(($amountUSD - $usr_withdrawn), 2), 0);
                send_balance_mail($withdrawn_calc, "0", $approve_account." account withdrawal");*/

              }else {
                $type = "Withdrawn";
                $status = 0;
                $withdrawn_calc = round(($usr_withdrawn - $amountUSD), 2);
                send_balance_mail($amountUSD, "0", $approve_account." account withdrawal");
              }
            }

          // }



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

          $update_withdrawn = $conn->prepare($withdrawn_sql)->execute([$new_withdrawn, $accountId]);

          if ($update_withdrawn) {

            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 Withdrawal", $amountUSD, "Withdrawal", 0]);
            // $create_history = $conn->prepare($req_sql)->execute([$accountId, "Profit Withdrawal", $trade_amount, $new_withdrawn, $acc_balance, $datetime, $date]);
            // var_dump([$accountId, "Profit Withdrawal", $trade_amount, '', $acc_balance, $datetime, $date]);
            // var_dump($req_sql);
            // var_dump($create_history);
            // die;
            if ($create_history) {

              die("success");

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

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

        }else {
          die("The entered amount will result in a negative balance. Please check and 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);
    }

  }

}

?>
