<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 settings-wrapper dt-info">
    <div class="head">
        <table>
            <tr>
                <td>
                    <button class="action-buttons blue" id="add-announcement-button">
                        <i class="icon-ic-21"></i>
                        <?php echo $this->user->lang('Add Announcement'); ?>
                    </button>
                </td>
            </tr>
        </table>
    </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="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="ann-publish"><?php echo $this->user->lang('Publish'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="ann-unpublish"><?php echo $this->user->lang('Unpublish'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="ann-pin"><?php echo $this->user->lang('Pin'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="ann-unpin"><?php echo $this->user->lang('Unpin'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="ann-delete"><?php echo $this->user->lang('Delete'); ?></button></li>
                    </ul>
                </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() {
            var showPublish = true;
            var showUnpublish = true;
            var showPin = true;
            var showUnpin = true;

            var selectedRows = table.rows({ selected: true }).data();
            selectedRows.each(function (value, index) {
                if (value.published == '0') {
                    showUnpublish = false;
                } else {
                    showPublish = false;
                }

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

            if (showPublish) {
                $("#ann-publish").removeClass("d-none");
            } else {
                $("#ann-publish").addClass("d-none");
            }

            if (showUnpublish) {
                $("#ann-unpublish").removeClass("d-none");
            } else {
                $("#ann-unpublish").addClass("d-none");
            }

            if (showPin) {
                $("#ann-pin").removeClass("d-none");
            } else {
                $("#ann-pin").addClass("d-none");
            }

            if (showUnpin) {
                $("#ann-unpin").removeClass("d-none");
            } else {
                $("#ann-unpin").addClass("d-none");
            }

            $("#ann-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");
                    }
                }
            });
        }

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

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