<?php
require("../includes/db_connect.php");
require_once("includes/admin_session_token.php");

$accountId = $_SESSION['adm_accountId'];


$rowperpage = 50;
$pageno = 1;

$allcount_query = "SELECT * FROM monthly_trade_transactions ORDER BY date DESC";
$allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$allcount_fetch->execute();
$allcount = $allcount_fetch->rowCount();

$all_history = $allcount_fetch->fetchAll();

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


//Fetch history
// $sql = "SELECT * FROM monthly_trade_history INNER JOIN users ON monthly_trade_history.accountId = users.accountId ORDER BY monthly_trade_history.date DESC LIMIT 0, $rowperpage";
$sql = "SELECT * FROM monthly_trade_transactions ORDER BY monthly_trade_transactions.date DESC LIMIT 0, $rowperpage";
$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 monthly_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>";

            }
            
        }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 = "";
        }
    }
} else {
    $trade_history = "<tr><td colspan='10' class='tx-color-03 tx-normal text-center'>No data available</td></tr>";
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Monthly Trading Transactionss History</title>
    <?php require_once("includes/header.php"); ?>

    <div class="content ht-100v pd-0">
        <div class="content-header">
        </div><!-- content-header -->

        <div class="content-body">
            <div class="container pd-x-0">
                <div class="d-sm-flex align-items-center justify-content-between mg-b-20 mg-lg-b-25 mg-xl-b-30">
                    <div>
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb breadcrumb-style1 mg-b-10">
                                <li class="breadcrumb-item"><a href="#">Trading History</a></li>
                            </ol>
                        </nav>
                        <h4 class="mg-b-0 tx-spacing--1">Monthly Trading Transactionss History</h4>
                    </div>

                </div>

                <div class="row row-xs">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">


                                <div class="row col-xl-12">
                                    <div class="col-md-4 search-field" style="padding-top: 30px; margin-bottom: 10px">

                                        <input type="text" id="search_field" class="form-control"
                                            placeholder="Search account ID, Email" name="search">
                                        <button id="search_button" class="btn" type="button">
                                            <i class="search-icon" data-feather="search"></i></i>
                                        </button>
                                    </div>
                                </div>

                                <div class="table-responsive col-md-12" style="margin-top: 30px">
                                    <table class="table table-centered table-nowrap mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Account ID</th>
                                                <!-- <th>Email</th> -->
                                                <th>Type</th>
                                                <th>Trade Amount</th>
                                                <th>Leverage</th>
                                                <th>Margin</th>
                                                <th>Profit</th>
                                                <!-- <th>Recent Profit</th> -->
                                                <th>Profit Date</th>
                                                <th>Status</th>
                                                <th>Open Date</th>
                                                <th>Closed Date</th>
                                            </tr>
                                        </thead>
                                        <tbody id="trade_history">
                                            <?php echo ($trade_history); ?>
                                        </tbody>
                                    </table>
                                    <input type="hidden" id="history_page" value="1">
                                    <input type="hidden" id="total_pages" value="<?php echo ($totalPages); ?>">
                                    <input type="hidden" id="all_history" value="<?php echo ($allcount); ?>">
                                    <input type="hidden" id="loading_status" value="loaded">

                                    <input type="hidden" id="balance_account_id" value="loaded">
                                </div>
                                <div class="col-md-12" style="margin-left: auto; margin-right: auto; margin-top: 20px">
                                    <div class="" style="float: right;">
                                        <nav aria-label="Page navigation example">
                                            <ul id="pagination" class="pagination pagination-circle mg-b-0" <?php if ($totalPages < 2) {
                                                                                                                echo "style='display: none'";
                                                                                                            } ?>>
                                                <li id="prev_history" class="page-item <?php if ($pageno <= 1) {
                                                                                            echo 'disabled';
                                                                                        } ?>">
                                                    <a class="page-link page-link-icon"
                                                        href="javascript:function previous() { return false; }"><i
                                                            data-feather="chevron-left"></i></a>
                                                </li>
                                                <li id="next_history" class="page-item <?php if ($pageno >= $totalPages) {
                                                                                            echo 'disabled';
                                                                                        } ?>">
                                                    <a class="page-link page-link-icon"
                                                        href="javascript:function next() { return false; }"><i
                                                            data-feather="chevron-right"></i></a>
                                                </li>
                                            </ul>
                                        </nav>
                                    </div><!-- df-example -->
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal fade" id="modalEditBalances" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered wd-sm-400" role="document">
                        <div class="modal-content">
                            <div class="modal-body pd-20 pd-sm-40">
                                <a href="" role="button" class="close pos-absolute t-15 r-15" data-dismiss="modal"
                                    aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </a>

                                <div>
                                    <h4>Edit History</h4>
                                    <div style="display: none;" id="balance_errorPrompt"
                                        class="alert alert-danger col-md-12" role="alert">
                                        <p></p>
                                    </div>
                                    <div class="col-md-12" style="margin-top: 20px">
                                        <label>Profit</label>
                                        <input id="profit" type="text" class="form-control" placeholder="">
                                    </div>
                                    <div class="col-md-12" style="margin-top: 20px">
                                        <label>Withdrawn</label>
                                        <input id="withdrawn" type="text" class="form-control" placeholder="">
                                    </div>
                                    <div class="modal-footer" style="margin-top: 20px">
                                        <button type="button" class="btn btn-secondary" style="width: 40%"
                                            data-dismiss="modal">Close</button>
                                        <button id="save_btn" style="width: 40%" type="button"
                                            class="btn btn-primary btn-block">Save Changes
                                            <span style="display: none;"
                                                class="save_spinner spinner-border spinner-border-sm" role="status"
                                                aria-hidden="false"></span>
                                            <span class="sr-only">Please wait...</span>
                                        </button>
                                    </div>

                                </div>
                            </div><!-- modal-body -->
                        </div><!-- modal-content -->
                    </div><!-- modal-dialog -->
                </div><!-- modal -->
            </div><!-- container -->

        </div>
    </div>

    <?php require_once("includes/footer.php"); ?>
    <script type="text/javascript">
    $(document).ready(function() {
        var classes = $("#mn-trading-history").prop('class');
        $("#mn-trading-history").prop('class', classes + ' active pcoded-trigger');

        var classes = $("#mn-demo-trading-history").prop('class');
        $("#mn-demo-trading-history").prop('class', classes + ' active pcoded-trigger');

    });
    </script>
    <script src="../js/admin/monthly-trading-transections-history.js?ver=<?php echo (rand()); ?>"></script>

    </body>

</html>