<div class="page-title">
    <h1><?php echo $this->user->lang("Pending Package Cancellation List");?></h1>
    <span><?php echo $this->user->lang("List of your client's packages pending cancellation."); ?></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("Show");?></label>
                        <select id="filterByStatus">
                            <option value="-1"><?php echo $this->user->lang('All'); ?></option>
                            <option value="<?php echo PACKAGE_CANCELLATION_TYPE_IMMEDIATE; ?>"><?php echo $this->user->lang("Immediately");?></option>
                            <option value="<?php echo PACKAGE_CANCELLATION_TYPE_END_BILLING; ?>"><?php echo $this->user->lang("End of Billing Cycle");?></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="packages-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <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('Package'); ?></th>
                        <th class="width4 "><?php echo $this->user->lang('Client'); ?></th>
                        <th class=""><?php echo $this->user->lang('Reason'); ?></th>
                        <th class=""><?php echo $this->user->lang('Request Date & Time'); ?></th>
                        <th class=""><?php echo $this->user->lang('Cancel On'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <button
                class="pill"
                type="button"
                id="pkg-cancel"
                disabled="disabled"
            >
                <i class="fas fa-ban"></i>
                <?php echo $this->user->lang('Cancel'); ?>
            </button>
        </div>

    </div>
</div>

<script data-cfasync="false">
    var packages = packages || {};

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

    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=clients&action=getpendingcancellations&controller=packages';
        var table = $('#packages-list').DataTable({
            columnDefs: [{
                targets: 0,
                orderable: false,
                className: 'select-checkbox',
                checkboxes: {
                    selectRow: true
                },
                width: '5%'
            }],

            select: {
                style: 'multi',
                selector: 'td:first-child'
            },

            "searching": false,
            "ajax": {
                url: ajaxUrl,
                dataSrc: 'results', // The root is results in the ajax call.
                data: function(d) {
                    d.filter = $('#filterByStatus').val();
                }
            },
            rowCallback: function (row, data) {
                $(row).removeClass('cancel-highlight');

                let highlight = false;

                if (data.when === 'Immediately') {
                    highlight = true;
                } else {
                    const cancelDate = new Date(data.when);
                    const now = new Date();

                    if (!isNaN(cancelDate) && cancelDate < now) {
                        highlight = true;
                    }
                }

                if (highlight) {
                    $(row).addClass('cancel-highlight');
                }
            },
            "columns": [
                { data: null, defaultContent: '', orderable: false, },
                { "data": "id" },
                {
                    "data": "name",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            value = clientexec.htmlspecialchars(row.name);
                            return "<a href='index.php?fuse=clients&controller=userprofile&view=profileproduct&frmClientID=" + row.customerid + "&id=" + row.id + "'>"+value+"</a>";
                        }

                        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": "reason" },
                {
                    "data": "requestdate",
                    render: clientexec.dateRenderer
                },
                {
                    data: 'when',
                    render: function (data, type, row) {
                        if (type === 'sort' || type === 'type') {
                            if (data === 'Immediately') {
                                return 0; // absolute top priority
                            }

                            const d = new Date(data);
                            if (!isNaN(d)) {
                                return d.getTime(); // timestamp sort
                            }

                            return Number.MAX_SAFE_INTEGER;
                        }


                        if (data === 'Immediately') {
                            return `
                                <span class="cancel-label cancel-immediate">
                                    <i class="fa fa-exclamation-triangle"></i>
                                    Immediately
                                </span>
                            `;
                        }

                        const cancelDate = new Date(data);
                        const now = new Date();

                        if (!isNaN(cancelDate) && cancelDate < now) {
                            return `
                                <span class="cancel-label cancel-past">
                                    <i class="fa fa-clock"></i>
                                    ${data}
                                </span>
                            `;
                        }

                        return data;
                    }
                }

            ],
            "order": [[6, '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();
        });

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

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

            RichHTML.msgBox(
                clientexec.lang('Do you want to use the respective server plugin(s) to % these package(s)?', id),
                {
                    type: "confirm"
                },
                function (result) {
                    if (result.btn === clientexec.lang('Cancel')) {
                        return;
                    } else if (result.btn === clientexec.lang('Yes')) {
                        usePlugin = 1;
                    } else {
                        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 () {
            $('#pkg-cancel').prop('disabled', false);
        };

        packages.disableButtons = function () {
            $('#pkg-cancel').prop('disabled', true);
        };

        packages.disableButtons();
    });
</script>