<?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 == "open") {
                    $sch_status = 1;
                } else if ($status == "closed") {
                    $sch_status = 0;
                } 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 annual_trade_history 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 annual_trade_history 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 annual_trade_history 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 annual_trade_history 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();

                $trade_history = "";


                if (count($history) > 0) {
                    foreach ($history as $key => $value) {
                        $id = $value['id'];
                        $type = $value['type'];
                        $trade_amount = $value['trade_amount'];
                        $profit = $value['profit'];
                        $recent_profit = $value['recent_profit'];
                        $recent_date = $value['recent_date'];
                        $status = $value['status'];
                        $closed_date = $value['closed_date'];
                        $date = $value['date'];

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

                        if ($recent_date != "" || $recent_date != null) {
                            $dtf = new DateTime($recent_date);
                            $dis_recent_date = $dtf->format('d/m/Y');
                        } else {
                            $dis_recent_date = "";
                        }

                        if ($closed_date != "" || $closed_date != null) {
                            $dtf = new DateTime($closed_date);
                            $dis_closed_date = $dtf->format('d/m/Y');
                        } else {
                            $dis_closed_date = "";
                        }

                        $dis_trade_amount = number_format($trade_amount, 2);
                        $dis_profit = number_format($profit, 2);
                        if ($recent_profit > 0) {
                            $dis_recent_profit =  number_format($recent_profit, 2);
                        } else {
                            $dis_recent_profit = number_format($recent_profit, 2);
                        }

                        if ($status == "1") {
                            $status_action = "<span class='badge badge-pill badge-soft-success font-size-12'>Active</span>";
                        } else {
                            $status_action = "<span class='badge badge-pill badge-soft-danger font-size-12'>Closed</span>";
                        }

                        $trade_history .= "
                            <tr>
                
                            <td>$type</td>
                            <td>$$dis_trade_amount</td>
                            <td>$$dis_profit</td>
                            <td>$$dis_recent_profit</td>
                            <td>$dis_recent_date</td>
                
                            <td>
                            $status_action
                            </td>
                            <td>$dis_date</td>
                            <td>$dis_closed_date</td>
                
                            </tr>
                            ";
                    }

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