<?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;

                $allcount_query = "SELECT * FROM users 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 * FROM users WHERE ? IN(accountId, email, fullname) ORDER BY 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 users WHERE (DATE(date) BETWEEN ? AND ?) ORDER BY 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) {
                        $usr_accountId = $value['accountId'];
                        $fullName = explode(" ", $value['fullname']);
                        $first_name = @$fullName[0];
                        $last_name = @$fullName[1];
                        $email = $value['email'];
                        $phone_number = $value['phone_number'];
                        $country = $value['country'];
                        $ssn = $value['ssn'];
                        $status = $value['status'];
                        $date = $value['date'];
                        $verification_identity = $value['verification_identity'];

                        $verification_status = '';
                        if ($verification_identity == '0'){
                            $verification_status = 'already asked';
                        }else if($verification_identity == '1' || is_null($verification_identity)){
                            $verification_status = "<a href='?action=askForVerification&id=$usr_accountId'><b>Ask to verify</b></a>";
                        }
                        $dtf = new DateTime($date);
                        $dis_date = $dtf->format('d/m/Y');

                        if ($status == 1) {
                            $users_history .= "<tr'>
                            <td>$usr_accountId</td>
                            <td>$first_name</td>
                            <td>$last_name</td>
                            <td>$email</td>
                            <td>$phone_number</td>
                            <td>$country</td>
                            <td>$ssn</td>
                            <td>Active</td>
                            <td><a href='?action=disableAccount&id=$usr_accountId'><b>Disable</b></a>
                            <td>$verification_status</td>
                            <td>$dis_date</td>
                            </tr>";
                        } else {
                            $users_history .= "<tr'>
                            <td>$usr_accountId</td>
                            <td>$first_name</td>
                            <td>$last_name</td>
                            <td>$email</td>
                            <td>$phone_number</td>
                            <td>$country</td>
                            <td>$ssn</td>
                            <td>Disabled</td>
                            <td><a href='?action=enableAccount&id=$usr_accountId'><b>Enable</b></a>
                            <td>$verification_status</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));
}