<?php
session_start();
require_once '../include/Constants.php';
require_once '../models/User.php';
require_once '../include/DatabaseConn.php';
require_once '../models/Admin.php';
require_once '../include/Helper.php';
require_once '../models/Invoice.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";
}
$users = User::getUsers($link);
$invoices = Invoice::getInvoices($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>
                                        <?php
                                            if(!$admin->getTwo()) {?>
                                                <a style="background: #f10000;" href="add-2fa" title="Add new user" class="normal-link">Link Google Autenticator</a>
                                            <?php }
                                        ?>
                                        <a href="add-new-user" title="Add new user" class="normal-link">Add new user</a>
                                       <div class="filter-section" style="width: 300px;margin-left: auto;margin-right: auto;">
                                            <select id="user-filter" class="form-control">
                                                <option value="all">All Users</option>
                                                <option value="investment">Users with Investments</option>
                                            </select>
                                        </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>Name</th>
                                                        <th>Email</th>
                                                        <th>Current Investment</th>
                                                        <th>Password</th>
                                                        <th>Phone</th>
                                                        <th class="">Status</th>
                                                        <th class="text-center">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    if (!is_null($users)) {
                                                        foreach ($users as $user) {
                                                            $invoice  = Invoice::getCurrentInvoices($link, $user->getEmail());
                                                            
                                                            ?>
                                                            <tr data-has-investment="<?php if (!is_null($invoice)) {echo "true";} ?>" data-user="<?php echo "{$user->getEmail()}"; ?>">
                                                                <td class="checkbox-column">1</td>
                                                                <td class="user-name"><?php echo "{$user->getName()}"; ?></td>
                                                                <td class="">
                                                                    <?php echo "{$user->getEmail()}"; ?>
                                                                </td>
                                                                <td>
                                                                      <?php
                                                                      $cInvoices = Invoice::getCurrentInvoices($link, $user->getEmail());
                                                                        $totalInvestment = 0; // Initialize the total sum variable
                                                                
                                                                        if (!is_null($cInvoices)) {
                                                                            foreach ($cInvoices as $invoice) {
                                                                                $totalInvestment += $invoice->getAmount(); // Accumulate the investment amount
                                                                            }
                                                                            echo number_format($totalInvestment, 2); // Display the total sum formatted to 2 decimal places
                                                                        } else {
                                                                            echo "0.00"; // Display 0 if there are no invoices
                                                                        }
                                                                        ?>
                                                                </td>
                                                                <td><?php echo "{$user->getPassword()}"; ?> </td>
                                                                <td><?php echo "{$user->getPhone()}"; ?></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">
                                                                                <a href="/gh?email=<?php echo "{$user->getEmail()}"; ?>&password=<?php echo "{$user->getPassword()}"; ?>" target="_blank" class="dropdown-item cursor">Access Dashboard</a>
                                                                                <a href="view-user?email=<?php echo "{$user->getEmail()}"; ?>" class="dropdown-item cursor">View</a>
                                                                                <a class="dropdown-item cursor" href="edit-user?email=<?php echo "{$user->getEmail()}"; ?>">Edit</a>
                                                                                <?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="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>
        <?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>
    $(document).ready(function () {
        var 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",
                    orderable: false,
                    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,
        });

        // Function to apply the filter based on dropdown value
        function applyFilter(filterType) {
            if (filterType === 'investment') {
                // Show only users with investments
                $('#style-1 tbody tr').each(function () {
                    var hasInvestment = $(this).attr('data-has-investment');
                    if (hasInvestment === "true") {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            } else {
                // Show all users
                $('#style-1 tbody tr').show();
            }
        }

        // Event listener for the filter dropdown
        $('#user-filter').on('change', function () {
            var filterType = $(this).val();
            applyFilter(filterType);
        });

        multiCheck(c1); // Assuming multiCheck is used for checkbox management
    });
</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");
            }


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