<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 dt-info">
    <div class="head padding-bottom">
        <div class="dt-header">
            <div class="dt-header-left">
                <?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 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="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">
            <div class="dropdown" id="cloneDeleteActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="cloneDeleteActionsMenu"
                    disabled="disabled"
                >
                    <i class="fas fa-clone"></i>
                    <?php echo $this->user->lang('Actions'); ?>
                    <i class="fas fa-chevron-down caret"></i>
                </button>

                <div
                    class="menu"
                    id="cloneDeleteActionsMenu"
                    role="menu"
                    aria-labelledby="cloneDeleteActions"
                >
                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="clone-button"
                    >
                        <i class="fas fa-clone mi-icon"></i>
                        <?php echo $this->user->lang('Clone'); ?>
                    </button>

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

    </div>
</div>

<script data-cfasync="false">
    var admin_edit_packagetypes = <?php echo ($this->user->hasPermission('admin_edit_packagetypes')) ? "true" : "false"; ?>;
    const collapsedGroups = JSON.parse(
        localStorage.getItem('collapsedProductGroups') || '{}'
    );

    $(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, group) {
                    const d = rows.data()[0];
                    const groupId = d.groupid;
                    const collapsed = collapsedGroups[groupId] === true;
                    const count = rows.count();

                    return $(`
                        <tr class="dt-group-header ${collapsed ? 'collapsed' : ''}"
                            data-group-id="${groupId}">
                            <td colspan="6">
                                <span class="group-toggle">
                                    ${collapsed ? '▶' : '▼'}
                                </span>

                                <strong>
                                    ${group}
                                </strong>

                                <span class="text-muted">(${count})</span>
                            </td>
                        </tr>
                    `);
                }
            },

            rowCallback: function (row, data) {
                if (collapsedGroups[data.groupid]) {
                    $(row).hide();
                } else {
                    $(row).show();
                }
            },

            "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 () {
            const selectedCount = table.rows({ selected: true }).count();

            const $dd = $('#cloneDeleteActions');
            const $pill = $dd.find('.pill');

            // No selection → disable everything
            if (selectedCount === 0) {
                clientexec.tableActions.setEnabled($pill, false);
                clientexec.tableActions.setVisible($('#clone-button'), false);
                clientexec.tableActions.setVisible($('#delete-button'), false);
                clientexec.tableActions.closeDropdown($dd);
                return;
            }

            // At least one row selected → enable dropdown
            clientexec.tableActions.setEnabled($pill, true);
            // Delete is always allowed with 1+
            clientexec.tableActions.setVisible($('#delete-button'), true);
            // Clone only allowed with exactly 1
            clientexec.tableActions.setVisible($('#clone-button'), selectedCount === 1);
            clientexec.tableActions.closeDropdown($dd);
        });


        $('#table-list tbody').on('click', '.group-toggle', function (e) {
            e.stopPropagation();

            const groupId = $(this)
                .closest('tr.dt-group-header')
                .data('group-id');

            collapsedGroups[groupId] = !collapsedGroups[groupId];

            localStorage.setItem(
                'collapsedProductGroups',
                JSON.stringify(collapsedGroups)
            );

            table.draw(false);
        });




        $('#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>