<?php
session_start();

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

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

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

    $accountId = $_POST['accountId'];
    $total_bonus = $_POST['total_bonus'];
    $withdrawn = $_POST['withdrawn'];

    if ((is_numeric($total_bonus) && $total_bonus >= 0) && (is_numeric($withdrawn) && $withdrawn >= 0) ) {

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

      foreach ($bonus_account_balances as $key => $value) {
        $usr_total_bonus = round($value['total_bonus'],2);
        $usr_withdrawn = round($value['withdrawn'],2);

        $total_bonus = round($total_bonus, 2);
        $withdrawn = round($withdrawn, 2);

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

        if ($total_bonus != $usr_total_bonus) {
          $trans_name = "Total bonus";

          $total_bonus_calc = max(round(($total_bonus - $usr_total_bonus), 2), 0);

          if ($total_bonus > $usr_total_bonus) {
            $type = "Top Up";
            $status = 1;
            send_balance_mail($total_bonus_calc, "1", "bonus account");
          }else {
            $type = "Take out";
            $status = 0;
            send_balance_mail($total_bonus_calc, "0", "bonus account");
          }

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

        }


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

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

            $withdrawn_calc = max(round(($withdrawn - $usr_withdrawn), 2), 0);

            send_balance_mail($withdrawn_calc, "0", "bonus account");

          }else {
            $type = "Withdrawn";
            $status = 0;
            $withdrawn_calc = round(($usr_withdrawn - $withdrawn), 2);

            send_balance_mail($withdrawn_calc, "1", "bonus account");

          }

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

        }

        $balance_sql = "UPDATE bot_account_balances SET total_bonus=?, withdrawn=? WHERE accountId=?";

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

        if ($update_balance) {
          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.');
}

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);
    }

  }

}

?>
