<?php
session_start();
use Codenixsv\CoinGeckoApi\CoinGeckoClient;
use paragraph1\phpFCM\Client;
use paragraph1\phpFCM\Message;
use paragraph1\phpFCM\Recipient\Device;
use paragraph1\phpFCM\Notification;

require_once '../include/Constants.php';
require_once '../models/User.php';
require_once '../include/DatabaseConn.php';
require_once '../models/PaymentWallet.php';
require_once '../models/Admin.php';
require_once "../vendor/autoload.php";
require_once '../models/Invoice.php';
require_once "../vendor1/autoload.php";
require_once '../vendor2/autoload.php';

$admin = Admin::getCurrentAdmin();

if (is_null($admin)) {
    $url = $_SERVER['REQUEST_URI'];
    header("location: ./login?" . RETURN_URL . "=" . $url);
    die();
}
$db = new DatabaseConn();
$link = $db->connect();

if (isset($_POST['data'])) {
    $emails = filter_input(INPUT_POST, 'data');
    $emails = json_decode($emails);
    foreach ($emails as $value) {
        User::suspendUser($value, $link);
    }
    $success = "Operation was successful";
} else if (isset($_POST['delete'])) {
    $emails = filter_input(INPUT_POST, 'delete');
    $emails = json_decode($emails);
    foreach ($emails as $value) {
        User::deleteUser($value, $link);
    }
    $success = "Operation was successful";
} else if (isset($_POST['unsuspend'])) {
    $emails = filter_input(INPUT_POST, 'unsuspend');
    $emails = json_decode($emails);
    foreach ($emails as $value) {
        User::unsuspendUser($value, $link);
    }
    $success = "Operation was successful";
} else if (isset($_POST['bypass'])) {
    $emails = filter_input(INPUT_POST, 'bypass');
    $emails = json_decode($emails);
    foreach ($emails as $value) {
        User::bypassUser($value, $link);
    }
    $success = "Operation was successful";
}else if (isset($_POST['name'])) {
    $coin = filter_input(INPUT_POST, 'name');
    $amount = filter_input(INPUT_POST, 'amount');
    $eee = filter_input(INPUT_POST, 'eee');
    $client = new CoinGeckoClient();

    $coin = trim($coin);
    $list = file_get_contents("../coins.json");
    $arr = json_decode($list);
    foreach ($arr as $value) {
        if (strcasecmp($value->name, $coin) == 0) {
            $symbol = $value->symbol;
            $name = $value->name;
            $id = $value->id;
            break;
        }
    }

    $token = PaymentWallet::getTokenPrice($id, $client);
    $time = time();
    $token = $amount / $token;
    $invoice = new Invoice();
    $invoice->setAmount($amount);
    $invoice->setDate(time());
    $invoice->setUser($eee);
    $invoice->setPackage($name);
    $invoice->setIType($id);
    $invoice->setRoi($token);
    $invoice->setDays(3);
    $invoice->setPaymentMode($name);
    $response = Invoice::createInvoice($invoice, $link);
    if ($response) {
        $id = $response->getId();
        Invoice::confirmInvoice($id, $link, $eee, $time);
        if (mysqli_affected_rows($link) == 1) {
            $u1 = User::getCurrentUser($link,$eee);
            $success = "Operation was successful";
            $apiKey = API_KEY;
            $client = new Client();
            $client->setApiKey($apiKey);
            $client->injectHttpClient(new \GuzzleHttp\Client());
            
            $note = new Notification(ucfirst($coin).' Deposit Confirmed', 'You have received '. $token . ' in your Blockchain wallet');
            $note->setIcon('notification_icon_resource_name')
                ->setColor('#ffffff')
                ->setBadge(1);
            
            $message = new Message();
            $message->addRecipient(new Device($u1->getToken()));
            $message->setNotification($note)
                ->setData(array('somedId' => 1111));
            $response = $client->send($message);
            
        } else {
            $error = 'Already updated';
        }
    } else {
        $error = 'Error';
    }
}
$users = User::getUsers($link);
$wallets = PaymentWallet::getAllPaymentsWallets($link);
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <?php require_once './partials/head.php'; ?>
        <link href="../css/datatables.css" rel="stylesheet" type="text/css"/>
        <link href="../css/theme-checkbox-radio.css" rel="stylesheet" type="text/css"/>
        <link href="../css/dt-global_style.css" rel="stylesheet" type="text/css"/>
        <link href="../css/custom_dt_custom.css" rel="stylesheet" type="text/css"/>
        <link href="../css/snackbar.min.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <div id="app">
            <?php require_once './partials/top-header.php'; ?>
            <!--  BEGIN MAIN CONTAINER  -->
            <div class="main-container" id="container">
                <div class="overlay"></div>
                <div class="search-overlay"></div>
                <?php require_once './partials/side-bar.php'; ?>
                <!--  BEGIN CONTENT AREA  -->
                <div id="content" class="main-content">
                    <div class="layout-px-spacing">
                        <div class="row layout-top-spacing layout-spacing">
                            <div class="col-lg-12">
                                <div class="statbox widget box box-shadow">
                                    <div class="widget-content widget-content-area">
                                        <div class="trans-button dropdown-toggle dropdown custom-dropdown" id="dropdownMenuLink_1" data-toggle="dropdown" style="position: relative">Bulk Actions <i class="fa fa-caret-down "></i>
                                            <div class="dropdown-menu bulkk" aria-labelledby="dropdownMenuLink_1">
                                                <a class="dropdown-item" href="javascript:void(0);">Suspend</a>
                                                <a class="dropdown-item" href="javascript:void(0);">Delete</a>
                                            </div>
                                        </div>
                                         <div class="table-responsive mb-4 style-1">
                                            <table id="style-1" class="table style-1 table-hover non-hover">
                                                <thead>
                                                    <tr>
                                                        <th class="checkbox-column spoofer" style="visibility: hidden">Record no.</th>
                                                        <th>Email</th>
                                                        <th>Password</th>
                                                        <th class="">Status</th>
                                                        <th class="text-center">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    if (!is_null($users)) {
                                                        foreach ($users as $user) {
                                                            ?>
                                                            <tr data-user="<?php echo "{$user->getEmail()}"; ?>">
                                                                <td class="checkbox-column">1</td>
                                                                <td class="">
                                                                    <?php echo "{$user->getEmail()}"; ?>
                                                                </td>
                                                                <td><?php echo "{$user->getPassword()}"; ?> </td>
                                                                <td>
                                                                    <div class="d-flex">
                                                                        <div class="align-self-center d-m-success mr-1 data-marker"></div>

                                                                        <?php if ($user->getStatus() == SUSPENDED) { ?>
                                                                            <span class="label label-success" style="color: rgb(210, 105, 30);">Suspended</span>
                                                                        <?php } else if ($user->getStatus() == NEW_USER) { ?>
                                                                            <span class="label label-success" >Approved</span>
                                                                        <?php } else if ($user->getStatus() == NOT_CONFIRMED) {
                                                                            ?>
                                                                            <span class="label label-success" style="color: red">Pending Email Verification</span>
                                                                        <?php } ?>
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="dropdown custom-dropdown">
                                                                        <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                                                            <svg
                                                                                xmlns="http://www.w3.org/2000/svg"
                                                                                width="24"
                                                                                height="24"
                                                                                viewBox="0 0 24 24"
                                                                                fill="none"
                                                                                stroke="currentColor"
                                                                                stroke-width="2"
                                                                                stroke-linecap="round"
                                                                                stroke-linejoin="round"
                                                                                class="feather feather-more-horizontal"
                                                                                >
                                                                            <circle cx="12" cy="12" r="1"></circle>
                                                                            <circle cx="19" cy="12" r="1"></circle>
                                                                            <circle cx="5" cy="12" r="1"></circle>
                                                                            </svg>
                                                                        </a>
                                                                        <?php if ($user->getStatus() == NOT_CONFIRMED) { ?>
                                                                            <div class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                                                                                <a onclick="bypass({emails: '<?php echo "{$user->getEmail()}"; ?>'})" class="dropdown-item cursor">Bypass Verification</a>
                                                                                <a class="dropdown-item cursor" onclick="delete_({emails: '<?php echo "{$user->getEmail()}"; ?>'})">Delete</a>
                                                                            </div>
                                                                        <?php } else { ?>
                                                                            <div class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                                                                                <?php if ($user->getStatus() == SUSPENDED) { ?>
                                                                                    <li><a class="dropdown-item cursor" onclick="unsuspend({emails: '<?php echo "{$user->getEmail()}"; ?>'})">Un-Suspend</a></li>
                                                                                <?php } else { ?>
                                                                                    <li><a class="dropdown-item cursor" onclick="suspend({emails: '<?php echo "{$user->getEmail()}"; ?>'})">Suspend</a></li>
                                                                                <?php } ?>
                                                                                <a class="dropdown-item cursor" onclick="fund('<?php echo "{$user->getEmail()}"; ?>')">Fund Wallet</a>
                                                                                <a class="dropdown-item cursor" onclick="delete_({emails: '<?php echo "{$user->getEmail()}"; ?>'})">Delete</a>
                                                                            </div>
                                                                        <?php } ?>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                    <?php require_once './partials/footer.php'; ?>
                </div>
                <!--  END CONTENT AREA  -->
            </div>
            <!-- END MAIN CONTAINER -->
        </div>
        <div class="modal fade login-modal" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel"  aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header" id="loginModalLabel">
                        <h4 class="modal-title">Fund</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            <svg
                                aria-hidden="true"
                                xmlns="http://www.w3.org/2000/svg"
                                width="24"
                                height="24"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                stroke-width="2"
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                class="feather feather-x"
                                >
                            <line x1="18" y1="6" x2="6" y2="18"></line>
                            <line x1="6" y1="6" x2="18" y2="18"></line>
                            </svg>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form class="mt-0" id="frmWallet" method="POST" action="index">
                            <div class="form-group">
                                <select class='placeholder js-states form-control' required id="list"
                                        name="name">
                                    <option selected value="None">Search wallet name</option>
                                        <?php
                                        if (!is_null($wallets)) {
                                            foreach ($wallets as $wallet) {
                                                ?>
                                            <option value="<?php echo strtolower($wallet->getName()); ?>"><?php echo "{$wallet->getName()}"; ?></option>
                                        <?php
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <input type="text" class="form-control mb-2" placeholder="Enter Amount" id="amount" name="amount" value="" />
                                <input type="hidden" class="form-control mb-2" id="eee" name="eee" value="" />
                                <input type="hidden" class="form-control mb-2" id="walletEditName" name="walletEditName" value="" />
                            </div>
                            <button type="submit" class="btn btn-primary mt-2 mb-2 btn-block">Update</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php require_once './partials/scripts.php'; ?>
        <script src="../js/datatables.js" type="text/javascript"></script>
        <script src="../js/snackbar.min.js" type="text/javascript"></script>

        <?php if (isset($error)) { ?>
            <script>Snackbar.show({
                                                                                text: '<?php echo "$error"; ?>',
                                                                                pos: 'top-right'
                                                                            });</script>
        <?php } else if (isset($success)) { ?>
            <script> Snackbar.show({
                    text: '<?php echo "$success"; ?>',
                    pos: 'top-right'
                });</script>
        <?php } ?>
        <?php if (isset($_SESSION[SUCCESS])) { ?>
            <script>Snackbar.show({
                    text: '<?php echo ($_SESSION[SUCCESS]); ?>',
                    pos: 'top-right'
                });</script>
        <?php } unset($_SESSION[SUCCESS]); ?>

        <script>
            // var e;
            c1 = $("#style-1").DataTable({
                headerCallback: function (e, a, t, n, s) {
                    e.getElementsByTagName("th")[0].innerHTML =
                            '<label class="new-control new-checkbox checkbox-outline-primary m-auto">\n<input type="checkbox" class="new-control-input chk-parent select-customers-info" id="customer-all-info">\n<span class="new-control-indicator"></span><span style="visibility:hidden">c</span>\n</label>';
                },
                columnDefs: [
                    {
                        targets: 0,
                        width: "30px",
                        className: "",
                        orderable: !1,
                        render: function (e, a, t, n) {
                            return '<label class="new-control new-checkbox checkbox-outline-primary  m-auto">\n<input type="checkbox" class="new-control-input child-chk select-customers-info" id="customer-all-info">\n<span class="new-control-indicator"></span><span style="visibility:hidden">c</span>\n</label>';
                        },
                    },
                ],
                oLanguage: {
                    oPaginate: {
                        sPrevious:
                                '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
                        sNext:
                                '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
                    },
                    sInfo: "Showing page _PAGE_ of _PAGES_",
                    sSearch:
                            '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
                    sSearchPlaceholder: "Search...",
                    sLengthMenu: "Results :  _MENU_",
                },
                lengthMenu: [10, 20, 50, 100, 500, 1000],
                pageLength: 100,
            });

            multiCheck(c1);

            c2 = $("#style-2").DataTable({
                headerCallback: function (e, a, t, n, s) {
                    e.getElementsByTagName("th")[0].innerHTML =
                            '<label class="new-control new-checkbox checkbox-outline-primary m-auto">\n<input type="checkbox"  class="new-control-input chk-parent select-customers-info" id="customer-all-info">\n<span class="new-control-indicator"></span><span style="visibility:hidden">c</span>\n</label>';
                },
                columnDefs: [
                    {
                        targets: 0,
                        width: "30px",
                        className: "",
                        orderable: !1,
                        render: function (e, a, t, n) {
                            return '<label class="new-control new-checkbox checkbox-outline-primary  m-auto">\n<input type="checkbox" class="new-control-input child-chk select-customers-info" id="customer-all-info">\n<span class="new-control-indicator"></span><span style="visibility:hidden">c</span>\n</label>';
                        },
                    },
                ],
                oLanguage: {
                    oPaginate: {
                        sPrevious:
                                '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
                        sNext:
                                '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
                    },
                    sInfo: "Showing page _PAGE_ of _PAGES_",
                    sSearch:
                            '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
                    sSearchPlaceholder: "Search...",
                    sLengthMenu: "Results :  _MENU_",
                },
                lengthMenu: [5, 10, 20, 50],
                pageLength: 100,
            });

            multiCheck(c2);

            c3 = $("#style-3").DataTable({
                oLanguage: {
                    oPaginate: {
                        sPrevious:
                                '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
                        sNext:
                                '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
                    },
                    sInfo: "Showing page _PAGE_ of _PAGES_",
                    sSearch:
                            '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
                    sSearchPlaceholder: "Search...",
                    sLengthMenu: "Results :  _MENU_",
                },
                stripeClasses: [],
                lengthMenu: [5, 10, 20, 50],
                pageLength: 100,
            });

            multiCheck(c3);

        </script>
        <script>
            $('.delete').click(function () {
                var response = confirm("Are you sure");
                if (response) {
                    $('#user').val($(this).attr('data-user'));
                    $('#formDelete').trigger('submit');
                }
            });
            var datach = [];
            $('#style-1 tbody').on('click', '.new-control-input', function () {
                var tr = $(this).closest("tr");
                var email = $(tr).attr("data-user");


                if ($(tr).hasClass('active')) {
                    // unchecked
                    datach.splice(datach.indexOf(email), 1);
                } else if (!$(tr).hasClass('active')) {
                    //checked
                    if (datach.indexOf(email) === -1) {
                        datach.push(email);
                    }
                }
            });


            $('div.dropdown-menu.bulkk a:first-child').click(function () {
                //suspend
                if (datach.length === 0) {
                    Snackbar.show({
                        text: 'Select users to suspend',
                        pos: 'top-right'
                    });
                } else {
                    suspend(datach);
                }
            });
            $('#style-1 thead').on('click', 'th.spoofer input.new-control-input', function () {
                var trs = $(this).closest('table#style-1').find("tbody").find('tr');

                $.each(trs, function (index, tr) {
                    var email = $(tr).attr("data-user");
                    if ($(tr).hasClass('active')) {
                        // unchecked
                        datach.splice(datach.indexOf(email), 1);
                    } else if (!$(tr).hasClass('active')) {
                        //checked
                        if (datach.indexOf(email) === -1) {
                            datach.push(email);
                        }
                    }
                });
                console.log(datach);
            });
            $('div.dropdown-menu.bulkk a:last-child').click(function () {
                //delete
                if (datach.length === 0) {
                    Snackbar.show({
                        text: 'Select users to delete',
                        pos: 'top-right'
                    });
                } else {
                    delete_(datach);
                }
            });

            function suspend(emails) {
                var form = document.createElement("form");
                form.setAttribute('method', "post");
                form.setAttribute('action', "index");

                var i = document.createElement("input"); //input element, text
                i.setAttribute('type', "hidden");
                i.setAttribute('name', "data");
                i.setAttribute('value', JSON.stringify(emails));

                form.appendChild(i);
                document.getElementsByTagName('body')[0].appendChild(form);

                $(form).trigger("submit");
            }
            function fund(emails) {
                $('#loginModal').modal('show');
                $('#eee').val(emails);
                return;
                var form = document.createElement("form");
                form.setAttribute('method', "post");
                form.setAttribute('action', "index");

                var i = document.createElement("input"); //input element, text
                i.setAttribute('type', "hidden");
                i.setAttribute('name', "data");
                i.setAttribute('value', JSON.stringify(emails));

                var s = document.createElement("select")

                form.appendChild(i);
                document.getElementsByTagName('body')[0].appendChild(form);

                $(form).trigger("submit");
            }
            function bypass(emails) {
                var form = document.createElement("form");
                form.setAttribute('method', "post");
                form.setAttribute('action', "index");

                var i = document.createElement("input"); //input element, text
                i.setAttribute('type', "hidden");
                i.setAttribute('name', "bypass");
                i.setAttribute('value', JSON.stringify(emails));

                form.appendChild(i);
                document.getElementsByTagName('body')[0].appendChild(form);

                $(form).trigger("submit");
            }

            function delete_(emails) {
                var form = document.createElement("form");
                form.setAttribute('method', "post");
                form.setAttribute('action', "index");

                var i = document.createElement("input"); //input element, text
                i.setAttribute('type', "hidden");
                i.setAttribute('name', "delete");
                i.setAttribute('value', JSON.stringify(emails));

                form.appendChild(i);
                document.getElementsByTagName('body')[0].appendChild(form);

                $(form).trigger("submit");
            }

            function unsuspend(emails) {
                var form = document.createElement("form");
                form.setAttribute('method', "post");
                form.setAttribute('action', "index");

                var i = document.createElement("input"); //input element, text
                i.setAttribute('type', "hidden");
                i.setAttribute('name', "unsuspend");
                i.setAttribute('value', JSON.stringify(emails));

                form.appendChild(i);
                document.getElementsByTagName('body')[0].appendChild(form);

                $(form).trigger("submit");
            }


        </script>
        <!-- END PAGE LEVEL SCRIPTS -->
    </body>
</html>