<?php
session_start();

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


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

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

        if ($conn) {
            try {

                $page = $_POST['page'];
                $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 invoices WHERE accountId = ? AND (DATE(date) BETWEEN ? AND ?) ORDER BY date DESC";
                $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $allcount_fetch->execute([$accountId, $dateFrom, $dateTo]);

                $allcount = $allcount_fetch->rowCount();

                $totalPages = ceil($allcount / $no_of_records_per_page);


                //Fetch transactions history

                $sql = "SELECT * FROM invoices WHERE accountId = ? AND (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([$accountId, $dateFrom, $dateTo]);


                $history = $sth->fetchAll();

                $invoices_history = "";


                if (count($history) > 0) {
                    foreach ($history as $key => $value) {
                        $id = $value['id'];
                        $package = $value['package'];
                        $method = $value['method'];
                        $usd_amount = $value['usd_amount'];
                        $coin_amount = $value['coin_amount'];
                        $address = $value['address'];
                        $status = $value['status'];
                        $receipt = $value['receipt'];
                        $date = $value['date'];

                        $dtf = new DateTime($date);
                        $dis_date = $dtf->format('d/m/Y');
                        $dis_amount = number_format($usd_amount, 2);

                        if ($status == 1) {
                            $action = "<span class='badge badge-pill badge-soft-success font-size-12'>Approved</span>";
                        } else if ($receipt == "default") {
                            $action = "<a class='btn btn-xs btn-primary flex-fill' href='invoice-details?receipt-id=$id&accountId=$accountId&account=main'><b>Upload Receipt</b></a>";
                        } else {
                            $action = "<span class='badge badge-pill badge-soft-warning font-size-12'>Receipt uploaded</span>";
                        }

                        $invoices_history .= "
                        <tr>
                        <td>$package</td>
                        <td>$method</td>
                        <td>$coin_amount</td>
                        <td>$dis_amount</td>
                        <td>$address</td>
                        <td>$action</td>
                        <td>$dis_date</td>
                        </tr>
                        ";
                    }

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