<div class="page-title">
    <h1><?php echo $this->user->lang("Products");?></h1>
    <span><?php echo $this->user->lang("Create and edit products available to your clients"); ?></span>
</div>
<div class="cm-holder settings-wrapper dt-info">
    <div class="head">
        <?php if ($this->user->hasPermission('admin_edit_packagetypes')) { ?>
        <button class="action-buttons blue" id="add-button">
            <i class="icon-ic-21"></i>
            <?php echo $this->user->lang('Add Product Group'); ?>
        </button>
        <?php } ?>
    </div>
    <div class="dt-wrapper pull-top">
        <div class="table-responsive">
            <table id="table-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th class=""><?php echo $this->user->lang('group'); ?></th>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th class=""><?php echo $this->user->lang('Name'); ?></th>
                        <th class=""><?php echo $this->user->lang('Late Fee'); ?></th>
                        <th class=""><?php echo $this->user->lang('Tax'); ?></th>
                        <th class=""><?php echo $this->user->lang('Signup?'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <button class="action-buttons" id="delete-button" disabled="disabled"><i class="icon-ic-25"></i><?php echo $this->user->lang('Delete'); ?></button>
            <button class="action-buttons" id="clone-button" disabled="disabled"><i class="icon-ic-25"></i><?php echo $this->user->lang('Clone'); ?></button>
        </div>
    </div>
</div>

<script>
    var admin_edit_packagetypes = <?php echo ($this->user->hasPermission('admin_edit_packagetypes')) ? "true" : "false"; ?>;

    $(document).ready(function () {

       addEditWindow = new RichHTML.window({
            url: 'index.php?fuse=admin&controller=products&view=productgroup',
            actionUrl: 'index.php?fuse=admin&controller=products&action=saveproductgroup',
            showSubmit: true,
            title: clientexec.lang("Product Group Window"),
            size: 'modal-lg',
            onSubmit: function (data) {
                clientexec.parseResponse(data);
                table.ajax.reload();
            }
        });


        var ajaxUrl = 'index.php?fuse=admin&controller=products&action=getproducts';
        var table = $('#table-list').DataTable({
            ordering: false,
            select: {
                style: 'multi',
                selector: 'td:nth-child(1)'
            },
            columnDefs: [
                { targets: 0, visible: false },
                {
                    targets: 1,
                    orderable: false,
                    className: 'select-checkbox',
                    checkboxes: {
                        selectRow: true
                    },
                    width: '5%'
                },

            ],
            rowGroup: {
                dataSrc: 'group',
                startRender: function (rows) {
                    const d = rows.data()[0];
                    return `
                    <div class="d-flex justify-content-between align-items-center w-100">
                        ${d.group}
                    </div>
                    `;
                }
            },
            "searching": false,
            "ajax": {
                url: ajaxUrl,
                dataSrc: 'results'
            },
            "columns": [
                {
                    'data': 'group', visible: false,
                },
                { data: null, defaultContent: '', orderable: false, },
                {
                    "data": "name",
                    render: function (data, type, row) {
                        var name = row.name;

                        if ($.trim(name) === "") {
                            name = "<i>Not named</i>";
                        }

                        if (admin_edit_packagetypes) {
                            name = '<a href="index.php?fuse=admin&view=product&controller=products&groupid='+row.groupid+'&id='+row.id+'">'+name+'</a>';
                        }

                        return name;
                    }
                },
                {
                    "data": "latefee",
                    className: 'text-center',
                    render: function (data, type, row) {
                        var fontClass = "";

                        if (row.latefee == 'N/A') {
                            fontClass = "price-muted";
                        }

                        return "<span class='"+fontClass+"'>"+row.latefee+"</span>";

                    }
                },
                {
                    "data": "taxable",
                    className: 'text-center',
                    render: function (data, type, row) {
                        if (row.id === 0) {
                            return "";
                        } else if (row.taxable === "1") {
                            return clientexec.lang("Yes");
                        }

                        return clientexec.lang("No");
                    }
                },
                {
                    "data": "signup",
                    className: 'text-center',
                    render: function (data, type, row) {
                        if (row.id === 0) {
                            return "";
                        } else if (row.signup === "1") {
                            return clientexec.lang("Yes");
                        } else if (row.signup === "0") {
                            return clientexec.lang("Hidden");
                        }

                        return clientexec.lang("No");
                    }
                },
            ],
            "order": [[1, 'asc']],
            createdRow: function(row, data) {
                $(row).attr('data-group', data.group);
                if (data.id == 0) {
                    $(row).find('td.select-checkbox').removeClass('select-checkbox').off('click');
                }
            }
        });

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

        $('#table-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 {
                row.child(format(row.data())).show();
                tr.addClass('shown');
            }
        });

        function format(d) {
            if ($.trim(d.status_message) == "") {
                d.status_message = clientexec.lang("No status message");
            }
            return '<table cellpadding="0" cellspacing="0" width="100%" border="0" class="inner-table">' +
            '<tr class="new-row">' +
            '<td><span class="fw-bold">' + clientexec.lang("Status Message:") + '</span><br/>' + d.status_message + '</td>' +

            '</tr>' +
            '</table>';
        }

        $('#checkAll').on('click', function () {
            if (this.checked) {
                table.rows({page: 'current'}).every(function () {
                    var rowNode = this.node();
                    if ($(rowNode).find('td.select-checkbox').length) {
                        this.select();
                    }
                });
            } else {
                table.rows().deselect();
            }
        });

        table.on('user-select', function (e, dt, type, cell, originalEvent) {
            if (type === 'row') {
                if (!$(cell.node()).hasClass('select-checkbox')) {
                    e.preventDefault();
                }
            }
        });

        table.on('select.dt deselect.dt', function() {
            var selectedRows = table.rows({ selected: true }).count();
            if (selectedRows == 0) {
                $('.table-actions .action-buttons').prop('disabled', true);
            } else if (selectedRows == 1) {
                $('.table-actions .action-buttons').prop('disabled', false);
            } else {
                $('#delete-button').prop('disabled', false)
                $('#clone-button').prop('disabled', true)
            }
        });

        $('#delete-button').click(function () {
            if ($(this).attr('disabled')) {
                return false;
            }
            RichHTML.msgBox(
                clientexec.lang('Are you sure you want to delete the selected product(s)'),
                {
                    type:"yesno"
                },
                function(result)
                {
                    if (result.btn === clientexec.lang("Yes")) {
                        $.post(
                            "index.php?fuse=admin&controller=products&action=deleteproducts",
                            {
                                ids: table.getSelectedRows()
                            },
                            function(data)
                            {
                                clientexec.parseResponse(data);
                                table.ajax.reload();
                            }
                        );
                    }
                }
            );
        });

        $('#clone-button').click(function() {
            if ($(this).attr('disabled')) {
                return false;
            }

            $.post(
                "index.php?fuse=admin&controller=products&action=cloneproduct",
                {
                    id: table.getSelectedRows()
                },
                function(data)
                {
                    clientexec.parseResponse(data);
                    table.ajax.reload();
                }
            );
        });

        $(document).on("click", '.edit-group-link', function(event) {
                addEditWindow.show({params:{id:$(this).attr('data-id')}});
            });

        $(document).on("click", '.delete-group-link', function(event) {
            id = $(this).attr('data-id')
            RichHTML.msgBox(
                clientexec.lang('Are you sure you want to delete this product group?'),
                {
                    type:"yesno"
                },
                function (result)
                {
                    if (result.btn === clientexec.lang("Yes")) {
                        $.post(
                            "index.php?fuse=admin&controller=products&action=deleteproductgroup",
                            {
                                id: id
                            },
                            function (data)
                            {
                                clientexec.parseResponse(data);
                                table.ajax.reload();
                            }
                        );
                    }
                }
            );
        });
    });

</script>