<?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;

                $sql = "SELECT * FROM bot_trade_transactions ORDER BY bot_trade_transactions.date DESC LIMIT $offset, $no_of_records_per_page";

                $allcount_query = "SELECT * FROM bot_trade_transactions ORDER BY bot_trade_transactions.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 * FROM bot_trade_transactions WHERE ? IN(accountId) ORDER BY bot_trade_transactions.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 * FROM bot_trade_transactions ORDER BY bot_trade_transactions.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 = "";
                 $previous_trade_id = -1;
$current_trade_history = "";
$count = 0;


                if (count($history) > 0) {
                    foreach ($history as $key => $value) {
                        $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['status'];
                        $closed_date = $value['closed_date'];
                        $date = $value['date'];

                        $count += 1;
        $current_trade_id = $value['trade_history_id'];

                        $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($recent_profit, 2);
                        // }
                        $_trade_history_status = "SELECT * FROM bot_trade_history WHERE id=? LIMIT 1";
                        $_trade_history_status = $conn->prepare($_trade_history_status, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                        $_trade_history_status->execute([$value['trade_history_id']]);
                        $_trade_history_status = $_trade_history_status->fetchAll();

                        if($_trade_history_status){
                            $status = $_trade_history_status[0]['status'];
                            $closed_date = $_trade_history_status[0]['closed_date'];
                        }

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

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


                        if ($current_trade_id == $previous_trade_id) {
            if ($type != "+Profit") {

                $history2 = "<tr'>
                        <td>$accountId</td>
                        <td>$type</td>
                        <td>$$dis_trade_amount</td>
                        <td>$leverage</td>
                        <td>$$dis_trade_margin</td>
                        <td>$$dis_profit</td>

                        <td>$dis_recent_date</td>
                        <td>$status_action</td>
                        <td>$dis_date</td>
                        <td>$dis_closed_date</td>
                        </tr>" . $current_trade_history;

                $current_trade_history = $history2;

            }else {

                $current_trade_history .= "<tr'>
                        <td>$accountId</td>
                        <td>$type</td>
                        <td>$$dis_trade_amount</td>
                        <td>$leverage</td>
                        <td>$$dis_trade_margin</td>
                        <td>$$dis_profit</td>

                        <td>$dis_recent_date</td>
                        <td>$status_action</td>
                        <td>$dis_date</td>
                        <td>$dis_closed_date</td>
                        </tr>";

            }

            if (count($history) == $count) {
                $previous_trade_id = $current_trade_id;
                $trade_history .= $current_trade_history;
                $current_trade_history = "";
            }
            
        }else {
            $previous_trade_id = $current_trade_id;
            $trade_history .= $current_trade_history;
            $current_trade_history = "";

            $current_trade_history = "<tr'>
                        <td>$accountId</td>
                        <td>$type</td>
                        <td>$$dis_trade_amount</td>
                        <td>$leverage</td>
                        <td>$$dis_trade_margin</td>
                        <td>$$dis_profit</td>

                        <td>$dis_recent_date</td>
                        <td>$status_action</td>
                        <td>$dis_date</td>
                        <td>$dis_closed_date</td>
                        </tr>";
        }

        if (count($history) == $count) {
            $previous_trade_id = $current_trade_id;
            $trade_history .= $current_trade_history;
            $current_trade_history = "";
        }
                    }

                    $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));
}