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

$accountId = $_SESSION['usr_accountId'];

$rowperpage = 50;
$pageno = 1;

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

$all_history = $allcount_fetch->fetchAll();

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


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

$account_balances_history = "";

if (count($history) > 0) {
    foreach ($history as $key => $value) {
        $id = $value['id'];
        $accountId = $value['account_id'];
        $amount = "$".number_format($value['amount']);
        $currency = $value['currency'];
        $status = $value['status'];
        $date = $value['date'];
        $account_type = $value['account_type'];
        $availed_date = $value['availed_date'];
        
        if ($currency != "USD") {
            $amount = round($value['amount'], 8);
        }

        $claim = '';
        $redeem_code = '';
        if (!is_null($availed_date)) {
            $claim = "<b class='btn mr-2' style='background-color:#f5f1f1;'>Claimed</b>";
            $redeem_code = $value['redeem_code'];
        }

        $account_balances_history .= "<tr'>
        <td>$redeem_code</td>
        <td>$amount</td>
        <td>$currency</td>
        <td>$account_type</td>
        <td>$date</td>
        <td>$availed_date</td>
        <td>$claim</td>
        </tr>";
    }
} else {
    $account_balances_history = "<tr><td colspan='6' class='tx-color-03 tx-normal text-center'>No data available</td></tr>";
}


function createRandomCode()
{

    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((float)microtime() * 1000000);
    $i = 0;
    $pass = '';

    while ($i <= 7) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }

    return $pass;
}
?>
<!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>Redeem Code</title>
    <?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><!-- 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="#">Redeem Code</a></li>
                            </ol>
                        </nav>
                        <h4 class="mg-b-0 tx-spacing--1">Redeem Code History</h4>
                    </div>

                </div>

                <div class="row row-xs">
                    <div class="col-lg-12">
                    <b class='btn btn-primary mb-4 mr-2' onclick='availRedeem()'>Claim code</b>
                        <div class="card">
                            <div class="card-body">

                                <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>Id</th > -->
                                                <th>Redeem Code</th>
                                                <th>Amount</th>
                                                <th>Currency</th>
                                                <th>Account Type</th>
                                                <th>Created Date</th>
                                                <th>Claimed Date</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody id="account_balances_history">
                                            <?php echo ($account_balances_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>

                <!-- claim redeem code modal -->
                <div class="modal fade" id="modalclaimRedeemCode" 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>Claim Redeem Code</h4>
                                    <div style="display: none;" id="errorPrompt" class="alert alert-danger col-md-12 form_feedback" role="alert">
                                        <p></p>
                                    </div>
                                    <div class="col-md-12" style="margin-top: 20px">
                                        <label>Code</label>
                                        <input id="redeem_id" name="redeem_id" type="hidden" class="form-control" placeholder="">
                                        <input id="redeem_code" name="redeem_code" 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="redeem_code_btn" style="width: 40%" type="button" class="btn btn-primary btn-block">Claim
                                            <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 = $("#redeem-code").prop('class');
            $("#redeem-code").prop('class', classes + ' active pcoded-trigger');

            var classes = $("#redeem-code").prop('class');
            $("#redeem-code").prop('class', classes + ' active pcoded-trigger');

        });
    </script>
    <script>
        function availRedeem() {
            // $("input#redeem_id").val(id);

            $('#modalclaimRedeemCode').modal({
                show: true,
                backdrop: 'static',
                keyboard: false
            });
        }

        $("#redeem_code_btn").click(function(event) {
            $("#redeem_code_btn").prop("disabled", true);

            $("#errorPrompt").hide();
            $("#errorPrompt").html("");

            // $(".profit_feedback").hide();
            var redeem_code = $("input#redeem_code").val();
            // var redeem_id = $("#redeem_id").val();

            if (redeem_code == "") {
                $(".form_feedback").html("Please fill all fields.");
                $(".form_feedback").show();
                $("input#redeem_code").focus();

                $("#redeem_code_btn").removeAttr("disabled");
                return false;
            }

            $(".save_spinner").show();

            $("input#redeem_code").prop("disabled", true);

            var form_data =
                "redeem_code=" +
                redeem_code;

            $.ajax({
                url: "../helpers/claim_redeem_code",
                type: "POST",
                data: form_data,
            }).done(function(response) {
                $("input#redeem_code").prop("disabled", false);
                // $("#redeem_id").prop("disabled", false);
                $("#redeem_code_btn").removeAttr("disabled");
                $(".save_spinner").hide();

                if (response == "success") {
                    $("input#redeem_code").val('');
                    // $("#redeem_id").val("");

                    $("#modalCreateRedeemCode").modal("toggle");

                    window.location.href = window.location.href;
                } else {
                    $("#errorPrompt").html(response);
                    $("#errorPrompt").show();
                }
            });
        });
    </script>
    <!-- <script src="../js/admin/redeem-code.js"></script> -->

    </body>

</html>