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

$accountId = $_SESSION['usr_accountId'];

$pageno = 1;

$sql = "SELECT accountId, date FROM users WHERE accountId = :accountId 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 WHERE accountId = :accountId";
$allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$allcount_fetch->execute([':accountId' => $accountId]);
$allcount = $allcount_fetch->rowCount();

$all_history = $allcount_fetch->fetchAll();

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


//Fetch Withdrawals
$sql = "SELECT * FROM bot_account_withdrawals WHERE accountId = :accountId ORDER BY date DESC LIMIT 0, $rowperpage";
$sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$sth->execute([':accountId' => $accountId]);
$history = $sth->fetchAll();

$withdrawals_history = "";

if (count($history) > 0) {
  foreach ($history as $key => $value) {
    $id = $value['id'];
    $method = $value['method'];
    $coin_amount = $value['coin_amount'];
    $usd = $value['usd'];
    $coin_address = $value['coin_address'];
    $status = $value['status'];
    $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>$method</td>
      <td>$coin_amount</td>
      <td>$dis_usd</td>
      <td>$coin_amount</td>

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

      <td>Cancel</td>
      <td>$dis_date</td>

      </tr>
      ";
    }else {

      $withdrawals_history.="<tr class='withdrawal_history_item action' onclick='cancelWithdrawal($id)'>

      <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>Cancel</td>
      <td>$dis_date</td>

      </tr>";
    }

  }

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


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

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

  if ($action == "cancelWithdrawal") {
    $accountId = $_SESSION['usr_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'];

        if ($status == 0) {

          $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>
    <link rel="stylesheet" href="../css/bootstrap-select-country.min.css" />
    <link rel="stylesheet" href="../build/css/intlTelInput.css">

    <?php require_once("includes/header.php"); ?>


    <div class="content ht-100v pd-0">
        <div class="content-header center">
            <img src="../img/logo-white.png" class="aside-logo" style="width: 160px;" />
        </div>
        <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="account">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">
                                    <div class="col-md-3">
                                        <label>Status</label>
                                        <select id="package_status" class="js-example-basic-single form-control">
                                            <option selected value="all">All</option>
                                            <option value="open">Open</option>
                                            <option value="closed">Closed</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>

                                <!-- <div class="col-xl-12" style="margin-top: 20px">
                                  <button class="btn btn-sm btn-primary btn-uppercase withdraw" style="padding-top: 7px; padding-bottom: 7px; padding-right: 15px; padding-left: 15px; font-size: .8125rem; font-weight: 600;">Request Withdrawal</button>
                                </div> -->

                                <div class="table-responsive" style="margin-top: 30px">
                                    <table class="table table-centered table-nowrap mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Method</th>
                                                <th>Coin Amount</th>
                                                <th>USD</th>
                                                <th>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="cancel_id" value="loaded">
                                </div>
                                <div class="col-md-10" 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>
        </div><!-- content-body -->
    </div><!-- content -->

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

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

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

    });
    </script>

    <script src="../js/bot-withdrawals.js"></script>

    </body>

</html>