<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 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("Type");?></label>
                        <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>
                    </div>
                    <div class="filter-group">
                        <label><?php echo $this->user->lang("Show");?></label>
                        <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>
                    </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="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="dropdown" id="packageSuspendActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="packageSuspendActionsMenu"
                    disabled="disabled"
                >
                    <i class="fas fa-box"></i>
                    <?php echo $this->user->lang('Actions'); ?>
                    <i class="fas fa-chevron-down caret"></i>
                </button>

                <div
                    class="menu"
                    id="packageSuspendActionsMenu"
                    role="menu"
                    aria-labelledby="packageSuspendActions"
                >
                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="pkg-suspend"
                    >
                        <i class="fas fa-pause-circle mi-icon"></i>
                        <?php echo $this->user->lang('Suspend'); ?>
                    </button>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="pkg-unsuspend"
                    >
                        <i class="fas fa-play-circle mi-icon"></i>
                        <?php echo $this->user->lang('UnSuspend'); ?>
                    </button>

                    <div class="menu-sep" role="separator"></div>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="pkg-cancel"
                    >
                        <i class="fas fa-ban mi-icon"></i>
                        <?php echo $this->user->lang('Cancel'); ?>
                    </button>

                    <button
                        class="menu-item danger"
                        role="menuitem"
                        type="button"
                        id="pkg-delete"
                    >
                        <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 packages = packages || {};

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

    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",
                orderable: false
            }
        );

        // 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,
            processing: true,
            serverSide: true,

            ajax: {
                url: ajaxUrl,
                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 () {
            const $dd = $('#packageStatusActions');
            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);
        };

        packages.disableButtons = function () {
            const $dd = $('#packageStatusActions');
            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);
        };

        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>
