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

$accountId = $_SESSION['adm_accountId'];

$pageno = 1;

$sql = "SELECT accountId, date FROM users ORDER BY date ASC LIMIT 1";
$sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$sth->execute([':accountId' => $accountId]);
$users = $sth->fetchAll();

foreach ($users as $key => $value) {
    $date = $value['date'];
    $dt = new DateTime($date);
    $dateFrom = $dt->format('d/m/Y');
}

$dateTo =  date("d/m/Y");

$rowperpage = 50;

$allcount_query = "SELECT * FROM bot_account_withdrawals 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 bot_account_withdrawals.*, users.accountId, users.email FROM bot_account_withdrawals INNER JOIN users ON bot_account_withdrawals.accountId = users.accountId ORDER BY bot_account_withdrawals.date DESC LIMIT 0, $rowperpage";
$sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$sth->execute();
$history = $sth->fetchAll();

$withdrawals_history = "";

if (count($history) > 0) {
    foreach ($history as $key => $value) {
        $id = $value['id'];
        $accountId = $value['accountId'];
        $email = $value['email'];
        $method = $value['method'];
        $coin_amount = $value['coin_amount'];
        $coin_address = $value['coin_address'];
        $status = $value['status'];
        $usd = $value['usd'];
        $date = $value['date'];

        $dtf = new DateTime($date);
        $dis_date = $dtf->format('d/m/Y');

        $dis_usd = number_format($usd, 2);

        if ($status == "1") {
            $withdrawals_history.="
            <tr>

            <td>$accountId</td>
            <td>$email</td>
            <td>$method</td>
            <td>$coin_amount</td>
            <td>$dis_usd</td>
            <td>$coin_address</td>

            <td>
            <span class='badge badge-pill badge-soft-success font-size-12'>Approved</span>
            </td>

            <td>None</td>
            <td>$dis_date</td>

            </tr>
            ";
        }else {

            $withdrawals_history.="<tr class='withdrawal_history_item action'>

            <td>$accountId</td>
            <td>$email</td>
            <td>$method</td>
            <td>$coin_amount</td>
            <td>$dis_usd</td>
            <td>$coin_address</td>

            <td>
            <span class='badge badge-pill badge-soft-danger  font-size-12'>Pending</span>
            </td>

            <td><b class='btn btn-xs btn-primary' onclick='approveWithdrawal(\"$id\" , \"$accountId\")'>Approve</b> <b class='btn btn-xs btn-danger' onclick='cancelWithdrawal(\"$id\" , \"$accountId\")'>Cancel</b></td>
            <td>$dis_date</td>

            </tr>";
        }
    }

}else {
    $withdrawals_history = "<tr><td colspan='9' class='tx-color-03 tx-normal text-center'>No data available</td></tr>";
}


if (isset($_GET['action']) && isset($_GET['id']) && isset($_GET['accountId']) ) {

    $action = $_GET['action'];
    $id = $_GET['id'];
    $accountId = $_GET['accountId'];

    $sql = "SELECT * FROM bot_account_withdrawals WHERE accountId = ? AND id=? LIMIT 1";
    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
    $sth->execute([$accountId, $id]);
    $history = $sth->fetchAll();

    if (count($history) > 0) {
        foreach ($history as $key => $value) {
            $status = $value['status'];
            $usd = $value['usd'];
            $status = $value['status'];

            if ($status == 0) {

                if ($action == "approveWithdrawal") {

                    $balance_sql = "SELECT * FROM bot_account_balances WHERE accountId=? LIMIT 1";
                    $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $balance_sth->execute([$accountId]);
                    $account_balances = $balance_sth->fetchAll();

                    foreach ($account_balances as $key => $value) {
                        $usr_total_bonus = $value['total_bonus'];
                        $usr_withdrawn = $value['withdrawn'];

                        $acc_total_bonus = round($usr_total_bonus, 2);
                        $acc_withdrawn = round($usr_withdrawn, 2);

                        $new_balance_calc = ($acc_total_bonus - ($acc_withdrawn + $usd));

                        if ($new_balance_calc >= 0) {

                            $new_withdrawn = round(($acc_withdrawn+$usd), 2);

                            $withdrawn_sql = "UPDATE bot_account_balances SET withdrawn=? WHERE accountId=?";

                            $update_withdrawn = $conn->prepare($withdrawn_sql)->execute([$new_withdrawn, $accountId]);

                            if ($update_withdrawn) {

                                $withdrawal_sql = "UPDATE bot_account_withdrawals SET status=? WHERE accountId=? AND id=?";

                                $update_withdrawal = $conn->prepare($withdrawal_sql)->execute([1, $accountId, $id]);

                                if ($update_withdrawal) {

                                    $req_sql = "INSERT INTO bot_account_transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";

                                    $trans_name = "Withdrawal";
                                    $type = "Approved";

                                    $create_history = $conn->prepare($req_sql)->execute([$accountId, $trans_name, $usd, $type, 0]);

                                    header('Location: bot-withdrawals');
                                    die();

                                }else {
                                    die("Unable to approve withdrawal. Please try again.");
                                }


                            }else {
                                die("An unexpected error occurred. Please try again.");
                            }

                        }else {
                         $inf_b = "Insufficent user balance. ";
                         die($inf_b);
                     }
                 }



             }else if ($action == "cancelWithdrawal") {

                $sql = 'DELETE FROM bot_account_withdrawals WHERE  accountId = ? AND id=?';
                $stmt = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $stmt->execute([$accountId, $id]);

                if ($stmt) {

                    $req_sql = "INSERT INTO bot_account_transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";

                    $trans_name = "Withdrawal";
                    $type = "Cancelled";

                    $create_history = $conn->prepare($req_sql)->execute([$accountId, $trans_name, $usd, $type, 1]);

                    header('Location: bot-withdrawals');
                    die();

                }

            }

        }

    }
}
}

?>
<!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>Withdrawals</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="#">Withdrawals</a></li>
                            </ol>
                        </nav>
                        <h4 class="mg-b-0 tx-spacing--1">Withdrawals</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 col-md-12">
                                    <div class="col-md-2">
                                        <label>Status</label>
                                        <select id="package_status" class="custom-select">
                                            <option selected value="all">All</option>
                                            <option value="pending">Pending</option>
                                            <option value="approved">Approved</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 row">
                                        <div class="col-md-6">
                                            <label>From</label>

                                            <input type="text" id="dateFrom" class="form-control"
                                                placeholder="DD/MM/YYYY" value="<?php echo ($dateFrom) ?>">
                                        </div><!-- col -->
                                        <div class="col-md-6">
                                            <label>To</label>

                                            <input type="text" id="dateTo" class="form-control" placeholder="DD/MM/YYYY"
                                                value="<?php echo ($dateTo) ?>">

                                        </div><!-- col -->
                                    </div>
                                    <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>Method</th>
                                                <th>Coin Amount</th>
                                                <th>Amount (USD)</th>
                                                <th>Coin Address</th>
                                                <th>Status</th>
                                                <th>Action</th>
                                                <th>Date</th>
                                            </tr>
                                        </thead>
                                        <tbody id="withdrawals_history">
                                            <?php echo ($withdrawals_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="withdrawal_id" value="loaded">
                                    <input type="hidden" id="withdrawal_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>
                <!-- end row -->


                <div class="modal fade" id="modalCancelWithdrawal" 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>Cancel Withdrawal?</h4>
                                    <div style="display: none;" id="pass_errorPrompt"
                                        class="alert alert-danger col-md-12" role="alert">
                                        <p></p>
                                    </div>
                                    <div class="form-group">
                                        <label>Are you sure you want to cancel the withdrawal?</label>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" style="width: 40%"
                                            data-dismiss="modal">Close</button>
                                        <button id="cancel_withdrawal_btn" style="width: 40%" type="button"
                                            class="btn btn-primary btn-block">Yes, Cancel
                                            <span style="display: none;"
                                                class="cancel_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 class="modal fade" id="modalApproveWithdrawal" 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>Approve Withdrawal?</h4>
                                    <div style="display: none;" id="pass_errorPrompt"
                                        class="alert alert-danger col-md-12" role="alert">
                                        <p></p>
                                    </div>
                                    <div class="form-group">
                                        <label>Are you sure you want to approve the withdrawal?</label>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" style="width: 40%"
                                            data-dismiss="modal">Close</button>
                                        <button id="approve_withdrawal_btn" style="width: 40%" type="button"
                                            class="btn btn-primary btn-block">Yes, Approve
                                            <span style="display: none;"
                                                class="approve_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-bot-account").prop('class');
        $("#mn-bot-account").prop('class', classes + ' active pcoded-trigger');
    });
    </script>
    <script src="../js/admin/bot_account-withdrawals.js"></script>

    </body>

</html>