<?php
session_start();
require_once '../include/Constants.php';
require_once '../models/User.php';
require_once '../include/Helper.php';
require_once '../models/Wallet.php';
require_once '../models/Upgrade.php';
require_once '../include/DatabaseConn.php';
require_once '../models/Admin.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();


$users = User::getUsers($link);
$wallets = Upgrade::getWalletDeposit($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"/>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.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="table-responsive mb-4 style-1">
                                            <div class="table-responsive mb-4 style-1">  
                                                <table id="style-4" class="table style-1 table-hover non-hover">
                                                                    <thead>
                                                                        <tr>
                                                                            <th>User</th>
                                                                            <th>Amount</th>
                                                                            <th>Proof</th>
                                                                            <th>Date</th>
                                                                            <th class="">Status</th>
                                                                            <th class="text-center">Action</th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody>
                                                                        <?php
                                                                        if (!is_null($wallets)) {
                                                                            foreach ($wallets as $wallet) {
                                                                                $user = User::getCurrentUser($link, $wallet->getUser());
                                                                                if(is_null($user)) {
                                                                                    continue;
                                                                                }
                                                                                if ( strcasecmp($wallet->getStatus(), SENT) == 0 || strcasecmp($wallet->getStatus(), RECEIVED) == 0) {
                                                                                    continue;
                                                                                }
                                                                                ?>
                                                                                <tr class="with">
    <td><?php echo "{$user->getName()}"; ?></td>
    <td class="">
        $<?php echo "{$wallet->getAmount()}"; ?>
    </td>
    <td class="" style="word-break: break-all;">
        <a style="cursor: pointer; color: #3c8dbc; text-decoration: underline" href="<?php echo DOMAIN_NAME . "/dashboard/" . "{$wallet->getProof()}"; ?>" data-lightbox="image-<?php echo "{$wallet->getId()}"; ?>" data-token="<?php echo "{$wallet->getId()}"; ?>" data-user="<?php echo "{$wallet->getUser()}"; ?>" >View Payment Proof</a>
    </td>
    <td><?php echo (Helper::readableTime($wallet->getDate())); ?></td>
    <td 
        <?php if (strcasecmp($wallet->getStatus(), APPROVED) == 0) { ?> style="color: #009688"<?php } else { ?> style="color: #e95f2b" <?php } ?> 
        class="status">
        <?php echo "{$wallet->getStatus()}"; ?>
    </td>
    <td class="text-center">
        <div class="dropdown custom-dropdown">
            <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink<?php echo "{$wallet->getId()}"; ?>" 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>
            
            <div class="dropdown-menu" aria-labelledby="dropdownMenuLink<?php echo "{$wallet->getId()}"; ?>">
                <?php if (strcasecmp($wallet->getStatus(), APPROVED) != 0) { ?>
                    <a class='dropdown-item cursor' onclick="approveUpgrade(<?php echo $wallet->getId(); ?>, '<?php echo $wallet->getUser(); ?>');">Approve Upgrade</a>
                <?php } ?>
            </div>
        </div>
    </td>
</tr>

                                                                                <?php
                                                                            }
                                                                        } else {
                                                                            ?>
                                                                            <tr><td colspan="7"> <p style="text-align: center">No investment upgrade history </p></td></tr>
                                                                        <?php }
                                                                        ?>
                                                                    </tbody>
                                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                    <?php require_once './partials/footer.php'; ?>
                </div>
                <!--  END CONTENT AREA  -->
            </div>
            <!-- END MAIN CONTAINER -->
        </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>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js"></script>
         <script src="../js/jqueryblockui.js" type="text/javascript"></script>
        <script src="../js/customblockui.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>
            function approveUpgrade(upgradeId, userEmail) {
            if (confirm('Are you sure you want to approve this upgrade?')) {
                $.ajax({
                    url: 'approve_upgrade.php',
                    type: 'POST',
                    data: {
                        upgrade_id: upgradeId,
                        user_email: userEmail
                    },
                    dataType: 'json',
                    success: function(response) {
                        alert(response.message);
                        if (response.success) {
                            // Optionally, reload the page or update the UI
                            location.reload();
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('An error occurred while processing the request.');
                    }
                });
            }
        }
        </script>


        </script>

        <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: 10,
            });

            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: 5,
            });

            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: 5,
            });

            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 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");
            }
            
            $('.dodo').click(function () {
                alert("The user has not uploaded payment proof");
            });
            
            $('.confirminv').click(function () {
                var user = $(this).attr('data-id');
                var email = $(this).attr('data-email');
                loader('.style-1');
                axios.get('v1/confirm-invoice', {
                    params: {
                        id: user,
                        email: email
                    }
                }).then((response) => {
                    var data = response.data;
                    if (!data.error) {
                        showToast("Confirmed successful");
                       window.location.href = "investment-history";
                    } else {
                        showToast("Error occured");
                    }
                }).catch((error) => {
                    showToast("Error occured");
                }).finally(() => {
                    removeLoader('.style-1');
                });
            });
            
            $('.deleteIn').click(function () {
                var user = $(this).attr('data-id');
                loader('.style-1');
                axios.get('v1/delete-invoice', {
                    params: {
                        id: user
                    }
                }).then((response) => {
                    var data = response.data;
                    if (!data.error) {
                        showToast("Deleted Successful");
                        window.location.href = "investment-history";
                    } else {
                        showToast("Error occured");
                    }
                }).catch((error) => {
                    showToast("Error occured");
                }).finally(() => {
                    removeLoader('.style-1');
                });

            });
            
             function loader(blockContent) {
                var block = $(blockContent);
                $(block).block({
                    message: "<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-loader spin'><line x1='12' y1='2' x2='12' y2='6'></line><line x1='12' y1='18' x2='12' y2='22'></line><line x1='4.93' y1='4.93' x2='7.76' y2='7.76'></line><line x1='16.24' y1='16.24' x2='19.07' y2='19.07'></line><line x1='2' y1='12' x2='6' y2='12'></line><line x1='18' y1='12' x2='22' y2='12'></line><line x1='4.93' y1='19.07' x2='7.76' y2='16.24'></line><line x1='16.24' y1='7.76' x2='19.07' y2='4.93'></line></svg>",
                    overlayCSS: {
                        backgroundColor: '#000',
                        opacity: 0.8,
                        zIndex: 99999,
                        cursor: 'wait'
                    },
                    css: {
                        border: 0,
                        color: '#fff',
                        padding: 0,
                        backgroundColor: 'transparent'
                    }
                });
            }

            function removeLoader(element) {
                $(element).unblock();
            }
            
            function showToast(msg) {
                Snackbar.show({
                    text: msg,
                    pos: 'top-right'
                });
            }

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