<?php
session_start();

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

$accountId = $_SESSION['usr_accountId'];

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

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

        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 annual_trade_transactions WHERE accountId = :accountId ORDER BY annual_trade_transactions.date DESC LIMIT $offset, $no_of_records_per_page";
                // var_dump($sql);
                $allcount_query = "SELECT * FROM annual_trade_transactions WHERE accountId = :accountId ORDER BY annual_trade_transactions.date DESC";
                $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $allcount_fetch->execute([':accountId' => $accountId]);
                 //Calculate total pages
                 $allcount = $allcount_fetch->rowCount();
                 $totalPages = ceil($allcount / $no_of_records_per_page);

                 //Fetch  history
                //  var_dump($search_id);
                 if ($search_id != "default") {

                     $sql = "SELECT * FROM annual_trade_transactions WHERE accountId = :accountId ORDER BY annual_trade_transactions.date DESC LIMIT $offset, $no_of_records_per_page";
                     $sql = "SELECT *, annual_trade_transactions.id as mid, annual_trade_transactions.status as mis, annual_trade_transactions.date as midt FROM annual_trade_transactions INNER JOIN users ON annual_trade_transactions.accountId = users.accountId  where users.accountId = :accountId ORDER BY annual_trade_transactions.date DESC LIMIT $offset, $no_of_records_per_page";
                    //  var_dump($sql);
                     $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                     $sth->execute([':accountId' => $accountId]);
                 } else {
                     $sql = "SELECT * FROM annual_trade_transactions WHERE accountId = :accountId ORDER BY annual_trade_transactions.date DESC LIMIT $offset, $no_of_records_per_page";
                    //  var_dump($sql);
                     $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                     $sth->execute([':accountId' => $accountId]);
                 }

                 $history = $sth->fetchAll();

                 $trade_history = "";
                 $previous_trade_id = -1;
$current_trade_history = "";
$count = 0;


                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'];
        $profit = $value['profit'];
        $recent_profit = $value['recent_profit'];
        $recent_date = $value['recent_date'];
        $status = $value['mis'];
        $closed_date = $value['closed_date'];
        $date = $value['midt'];

        $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_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);
        }
        $action = '';

        $_trade_history_status = "SELECT * FROM annual_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 ($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>";
            if($type != "+Profit"){
                // $trade_history_id = "SELECT * FROM annual_trade_history WHERE id=? LIMIT 1";
                // $trade_history_id = $conn->prepare($trade_history_id, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                // $trade_history_id->execute([$value['trade_history_id']]);
                // $trade_history_id = $trade_history_id->fetchAll();
                // // var_dump($trade_history_id);
                // // $id = $trade_history_id[0]['id'];
                $id = $value['trade_history_id'];
                $action = "<b class='btn btn-xs btn-primary' onclick='profitTrade(\"$id\" , \"$accountId\")'>Profit</b> <b class='btn btn-xs btn-danger' onclick='closeTrade(\"$id\" , \"$accountId\")'>Close</b>";
                $id = '';
            }
        } else {
            $action = "None";
            $status_action = "<span class='badge badge-pill badge-soft-danger font-size-12'>Closed</span>";
        }

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

                $history2 = "<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>" . $current_trade_history;

                $current_trade_history = $history2;

            }else {

                $current_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>";

            }
            
        }else {
            $previous_trade_id = $current_trade_id;
            $trade_history .= $current_trade_history;
            $current_trade_history = "";

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

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