<?php
session_start();

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


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

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

        if ($conn) {
            try {

                $page = $_POST['page'];
                $search_id = $_POST['search_id'];

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

                $allcount_query = "SELECT * FROM monthly_trade_history INNER JOIN users ON monthly_trade_history.accountId = users.accountId ORDER BY monthly_trade_history.date DESC";
                $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $allcount_fetch->execute();

                //Calculate total pages
                $allcount = $allcount_fetch->rowCount();
                $totalPages = ceil($allcount / $no_of_records_per_page);

                //Fetch  history

                if ($search_id != "default") {

                    $sql = "SELECT *, monthly_trade_history.id as mid, monthly_trade_history.status as mis, monthly_trade_history.date as midt FROM monthly_trade_history INNER JOIN users ON monthly_trade_history.accountId = users.accountId WHERE ? IN(monthly_trade_history.accountId, users.email) ORDER BY monthly_trade_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 *, monthly_trade_history.id as mid, monthly_trade_history.status as mis, monthly_trade_history.date as midt FROM monthly_trade_history INNER JOIN users ON monthly_trade_history.accountId = users.accountId ORDER BY monthly_trade_history.date DESC LIMIT $offset, $no_of_records_per_page";
                    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $sth->execute();
                }


                $history = $sth->fetchAll();

                $trade_history = "";

                if (count($history) > 0) {
                    foreach ($history as $key => $value) {
                        $id = $value['mid'];
                        $accountId = $value['accountId'];
                        $email = $value['email'];
                        $type = $value['type'];
                        $trade_amount = $value['trade_amount'];
                        $leverage = $value['leverage'];
                        $trade_margin = $value['margin'];
                        $profit = $value['profit'];
                        $recent_profit = $value['recent_profit'];
                        $recent_date = $value['recent_date'];
                        $status = $value['mis'];
                        $closed_date = $value['closed_date'];
                        $date = $value['midt'];

                        $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 = "";
                        }

                        $dis_trade_amount = number_format($trade_amount, 2);
                        $dis_trade_margin = number_format($trade_margin, 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( abs($recent_profit), 2);
                        }
                        $action = '';

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

                        if ($status == "1") {
                            $status_action = "<span class='badge badge-pill badge-soft-success font-size-12'>Active</span>";
                            $action = "<button class='btn btn-xs btn-primary' onclick='profitTrade(\"$id\" , \"$accountId\")'>Profit</button> <button class='btn btn-xs btn-secondary' onclick='lossTrade(\"$id\", \"$accountId\")'>Loss</button> <button
                                class='btn btn-xs btn-danger' onclick='closeTrade(\"$id\" , \"$accountId\")'>Close</button>";
                        } else {
                            $action = "None";
                            $status_action = "<span class='badge badge-pill badge-soft-danger font-size-12'>Closed</span>";
                        }

                        $trade_history .= "<tr'>
                            <td>$accountId</td>
                            <td>$email</td>
                            <td>$type</td>
                            <td>$$dis_trade_amount</td>
                            <td>$leverage</td>
                        <td>$$dis_trade_margin</td>
                            <td>$$dis_profit</td>
                            <td>$dis_recent_profit</td>
                            <td>$dis_recent_date</td>
                            <td>$status_action</td>
                            <td>$action</td>
                            <td>$dis_date</td>
                            <td>$dis_closed_date</td>
                            </tr>";

                        $_trd_history = "SELECT * FROM monthly_trade_transactions WHERE trade_history_id=? AND type IN ('+Profit', '-Loss') ORDER BY recent_date
                        DESC LIMIT 5";
                        $_trd_history = $conn->prepare($_trd_history, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                        $_trd_history->execute([$id]);
                        $_trade_history = $_trd_history->fetchAll();

                        foreach ($_trade_history as $key => $value) {
                            $type2 = $value['type'];
                            $profit2 = $value['profit'];
                            $recent_profit2 = $value['recent_profit'];
                            $recent_date2 = $value['recent_date'];

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

                            $dis_profit2 = number_format($profit2, 2);
                            if ($recent_profit2 > 0) {
    $dis_recent_profit2 = "$".number_format($recent_profit2, 2);
} else {
    $dis_recent_profit2 ="-$". number_format( abs($recent_profit2), 2);
}

                            $trade_history .= "<tr'>
                                <td>$accountId</td>
                                <td>$email</td>
                                <td>$type2</td>
                                <td>$$dis_trade_amount</td>
                                <td>$leverage</td>
                        <td>$$dis_trade_margin</td>
                                <td>$$dis_profit2</td>
                                <td>$dis_recent_profit2</td>
                                <td>$dis_recent_date2</td>
                                <td>$status_action</td>
                                <td>None</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));
}