<?php
session_start();

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


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

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

        if ($conn) {
            try {

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

                $sch_status;

                if ($status == "pending") {
                    $sch_status = 0;
                } else if ($status == "approved") {
                    $sch_status = 1;
                } else if ($status == "all") {
                    $sch_status = 5;
                } else {
                    die("empty");
                }

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

                $accountId = $_SESSION['usr_accountId'];


                $total_approved_withdrawals = 0;
                $total_pending_withdrawals = 0;


                //Count earnings
                if ($sch_status == 5) {

                    $allcount_query = "SELECT * FROM withdrawals 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]);
                } else {
                    $allcount_query = "SELECT * FROM withdrawals WHERE accountId = ? AND status=? 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, $sch_status, $dateFrom, $dateTo]);
                }

                $allcount = $allcount_fetch->rowCount();

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


                //Fetch trading history

                if ($sch_status == 5) {

                    $sql = "SELECT * FROM withdrawals 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]);
                } else {
                    $sql = "SELECT * FROM withdrawals WHERE accountId = ? AND status=? 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, $sch_status, $dateFrom, $dateTo]);
                }

                $history = $sth->fetchAll();

                $withdrawals_history = "";


                if (count($history) > 0) {
                    foreach ($history as $key => $value) {
                        $id = $value['id'];
                        $account = $value['account'];
                        $method = $value['method'];
                        $coin_amount = $value['coin_amount'];
                        $usd = $value['usd'];
                        $coin_address = $value['coin_address'];
                        $status = $value['status'];
                        $date = $value['date'];

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

                        $dis_usd = number_format($usd, 2);

                        if ($status == "1") {
                            $withdrawals_history .= "
                            <tr>

                            <td>$account</td>
                            <td>$method</td>
                            <td>$coin_amount</td>
                            <td>$dis_usd</td>
                            <td>$coin_address</td>
                
                            <td>
                            <span class='badge badge-pill badge-soft-success font-size-12'>Approved</span>
                            </td>
                
                            <td>None</td>
                            <td>$dis_date</td>
                
                            </tr>
                            ";
                        } else {

                            $withdrawals_history .= "<tr>
                
                            <td>$account</td>
                            <td>$method</td>
                            <td>$coin_amount</td>
                            <td>$dis_usd</td>
                            <td>$coin_address</td>
                
                            <td>
                            <span class='badge badge-pill badge-soft-danger font-size-12'>Pending</span>
                            </td>
                
                            <td class='withdrawal_history_item_action' onclick='cancelWithdrawal($id)'>Cancel</td>
                            <td>$dis_date</td>
                
                            </tr>";
                        }
                    }

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