<div class="page-title">
    <h1><?php echo $this->user->lang("Article Comments");?></h1>
    <span><?php echo $this->user->lang("List of comments left for publicly available knowledgebase articles."); ?></span>
</div>

<div class="cm-holder dt-info">
    <div class="head padding-bottom">
        <div class="dt-header">
            <div class="dt-header-left">
                <div class="dt-filters">
                    <div class="filter-group">
                        <label><?php echo $this->user->lang("Show");?></label>
                        <select id="filterByStatus">
                            <option value='all' <?php echo ($this->filter == 'all') ? "selected" : "" ?>><?php echo $this->user->lang("All"); ?></option>
                            <option value='Approved' <?php echo ($this->filter == 'Approved') ? "selected" : "" ?>><?php echo $this->user->lang("Approved"); ?></option>
                            <option value='NonApproved' <?php echo ($this->filter == 'NonApproved') ? "selected" : "" ?>><?php echo $this->user->lang("Un-Approved"); ?></option>
                            <option value='articleId' <?php echo ($this->filter == 'articleId') ? "selected" : "" ?>><?php echo $this->user->lang("Article Id"); ?></option>
                        </select>
                    </div>

                    <div id="td-for-kbaid" class="filter-group" style="display: none">
                        <input type="text" id="kba-id" name="kba-id" class="form-control" placeholder="<?php echo $this->user->lang("Article");?> #" />
                    </div>

                </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="comments-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th></th>
                        <th class=""><?php echo $this->user->lang('Article Id'); ?></th>
                        <th class="width4"><?php echo $this->user->lang('Title'); ?></th>
                        <th class=""><?php echo $this->user->lang('Added'); ?></th>
                        <th class=""><?php echo $this->user->lang('Approved'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <?php if($this->user->hasPermission('knowledgebase_manageComments')) { ?>
        <div class="table-actions">
            <div class="dropdown" id="kbCategoryActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="kbCategoryActionsMenu"
                    disabled="disabled"
                >
                    <i class="fas fa-folder"></i>
                    <?php echo $this->user->lang('Actions'); ?>
                    <i class="fas fa-chevron-down caret"></i>
                </button>

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

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="kbc-toggle"
                    >
                        <i class="fas fa-toggle-on mi-icon"></i>
                        <?php echo $this->user->lang('Toggle Approval'); ?>
                    </button>
                </div>
            </div>
        </div>

        <?php } ?>
    </div>
</div>

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

    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=knowledgebase&controller=comments&action=getkbcomments';
        var table = $('#comments-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: 'data', // The root is data in the ajax call.
                data: function(d) {
                    d.filterComents = $('#filterByStatus').val();
                    d.articleId = $('#kba-id').val();
                }
            },
            "columns": [
                { data: null, defaultContent: '', orderable: false, },
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                {
                    "data": "articleId",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            var arr = row.articleId.split('/');
                            var str = '';

                            if (row.canViewArticles) {
                                str += "<a target='blank' href='../index.php?fuse=knowledgebase&view=article&controller=articles&articleId=" + arr[0] + "'>"
                            }

                            str += arr[0];

                            if (row.canViewArticles) {
                              str += "</a>";
                            }

                            return str;
                        }

                        return data;
                    }
                },
                { "data": "articleTitle" },
                { "data": "commentAddedOn" },
                { "data": "commentIsApproved" }
            ],
            "order": [[2, 'asc']]
        });

        $('#comments-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 {
                var expanderBody = "<b>" + clientexec.lang("User") + "</b>: " + row.data().commentUser + "<br/><b>" + clientexec.lang("Email") + "</b>: " + row.data().commentEmail + "<br/><b>" + clientexec.lang("Comment") + "</b>: " + nl2br(row.data().comment);
                row.child(expanderBody).show();
                tr.addClass('shown');
            }
        });

        function nl2br(str, isXhtml) {
            if (typeof str === 'undefined' || str === null) {
                return '';
            }

            // Determine whether to use <br /> (XHTML) or <br> (HTML5)
            var breakTag = (isXhtml || typeof isXhtml === 'undefined') ? '<br />' : '<br>';

            // Replace all newline characters with the chosen break tag
            return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
        }

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

        $('#filterByStatus').on('change', function () {
            if ($(this).val() == "articleId") {
                $('#kba-id').val('');
                $('#td-for-kbaid').show();
            } else {
                $('#kba-id').val('');
                $('#td-for-kbaid').hide();
                viewcomments.disableButtons();
                table.ajax.reload();
            }
        });

        $('#kba-id').on('change', function () {
            viewcomments.disableButtons();
            table.ajax.reload();
        });

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

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

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

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

        viewcomments.performaction = function (id) {
            var rowIds = table.getSelectedRows('commentId');

            var data = {
                commentId: rowIds
            };

            if (id == 'toggle') {
                id = 'approve';
            }

            $.ajax({
                url: "index.php?controller=comments&fuse=knowledgebase&action=" + id,
                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() {
            viewcomments.disableButtons();

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

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

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

            // Show all available actions
            $actions.find('.menu-item').removeClass('d-none');

            // Enable dropdown trigger
            clientexec.tableActions.setEnabled($pill, true);

            // Close if open to avoid stale UI
            clientexec.tableActions.closeDropdown($dd);
        };

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

            // Disable dropdown trigger
            clientexec.tableActions.setEnabled($pill, false);

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

            // Close if open
            clientexec.tableActions.closeDropdown($dd);
        };


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