<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 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) == '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>
                    </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="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>
                    </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('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="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-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 class="btn-group">
                    <button class="btn btn-outline-secondary d-none" id="btn-send-reminder"><?php echo $this->user->lang('Send Reminder'); ?></button>
                </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;

        // 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" }
        );

        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,

            ajax: {
                url: ajaxUrl,
                dataSrc: 'results',
                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() {
            $(".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>
