<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 settings-wrapper dt-info">
    <div class="head">
        <div class="filter-block" style="">
            <table>
                <tr>
                    <td>
                        <?php echo $this->user->lang("Show");?>
                        <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>
                    </td>
                    <td id="td-for-kbaid" style="width:100px;display:none">
                        <input type="text" id="kba-id" name="kba-id" class="form-control" placeholder="<?php echo $this->user->lang("Article");?> #" />
                    </td>
                </tr>
            </table>
        </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="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="kbc-delete"><?php echo $this->user->lang('Delete'); ?></button></li>
                            <li><button class="dropdown-item d-none" id="kbc-toggle"><?php echo $this->user->lang('Toggle Approval'); ?></button></li>
                        </ul>
                    </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() {
            $(".table-actions .btn-group").removeClass("d-none");
            $(".table-actions .btn-group button").removeClass("d-none");
        }

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

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