<?php
session_start();

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


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

  if((!empty($_POST['page'])) && (!empty($_POST['search_id'])) ) {

    if ($conn) {
      try {  

        $page = $_POST['page'];
        $search_id = $_POST['search_id'];

        $no_of_records_per_page = 50;
        $offset = ($page-1) * $no_of_records_per_page;

        $allcount_query = "SELECT * FROM bonus_account_balances INNER JOIN users ON bonus_account_balances.accountId = users.accountId ORDER BY bonus_account_balances.date DESC";
        $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
        $allcount_fetch->execute();

        //Calculate total pages
        $allcount = $allcount_fetch->rowCount();
        $totalPages = ceil($allcount / $no_of_records_per_page);

        //Fetch  history

        if ($search_id != "default") {

          $sql = "SELECT * FROM bonus_account_balances INNER JOIN users ON bonus_account_balances.accountId = users.accountId WHERE ? IN(bonus_account_balances.accountId, users.email) ORDER BY bonus_account_balances.date DESC LIMIT $offset, $no_of_records_per_page";
          $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
          $sth->execute([$search_id]);

        }else {
          $sql = "SELECT * FROM bonus_account_balances INNER JOIN users ON bonus_account_balances.accountId = users.accountId ORDER BY bonus_account_balances.date DESC LIMIT $offset, $no_of_records_per_page";
          $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
          $sth->execute();
        }


        $history = $sth->fetchAll();

        $account_balances_history = "";


        if (count($history) > 0) {
          foreach ($history as $key => $value) {
            $accountId = $value['accountId'];
            $email = $value['email'];
            $usr_total_bonus = $value['total_bonus'];
            $usr_withdrawn = $value['withdrawn'];

            $total_bonus = number_format($usr_total_bonus, 2);
            $withdrawn = number_format($usr_withdrawn, 2);

            $balance_calc = $usr_total_bonus - $usr_withdrawn;

            $balance = number_format($balance_calc, 2);

            $account_balances_history.="<tr'>
            <td>$accountId</td>
            <td>$email</td>
            <td>$total_bonus</td>
            <td>$withdrawn</td>
            <td>$balance</td>
            <td><b class='btn btn-primary mr-2' onclick='editBalances(\"$accountId\" , \"$usr_total_bonus\", \"$usr_withdrawn\")'>Edit</b></td>
            </tr>";

          }

          $response = array(
            'history' => $account_balances_history,
            'total_pages' => $totalPages,
          );

          echo (json_encode($response));

        }else {
          echo "empty";
        }

      } catch(PDOException $e) {
        die('An unexpected error occurred. Connection failed');
      }
    }else {
      die('An unexpected error occurred. Connection failed.');
    }
  } else {
    die('Invalid user information.');
  }
}else {
  die('Invalid request.');
}


function convertDate($date) {
 $dt = str_replace('/', '-', $date);

 return date('Y-m-d', strtotime($dt));
}

?>