<?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_trading_balances INNER JOIN users ON monthly_trading_balances.accountId = users.accountId ORDER BY monthly_trading_balances.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 monthly_trading_balances INNER JOIN users ON monthly_trading_balances.accountId = users.accountId WHERE ? IN(monthly_trading_balances.accountId, users.email) ORDER BY monthly_trading_balances.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 monthly_trading_balances INNER JOIN users ON monthly_trading_balances.accountId = users.accountId ORDER BY monthly_trading_balances.date DESC LIMIT $offset, $no_of_records_per_page";
                    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $sth->execute();
                }


                $history = $sth->fetchAll();

                $account_balances_history = "";


                if (count($history) > 0) {
                    foreach ($history as $key => $value) {
                        $accountId = $value['accountId'];
                        $email = $value['email'];
                        $usr_trade_amount = $value['trade_amount'];
                        $usr_trade_margin = $value['margin'];
                        $usr_profit = $value['profit'];
                        $charges = $value['charges'];
                        $usr_withdrawn = $value['withdrawn'];

                        $trade_amount = number_format($usr_trade_amount, 2);
                        $trade_margin = number_format($usr_trade_margin, 2);
                        $profit = number_format($usr_profit, 2);
                        $withdrawn = number_format($usr_withdrawn, 2);

                        $account_balances_history .= "<tr'>
                        <td>$accountId</td>
                        <td>$email</td>
                        <td>$trade_amount</td>
                        <td>$trade_margin</td>
                        <td>$profit</td>
                        <td>$charges%</td>
                        <td>$withdrawn</td>
                        <td><b class='btn btn-primary mr-2' onclick='editBalances(\"$accountId\", \"$usr_profit\", \"$usr_withdrawn\")'>Edit</b></td>
                        </tr>";
                    }

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