<div class="page-title">
    <h1><?php echo $this->user->lang("Domain Package List");?></h1>
    <span><?php echo $this->user->lang("List of your client's Domain packages."); ?></span>
</div>

<?php
if ( $this->showWarning == 0 ) { ?>
<div class="alert alert-danger">
    <span class="bold-item"><?php echo $this->user->lang('Notice'); ?>:</span>&nbsp;<?php echo $this->user->lang('The domain updater service is currently turned off.  Some information may be out of date.'); ?>&nbsp;&nbsp;<a href="index.php?fuse=admin&controller=settings&settings=plugins_services&type=Services&view=plugins&setting=domainupdater"><?php echo $this->user->lang('Click here to turn the service on.'); ?></a>
</div>
<?php } ?>

<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) == 'domain'){
                                    $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="expired"><?php echo $this->user->lang('Expired'); ?></option>
                            <option value="30days"><?php echo $this->user->lang('Expires within 30 Days'); ?></option>
                            <option value="15days"><?php echo $this->user->lang('Expires within 15 Days'); ?></option>
                            <option value="tomorrow"><?php echo $this->user->lang('Expires Tomorrow'); ?></option>
                            <option value="today"><?php echo $this->user->lang('Expires Today'); ?></option>
                            <option value="canceled"><?php echo $this->user->lang('Cancelled'); ?></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('Domain Name'); ?></th>
                        <th class=""><?php echo $this->user->lang('Client'); ?></th>
                        <th class=""><?php echo $this->user->lang('Expiration'); ?></th>
                        <th class=""><?php echo $this->user->lang('Next Bill Date'); ?></th>
                        <th class=""><?php echo $this->user->lang('Period'); ?></th>
                        <th class=""><?php echo $this->user->lang('Auto Renew'); ?></th>
                        <th class=""><?php echo $this->user->lang('Registrar'); ?></th>
                        <th class=""><?php echo $this->user->lang('Status'); ?></th>
                        <th class=""><?php echo $this->user->lang('Recurring Price'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <div class="dropdown" id="packageReminderActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="packageReminderActionsMenu"
                    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="packageReminderActionsMenu"
                    role="menu"
                    aria-labelledby="packageReminderActions"
                >
                    <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 class="menu-sep" role="separator"></div>

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="btn-send-reminder"
                    >
                        <i class="fas fa-envelope mi-icon"></i>
                        <?php echo $this->user->lang('Send Reminder'); ?>
                    </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;

        // Dynamically build columns
        var columns = [];

        // Add expander column only if custom fields exist
        if (hasCustomFields) {
            columns.push({
                className: 'details-control',
                orderable: false,
                data: null,
                defaultContent: ''
            });
        }

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

        // Add the rest of your columns
        columns.push(
            { "data": "id" },
            {
                "data": "domainname",
                render: function (data, type, row) {
                    if (type === 'display') {
                        value = clientexec.htmlspecialchars(row.domainname);
                        nameString = "<a href='index.php?fuse=clients&controller=userprofile&view=profileproduct&frmClientID=" + row.customerid + "&id=" + row.id + "'>"+value+"</a>";

                        if (row.cycle_issue == true) {
                            return nameString + " <a href='index.php?fuse=clients&controller=userprofile&view=profileproducts&frmClientID=" + row.customerid + "&packageid=" + row.id + "&tab=billing&frmClientID=" + row.customerid + "'><img style='padding-left:2px;margin-bottom:-3px;' title='" + clientexec.lang('Invalid payment term for domain') + "' src='../templates/admin/images/icon_alert.gif' /></a>";
                        } else {
                            return nameString;
                        }
                    }

                    return data;
                }
            },
            {
                "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": "expires",
                render: clientexec.dateRenderer
            },
            {
                "data": "renewal",
                render: clientexec.dateRenderer
            },
            { "data": "period" },
            { "data": "autorenew" },
            { "data": "registrar" },
            {
                "data": "status",
                render: function (data, type, record) {
                    return String.format('<span class="status-btn {1}">{0}</span>', record.status, record.status_class);
                }
            },
            {
                "data": "price",
                orderable: false
            }
        );

        console.log(columns);

        // Determine checkbox column index
        var checkboxColIndex = hasCustomFields ? 1 : 0;

        // Determine selection selector
        var selectorColumn = hasCustomFields ? 'td:nth-child(2)' : 'td:first-child';

        var table = $('#table-list').DataTable({
            columnDefs: [{
                targets: checkboxColIndex,
                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: [[ hasCustomFields ? 2 : 1, '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;
                }
            }
        });

        $('#btn-send-reminder').click(function () {
            packages.disableButtons();

            var rowIds = table.getSelectedRows();

            var data = {
                ids: rowIds
            };

            $.ajax({
                url: "index.php?action=senddomainreminder&controller=packages&fuse=clients",
                type: 'POST',
                data:  data,
                success:  function (xhr) {
                    clientexec.parseResponse(xhr);
                    table.ajax.reload();

                    if (typeof profile !== "undefined") {
                        setTimeout(function () {
                            profile.get_counts();
                        },1000);
                    }
                }
            });
        });

        $("[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 domain(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 = $('#packageReminderActions');
            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 = $('#packageReminderActions');
            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>
