<div class="page-title">
    <h1><?php echo $this->user->lang("Announcements");?></h1>
    <span><?php echo $this->user->lang("List of all company announcements."); ?></span>
</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-announcement-button">
                    <i class="icon-ic-21"></i>
                    <?php echo $this->user->lang('Add Announcement'); ?>
                </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="announcements-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th class="width4 "><?php echo $this->user->lang('Title'); ?></th>
                        <th class=""><?php echo $this->user->lang('Post Date'); ?></th>
                        <th class=""><?php echo $this->user->lang('Published'); ?></th>
                        <th class=""><?php echo $this->user->lang('Pinned'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <div class="dropdown" id="announcementActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="announcementActionsMenu"
                    disabled="disabled"
                >
                    <i class="fas fa-bullhorn"></i>
                    <?php echo $this->user->lang('Actions'); ?>
                    <i class="fas fa-chevron-down caret"></i>
                </button>

                <div
                    class="menu"
                    id="announcementActionsMenu"
                    role="menu"
                    aria-labelledby="announcementActions"
                >
                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="ann-publish"
                    >
                        <i class="fas fa-upload mi-icon"></i>
                        <?php echo $this->user->lang('Publish'); ?>
                    </button>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="ann-unpublish"
                    >
                        <i class="fas fa-eye-slash mi-icon"></i>
                        <?php echo $this->user->lang('Unpublish'); ?>
                    </button>

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

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="ann-pin"
                    >
                        <i class="fas fa-thumbtack mi-icon"></i>
                        <?php echo $this->user->lang('Pin'); ?>
                    </button>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="ann-unpin"
                    >
                        <i class="fas fa-times mi-icon"></i>
                        <?php echo $this->user->lang('Unpin'); ?>
                    </button>

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

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

    </div>
</div>

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

    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=admin&action=getannouncements&controller=announcements';
        var table = $('#announcements-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: 'announcements' // The root is announcements in the ajax call.
            },
            "columns": [
                { data: null, defaultContent: '', orderable: false, },
                {
                    "data": "title",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            return '<a class="announcement-title" data-announcement-id="'+row.id+'">' + ( row.published == '0' ? '<span style="color: gray; font-style: italic;">' + clientexec.htmlspecialchars(row.title) + '</span>' : clientexec.htmlspecialchars(row.title) ) + '</a>';
                        }

                        return data;
                    }
                },
                { "data": "postdate" },
                {
                    "data": "published",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            if (row.published == '0') {
                                return clientexec.lang('No');
                            } else {
                                return clientexec.lang('Yes');
                            }
                        }

                        return data;
                    }
                },
                {
                    "data": "pinned",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            if (row.pinned == '1') {
                                return clientexec.lang('Yes');
                            } else {
                                return clientexec.lang('No');
                            }
                        }

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

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

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

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

        $(document).on('click', 'a.announcement-title', function() {
            announcements.window.show({
                params: {
                    id: $(this).attr('data-announcement-id')
                }
            });

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

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

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

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

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

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

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

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

                    var action = 'publishunpublishannouncements';

                    break;
                case 'unpublish':
                    var data = {
                        items:   rowIds,
                        publish: 0
                    };

                    var action = 'publishunpublishannouncements';

                    break;
                case 'pin':
                    var data = {
                        items:  rowIds,
                        pinned: 1
                    };

                    var action = 'togglepin';

                    break;
                case 'unpin':
                    var data = {
                        items:  rowIds,
                        pinned: 0
                    };

                    var action = 'togglepin';

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

                    var action = 'deleteannouncements';

                    break;
            }

            $.ajax({
                url: "index.php?fuse=admin&controller=announcements&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() {
            announcements.disableButtons();

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

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

        announcements.enableButtons = function () {
            const $dd = $('#announcementActions');
            const $actions = $dd.closest('.table-actions');
            const $pill = $actions.find('.pill');

            let showPublish = true;
            let showUnpublish = true;
            let showPin = true;
            let showUnpin = true;

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

            selectedRows.each(function (value) {
                // Published logic
                if (value.published == '0') {
                    showUnpublish = false;
                } else {
                    showPublish = false;
                }

                // Pinned logic
                if (value.pinned == '0') {
                    showUnpin = false;
                } else {
                    showPin = false;
                }
            });

            // Toggle menu items
            clientexec.tableActions.setVisible($('#ann-publish'), showPublish);
            clientexec.tableActions.setVisible($('#ann-unpublish'), showUnpublish);
            clientexec.tableActions.setVisible($('#ann-pin'), showPin);
            clientexec.tableActions.setVisible($('#ann-unpin'), showUnpin);
            clientexec.tableActions.setVisible($('#ann-delete'), true);

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

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

            // Prevent stale open menus
            clientexec.tableActions.closeDropdown($dd);
        };

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

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

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

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

        announcements.disableButtons();

        $(document).on('shown.bs.modal', '.richwindow', function () {
            clientexec.waitForEditorElement('.wysihtml5', clientexec.initDefaultTinyMCE);
        });
    });
</script>
