<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 dt-info">
    <div class="head padding-bottom">
        <div class="dt-header">
            <div class="dt-header-left">
                <button class="action-buttons blue" id="add-notification-button">
                    <i class="icon-ic-21"></i>
                    <?php echo $this->user->lang('Add Notification'); ?>
                </button>
                 <div class="dt-filters"></div>
            </div>
            <div class="dt-header-right">
                <div class="filter-group dt-length"></div>
            </div>
        </div>
    </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="dropdown" id="notificationActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="notificationActionsMenu"
                    disabled="disabled"
                >
                    <i class="fas fa-bell"></i>
                    <?php echo $this->user->lang('Actions'); ?>
                    <i class="fas fa-chevron-down caret"></i>
                </button>

                <div
                    class="menu"
                    id="notificationActionsMenu"
                    role="menu"
                    aria-labelledby="notificationActions"
                >
                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="ntf-enable"
                    >
                        <i class="fas fa-toggle-on mi-icon"></i>
                        <?php echo $this->user->lang('Enable'); ?>
                    </button>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="ntf-disable"
                    >
                        <i class="fas fa-toggle-off mi-icon"></i>
                        <?php echo $this->user->lang('Disable'); ?>
                    </button>

                    <div class="menu-sep" role="separator"></div>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="ntf-reset"
                    >
                        <i class="fas fa-sync-alt mi-icon"></i>
                        <?php echo $this->user->lang('Reset'); ?>
                    </button>

                    <button
                        class="menu-item danger"
                        role="menuitem"
                        type="button"
                        id="ntf-delete"
                    >
                        <i class="fas fa-trash mi-icon"></i>
                        <?php echo $this->user->lang('Delete'); ?>
                    </button>
                </div>
            </div>
        </div>

    </div>
</div>

<script data-cfasync="false">
    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 () {
            // Scope to this table-actions block (adjust selector if you named it differently)
            const $dd = $('#notificationActions');
            const $actions = $dd.closest('.table-actions');
            const $pill = $actions.find('.pill');

            let showEnable = true;
            let showDisable = true;

            const selectedRows = table.rows({ selected: true }).data();

            selectedRows.each(function (value) {
                if (value.enabled == 0) {
                    showDisable = false; // can't disable/reset if any selected is already disabled
                } else {
                    showEnable = false;  // can't enable if any selected is already enabled
                }
            });

            // Toggle items (use d-none so it works even if Bootstrap is involved)
            clientexec.tableActions.setVisible($('#ntf-enable'), showEnable);
            clientexec.tableActions.setVisible($('#ntf-disable'), showDisable);
            clientexec.tableActions.setVisible($('#ntf-reset'), showDisable);
            clientexec.tableActions.setVisible($('#ntf-delete'), true);

            // Enable the pill only if at least one action is visible AND there are selected rows
            const hasVisibleActions = $actions.find('.menu-item:not(.d-none)').length > 0;
            const hasSelection = selectedRows.length > 0;

            $pill.prop('disabled', !(hasVisibleActions && hasSelection));

            clientexec.tableActions.closeDropdown($dd);
        };

        notifications.disableButtons = function () {
            const $dd = $('#notificationActions');
            const $actions = $dd.closest('.table-actions');
            const $pill = $actions.find('.pill');

            $pill.prop('disabled', true);

            // Hide all actions
            $actions.find('.menu-item').addClass('d-none');

            clientexec.tableActions.closeDropdown($dd);
        };

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