<?php
session_start();

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


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

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

    if ($conn) {
      try { 

        $page = $_POST['page'];
        $search_id = $_POST['search_id'];
        $dateFrom = convertDate($_POST['dateFrom']);
        $dateTo = convertDate($_POST['dateTo']);

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

        //Count earnings

        if ($search_id != "default") {

          $allcount_query = "SELECT * FROM bonus_account_transaction_history WHERE ? IN(accountId, name, type) ORDER BY date DESC";
          $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
          $allcount_fetch->execute([$search_id]);

        }else {

          $allcount_query = "SELECT * FROM bonus_account_transaction_history WHERE (DATE(date) BETWEEN ? AND ?) ORDER BY date DESC";
          $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
          $allcount_fetch->execute([$dateFrom, $dateTo]);

        }

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

        //Fetch  history

        if ($search_id != "default") { 

          $sql = "SELECT bonus_account_transaction_history.*, users.accountId, users.email FROM bonus_account_transaction_history INNER JOIN users ON bonus_account_transaction_history.accountId = users.accountId WHERE ? IN(bonus_account_transaction_history.accountId, bonus_account_transaction_history.name, bonus_account_transaction_history.type, users.email) ORDER BY bonus_account_transaction_history.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 bonus_account_transaction_history.*, users.accountId, users.email FROM bonus_account_transaction_history INNER JOIN users ON bonus_account_transaction_history.accountId = users.accountId WHERE (DATE(bonus_account_transaction_history.date) BETWEEN ? AND ?) ORDER BY bonus_account_transaction_history.date DESC LIMIT $offset, $no_of_records_per_page";
          $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
          $sth->execute([$dateFrom, $dateTo]);
        }


        $history = $sth->fetchAll();

        $transactions_history = "";


        if (count($history) > 0) {
          foreach ($history as $key => $value) {
            $id = $value['id'];
            $accountId = $value['accountId'];
            $email = $value['email'];
            $name = $value['name'];
            $type = $value['type'];
            $amount = $value['amount'];
            $status = $value['status'];
            $date = $value['date'];

            $dtf = new DateTime($date);
            $dis_date = $dtf->format('d/m/Y');

            $dis_name = ucfirst($name);
            $dis_action = ucfirst($type);

            if ($type == "ROI") {
              $dis_amount = round($amount, 2).'%';
            }else if ($type == "Cancelled") {
              $dis_amount = '&#36;'.number_format($amount, 2);
            }else {

              if ($status == 1){

                $dis_amount = '+'.'&#36;'.number_format($amount, 2);
              }else {

                $dis_amount = '-'.'&#36;'.number_format($amount, 2);
              }

            }

            if ($status == 1) {

              $transactions_history.="
              <tr>

              <td>$accountId</td>
              <td>$email</td>
              <td>$dis_name</td>

              <td>
              <span class='primary-color'>$dis_amount</span>
              </td>

              <td>$dis_action</td>
              <td>$dis_date</td>

              </tr>
              ";

            }else {
              $transactions_history.="
              <tr>

              <td>$accountId</td>
              <td>$email</td>
              <td>$dis_name</td>

              <td>
              <span style='color:#ff3366'>$dis_amount</span>
              </td>

              <td>$dis_action</td>
              <td>$dis_date</td>

              </tr>
              ";

            }

          }

          $response = array(
            'history' => $transactions_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));
}

?>