<?php CE_Lib::log(4, $this->customfields); ?>
<div class="page-title">
    <h1><?php echo $this->user->lang("User Notifications");?></h1>
    <div><?php echo $this->user->lang("List of all notification rules that are configured to be mailed out."); ?></div>
    <div><?php echo $this->user->lang('Configure');?>&nbsp;<a href="index.php?fuse=admin&controller=settings&settings=plugins_services&type=Services&view=plugins&setting=automailer"><?php echo $this->user->lang('Notification Automation Service');?></a>&nbsp;<?php echo $this->user->lang('and');?>&nbsp;<a href="index.php?fuse=admin&controller=settings&view=emailtemplates&settings=mail"><?php echo $this->user->lang('Email Templates');?></a></div>
</div>

<div class="cm-holder settings-wrapper dt-info">
    <div class="head">
        <table>
            <tr>
                <td>
                    <button class="action-buttons blue" id="add-notification-button">
                        <i class="icon-ic-21"></i>
                        <?php echo $this->user->lang('Add Notification'); ?>
                    </button>
                </td>
            </tr>
        </table>
    </div>
    <div class="dt-wrapper pull-top">
        <div class="table-responsive">
            <table id="notifications-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th></th>
                        <th class="width4 "><?php echo $this->user->lang('Event Name'); ?></th>
                        <th class=""><?php echo $this->user->lang('From Name'); ?></th>
                        <th class=""><?php echo $this->user->lang('From Email'); ?></th>
                        <th class=""># <?php echo $this->user->lang('Notified'); ?></th>
                        <th class=""><?php echo $this->user->lang('Last Notified'); ?></th>
                        <th class=""><?php echo $this->user->lang('Enabled'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <div class="btn-toolbar mb-3" role="toolbar" aria-label="Actions">
                <div class="btn-group me-2" role="group">
                    <button type="button" class="btn btn-outline-primary dropdown-toggle d-none" data-bs-toggle="dropdown" aria-expanded="false">
                        <?php echo $this->user->lang('Actions'); ?>
                    </button>
                    <ul class="dropdown-menu">
                        <li><button class="dropdown-item d-none" id="ntf-enable"><?php echo $this->user->lang('Enable'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="ntf-disable"><?php echo $this->user->lang('Disable'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="ntf-reset"><?php echo $this->user->lang('Reset'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="ntf-delete"><?php echo $this->user->lang('Delete'); ?></button></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var notifications = notifications || {};

    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=admin&action=getnotifications&controller=notifications';
        var table = $('#notifications-list').DataTable({
            columnDefs: [{
                targets: 0,
                orderable: false,
                className: 'select-checkbox',
                checkboxes: {
                    selectRow: true
                },
                width: '5%'
            }],

            select: {
                style: 'multi',
                selector: 'td:first-child'
            },

            "searching": false,
            "ajax": {
                url: ajaxUrl,
                dataSrc: 'notifications' // The root is notifications in the ajax call.
            },
            "columns": [
                { data: null, defaultContent: '', orderable: false, },
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                {
                    "data": "name",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            return '<a class="notification-name" data-notification-id="'+row.id+'">' + ( row.enabled == 0 ? '<span style="color: gray; font-style: italic;">' + clientexec.htmlspecialchars(row.name) + '</span>' : clientexec.htmlspecialchars(row.name) ) + '</a>';
                        }

                        return data;
                    }
                },
                { "data": "fromName" },
                { "data": "fromEmail" },
                { "data": "count" },
                { "data": "datenotified" },
                {
                    "data": "enabled",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            if (row.enabled == 0) {
                                return clientexec.lang('No');
                            } else {
                                return clientexec.lang('Yes');
                            }
                        }

                        return data;
                    }
                }
            ],
            "order": [[2, 'asc']]
        });

        $('#notifications-list tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                fetchRowDetails(row.data()).then(function (data) {
                    var expanderBody = "<div class='notificationdetails'><b>" + data.appliesto + "</b><br/>" + data.appliestodetails + "</div>";
                    row.child(expanderBody).show();
                    tr.addClass('shown');
                });
            }
        });

        function fetchRowDetails(row) {
            return new Promise((resolve, reject) => {
                $.get("index.php?fuse=admin&action=notificationdetails&controller=notifications", { id:row.id }, function(data) {})
                .done(resolve)
                .fail(reject);
            });
        }

        $('#checkAll').on('click', function () {
            if (this.checked) {
                table.rows({page: 'current'}).select();
            } else {
                table.rows().deselect();
            }
        });

        notifications.window = new RichHTML.window({
            id:         'notification-window',
            size:       'modal-lg', //'modal-fullscreen', 'modal-xl', 'modal-lg',
            url:        'index.php?fuse=admin&view=notification&controller=notifications',
            actionUrl:  'index.php?fuse=admin&action=savenotification&controller=notifications',
            showSubmit: true,
            title:      clientexec.lang('Notification Window'),
            onSubmit: function (data) {
                clientexec.parseResponse(data);
                table.ajax.reload();

                if (typeof profile !== "undefined") {
                    setTimeout(function () {
                        profile.get_counts();
                    },1000);
                }
            }
        });

        $(document).on('click', 'a.notification-name', function() {
            notifications.window.show({
                params: {
                    id: $(this).attr('data-notification-id')
                }
            });

            // setting this inside the options obj above doesn't work
            $('.window-title').text(clientexec.lang('Edit') + ' - ' + $(this).text());
        });

        $('#add-notification-button').on('click', function(){
            notifications.window.show();
        });

        $("[id^='ntf-']").click(function () {
            if ($(this).attr('disabled')) {
                return;
            }

            var id = $(this).attr('id');
            id = id.replace('ntf-', '');

            RichHTML.msgBox(
                clientexec.lang('Are you sure you want to % the selected notification(s)', id),
                {
                    type: "yesno"
                },
                function (result) {
                    if (result.btn === clientexec.lang('Cancel') || result.btn === clientexec.lang('No')) {
                        return;
                    }

                    notifications.disableButtons();
                    notifications.performaction(id)
                }
            );
        });

        notifications.performaction = function (id) {
            var rowIds = table.getSelectedRows();

            switch (id) {
                case 'enable':
                    var data = {
                        items:   rowIds,
                        enabled: 1
                    };

                    var action = 'enabledisablenotifications';

                    break;
                case 'disable':
                    var data = {
                        items:   rowIds,
                        enabled: 0
                    };

                    var action = 'enabledisablenotifications';

                    break;
                case 'reset':
                    var data = {
                        items: rowIds
                    };

                    var action = 'resetnotifications';

                    break;
                case 'delete':
                    var data = {
                        items: rowIds
                    };

                    var action = 'deletenotifications';

                    break;
            }

            $.ajax({
                url: "index.php?fuse=admin&controller=notifications&action=" + action,
                type: 'POST',
                data:  data,
                success:  function (xhr) {
                    clientexec.parseResponse(xhr);
                    table.ajax.reload();

                    if (typeof profile !== "undefined") {
                        setTimeout(function () {
                            profile.get_counts();
                        },1000);
                    }
                }
            });
        };

        table.on('select.dt deselect.dt', function() {
            notifications.disableButtons();

            var selectedRows = table.rows({ selected: true }).count();

            if (selectedRows > 0) {
                notifications.enableButtons();
            }
        });

        notifications.enableButtons = function() {
            var showEnable = true;
            var showDisable = true;

            var selectedRows = table.rows({ selected: true }).data();
            selectedRows.each(function (value, index) {
                if (value.enabled == 0) {
                    showDisable = false;
                } else {
                    showEnable = false;
                }
            });

            if (showEnable) {
                $("#ntf-enable").removeClass("d-none");
            } else {
                $("#ntf-enable").addClass("d-none");
            }

            if (showDisable) {
                $("#ntf-disable").removeClass("d-none");
                $("#ntf-reset").removeClass("d-none");
            } else {
                $("#ntf-disable").addClass("d-none");
                $("#ntf-reset").addClass("d-none");
            }

            $("#ntf-delete").removeClass("d-none");

            //$(".table-actions .btn-group").removeClass("d-none");
            $(".table-actions .btn-group").each(function () {
                let $group = $(this);

                // Count visible dropdown items inside this group
                let $visibleDropdownItems = $group.find(".dropdown-menu .dropdown-item:not(.d-none)");

                // Count visible direct buttons (single buttons not part of dropdown)
                let $visibleDirectBtns = $group.children("button:not(.d-none):not(.dropdown-toggle)");

                if ($visibleDropdownItems.length + $visibleDirectBtns.length === 0) {
                    // Nothing visible, hide group
                    $group.addClass("d-none");
                } else {
                    // At least one item visible, show group
                    $group.removeClass("d-none");

                    // If it has a dropdown toggle, show it
                    let $toggle = $group.children(".dropdown-toggle");
                    if ($toggle.length && $visibleDropdownItems.length > 0) {
                        $toggle.removeClass("d-none");
                    }
                }
            });
        }

        notifications.disableButtons = function() {
            $(".table-actions .btn-group").addClass("d-none");
            $(".table-actions .btn-group button").addClass("d-none");
        };

        notifications.disableButtons();
    });
</script>
