<?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 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 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 transaction_history.*, users.accountId FROM transaction_history INNER JOIN users ON transaction_history.accountId = users.accountId WHERE ? IN(transaction_history.accountId, transaction_history.name, transaction_history.type) ORDER BY 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 transaction_history.*, users.accountId FROM transaction_history INNER JOIN users ON transaction_history.accountId = users.accountId WHERE (DATE(transaction_history.date) BETWEEN ? AND ?) ORDER BY 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);
                        $dis_amount = number_format($amount, 2);

                        if ($status == 1) {
                            $dis_amount_data = "<span class='badge badge-pill badge-success'>+ &#36;$dis_amount</span>";
                        } else if ($status == 0) {
                            $dis_amount_data = "<span class='badge badge-pill badge-danger'>- &#36;$dis_amount</span>";
                        } else {
                            $dis_amount_data = "&#36;$dis_amount";
                        }

                        $transactions_history .= "
                        <tr>
                        <td>$accountId</td>
                        <td>$email</td>
                        <td>$dis_name</td>
                        <td>$dis_amount_data</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));
}