<div class="page-title">
    <h1><?php echo $this->user->lang("General Package List");?></h1>
    <span><?php echo $this->user->lang("List of your client's General packages."); ?></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("Type");?>
                        <select id="filterByType">
                        <?php
                            foreach($this->productgroups as $key=>$cat) {
                                $selected = "";
                                if(in_array($this->selected_group, array("", 0)) && strtolower($key) == 'general'){
                                    $this->selected_group = 0;
                                    $selected = "selected";
                                }
                                echo "<option class='optionGroup' value='".strtolower($key)."_0' ".$selected.">".$key."</option>";
                                foreach($cat as $productgroup) {
                                    $selected = "";
                                    if($productgroup['id'] == $this->selected_group){
                                        $selected = "selected";
                                    }
                                    echo "<option class='optionChild' value='".strtolower($key)."_".$productgroup['id']."' ".$selected.">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$productgroup['name']."</option>";
                                }
                            }
                        ?>
                        </select>
                    </td>
                    <td>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <?php echo $this->user->lang("Show");?>
                        <select id="filterByStatus">
                            <option value="active"><?php echo $this->user->lang('Active'); ?></option>
                            <option value="all"><?php echo $this->user->lang('All'); ?></option>
                            <option value="pending"><?php echo $this->user->lang('Pending'); ?></option>
                            <option value="pendingcancel"><?php echo $this->user->lang('Pending Cancelation'); ?></option>
                            <option value="suspended"><?php echo $this->user->lang('Suspended'); ?></option>
                            <option value="canceled"><?php echo $this->user->lang('Cancelled'); ?></option>
                            <option value="expired"><?php echo $this->user->lang('Expired'); ?></option>
                        </select>
                    </td>
                </tr>
            </table>
        </div>
    </div>

    <div class="dt-wrapper pull-top">
        <div class="table-responsive">
            <table id="table-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <?php if (count(json_decode(html_entity_decode($this->customfields))) > 0) { ?>
                        <th></th>
                        <?php } ?>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th class=""><?php echo $this->user->lang('Id'); ?></th>
                        <th class=""><?php echo $this->user->lang('Client'); ?></th>
                        <th class=""><?php echo $this->user->lang('Package'); ?></th>
                        <th class=""><?php echo $this->user->lang('Group'); ?></th>
                        <th class=""><?php echo $this->user->lang('Status'); ?></th>
                        <th class=""><?php echo $this->user->lang('Cycle'); ?></th>
                        <th class=""><?php echo $this->user->lang('Next Due Date'); ?></th>
                        <th class=""><?php echo $this->user->lang('Recurring Price'); ?></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="pkg-suspend"><?php echo $this->user->lang('Suspend'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="pkg-unsuspend"><?php echo $this->user->lang('UnSuspend'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="pkg-cancel"><?php echo $this->user->lang('Cancel'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="pkg-delete"><?php echo $this->user->lang('Delete'); ?></button></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

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

    packages.customFields = <?php echo html_entity_decode($this->customfields) ?>

    <?php
        if($this->selected_group == ''){
            $this->selected_group = 0;
        }
    ?>
    packages.groupid = <?php echo $this->selected_group; ?>;

    packages.getType = function () {
        var typeParts =  $('#filterByType').val().split("_");

        switch (typeParts[0]) {
            case 'general':
                return 0;
            case 'hosting':
                return 1;
            case 'ssl':
                return 2;
            case 'domain':
                return 3;
        }
    };

    packages.getGroupId = function () {
        var typeParts =  $('#filterByType').val().split("_");

        return typeParts[1];
    };

    packages.type = packages.getType();

    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=clients&action=getpackages&controller=packages';

        var hasCustomFields = packages.customFields && packages.customFields.length > 0;

        // Build columns dynamically (same as hosting)
        var columns = [];

        // 1. Expander column ONLY when custom fields exist
        if (hasCustomFields) {
            columns.push({
                className: 'details-control',
                orderable: false,
                data: null,
                defaultContent: ''
            });
        }

        // 2. Checkbox column (always present)
        columns.push({
            data: null,
            defaultContent: '',
            orderable: false
        });

        // 3. Standard table columns
        columns.push(
            { data: "id" },
            {
                data: "customer",
                render: function (data, type, row) {
                    if (type === 'display') {
                        value = clientexec.htmlspecialchars(row.customer);
                        return '<a href="index.php?fuse=clients&controller=userprofile&view=profilecontact&frmClientID=' +
                            row.customerid + '">' + value + '</a>';
                    }
                    return data;
                }
            },
            {
                data: "name",
                render: function (data, type, row) {
                    if (type === 'display') {
                        value = clientexec.htmlspecialchars(row.productname);
                        return '<a href="index.php?fuse=clients&controller=userprofile&view=profileproduct&frmClientID=' +
                            row.customerid + '&id=' + row.productid + '">' + value + '</a>';
                    }
                    return data;
                }
            },
            { data: "productgroupname" },
            {
                data: "status",
                render: function (data, type, record) {
                    return String.format('<span class="status-btn {1}">{0}</span>',
                        record.status, record.status_class);
                }
            },
            { data: "cycle" },
            { data: "renewal", render: clientexec.dateRenderer },
            { data: "price" }
        );

        // Checkbox + selector column index logic
        var checkboxTarget = hasCustomFields ? 1 : 0;
        var selectorColumn = hasCustomFields ? 'td:nth-child(2)' : 'td:first-child';

        // ID column index changes depending on presence of expander
        var idColumnIndex = hasCustomFields ? 2 : 1;

        var table = $('#table-list').DataTable({
            columnDefs: [{
                targets: checkboxTarget,
                orderable: false,
                className: 'select-checkbox',
                checkboxes: {
                    selectRow: true
                },
                width: '5%'
            }],

            select: {
                style: 'multi',
                selector: selectorColumn
            },

            searching: false,

            ajax: {
                url: ajaxUrl,
                dataSrc: 'results',
                data: function(d) {
                    d.filter = $('#filterByStatus').val();
                    d.type = packages.getType();
                    d.groupid = packages.getGroupId();
                }
            },

            columns: columns,

            order: [[idColumnIndex, 'asc']]
        });

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

        $('#filterByStatus').on('change', function () {
            packages.disableButtons();
            table.ajax.reload();
        });
        
        $('#filterByType').on('change', function () {
            var type = packages.getType();

            if (packages.type == type) {
                packages.disableButtons();
                table.ajax.reload();
            } else {
                var groupId = packages.getGroupId()
                groupId = '&groupid='+groupId;

                switch (type) {
                    case 0:
                        window.location = 'index.php?fuse=clients&controller=packages&view=generalpackageslist' + groupId;
                        break;
                    case 1:
                        window.location = 'index.php?fuse=clients&controller=packages&view=hostingpackagelist' + groupId;
                        break;
                    case 2:
                        window.location = 'index.php?fuse=clients&controller=packages&view=sslpackagelist' + groupId;
                        break;
                    case 3:
                        window.location = 'index.php?fuse=clients&controller=packages&view=domainslist' + groupId;
                        break;
                }
            }
        });

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

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

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

                    usePlugin = 0;
                    packages.disableButtons();
                    packages.performaction(id, usePlugin)
                }
            );
        });

        packages.performaction = function (id, usePlugin) {
            var rowIds = table.getSelectedRows();

            var data = {
                ids:       rowIds,
                useplugin: usePlugin
            };

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

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

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

        packages.enableButtons = function() {
            $(".table-actions .btn-group").removeClass("d-none");
            $(".table-actions .btn-group button").removeClass("d-none");
        };

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

        packages.disableButtons();

        $('#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 {
                fetchRowDetails(row.data()).then(function (data) {
                    const apiData = data;
                    const cfList = packages.customFields;

                    let output = "";

                    Object.keys(apiData).forEach(key => {
                        const field = apiData[key];

                        if (!field || !field.id) return;

                        const matchId = "custom_" + field.id;

                        const match = cfList.find(cf => cf.id === matchId);

                        if (match) {
                            output += `<b>${match.text}:</b> ${field.value}<br>`;
                        }
                    });

                    row.child(output).show();
                    tr.addClass('shown');
                });
            }
        });

        function fetchRowDetails(row) {
            return new Promise((resolve, reject) => {
                $.get("index.php?fuse=clients&controller=packages&action=getcustomfieldsforpackage", { id: row.id }, function(data) {})
                .done(resolve)
                .fail(reject);
            });
        }
    });
</script>
