<?php
session_start();

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


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

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

    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;

        $accountId = @$_SESSION['usr_accountId'];

        $allcount_query = "SELECT * FROM kyc_documents WHERE full_legal_name <> 'default' AND (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 kyc_documents.*, users.accountId, users.email FROM kyc_documents INNER JOIN users ON kyc_documents.accountId = users.accountId WHERE kyc_documents.full_legal_name <> 'default' AND ? IN(kyc_documents.accountId, users.email) ORDER BY kyc_documents.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 kyc_documents.*, users.accountId, users.email FROM kyc_documents INNER JOIN users ON kyc_documents.accountId = users.accountId WHERE kyc_documents.full_legal_name <> 'default' AND (DATE(kyc_documents.date) BETWEEN ? AND ?) ORDER BY kyc_documents.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();

        $users_history = "";


        if (count($history) > 0) {
          foreach ($history as $key => $value) {
            $accountId = $value['accountId'];
            $email = $value['email'];
            $ssn = $value['ssn'];
            $full_legal_name = $value['full_legal_name'];
            $nationality = $value['nationality'];
            $date_of_birth = $value['date_of_birth'];
            $address = $value['address'];
            $mobile_number = $value['mobile_number'];
            $email_address = $value['email_address'];
            $status  = $value['status'];
            $date = $value['date'];

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

            if ($status == 1) {
              $action = "<span class='badge badge-pill badge-soft-success primary-color'>Approved</span>";
            }else {
              $action = "<a class='btn btn-xs btn-primary flex-fill' href='review-identity?accountId=$accountId'><b>Approve</b></a> <a class='btn btn-xs btn-danger flex-fill' href='?action=decline&accountId=$accountId'><b>Decline</b></a>";
            }

            $users_history.="
            <tr>
            <td>$accountId</td>
            <td>$email</td>
            <td>$ssn</td>
            <td>$full_legal_name</td>
            <td>$nationality</td>
            <td>$date_of_birth</td>
            <td>$address</td>
            <td>$mobile_number</td>
            <td>$email_address</td>
            <td>$action</td>
            <td>$dis_date</td>
            </tr>
            ";

          }

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