<div class="page-title">
    <h1><?php echo $this->user->lang("Commissions");?></h1>
</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->filter == -1) ? "selected" : "" ?>><?php echo $this->user->lang("All"); ?></option>
                            <option value='0' <?php echo ($this->filter == 0) ? "selected" : "" ?>><?php echo $this->user->lang("Pending"); ?></option>
                            <option value='1' <?php echo ($this->filter == 1) ? "selected" : "" ?>><?php echo $this->user->lang("Approved"); ?></option>
                            <option value='2' <?php echo ($this->filter == 2) ? "selected" : "" ?>><?php echo $this->user->lang("Paid"); ?></option>
                            <option value='4' <?php echo ($this->filter == 4) ? "selected" : "" ?>><?php echo $this->user->lang("Pending Pay Out"); ?></option>
                            <option value='3' <?php echo ($this->filter == 3) ? "selected" : "" ?>><?php echo $this->user->lang("Declined"); ?></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="commissions-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th></th>
                        <th class=""><?php echo $this->user->lang('Id'); ?></th>
                        <th class="width4 "><?php echo $this->user->lang('Client'); ?></th>
                        <th class="width4 "><?php echo $this->user->lang('Affiliate'); ?></th>
                        <th class=""><?php echo $this->user->lang('Package'); ?></th>
                        <th class=""><?php echo $this->user->lang('Clearing Date'); ?></th>
                        <th class=""><?php echo $this->user->lang('Order Value'); ?></th>
                        <th class=""><?php echo $this->user->lang('Commission'); ?></th>
                        <th class=""><?php echo $this->user->lang('Status'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <div class="dropdown" id="commissionActions" data-open="false">
                <button
                    class="pill"
                    type="button"
                    aria-haspopup="menu"
                    aria-expanded="false"
                    aria-controls="commissionActionsMenu"
                    disabled="disabled"
                >
                    <i class="fas fa-hand-holding-usd"></i>
                    <?php echo $this->user->lang('Actions'); ?>
                    <i class="fas fa-chevron-down caret"></i>
                </button>

                <div
                    class="menu"
                    id="commissionActionsMenu"
                    role="menu"
                    aria-labelledby="commissionActions"
                >
                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="com-approve"
                    >
                        <i class="fas fa-check mi-icon"></i>
                        <?php echo $this->user->lang('Approve'); ?>
                    </button>

                    <button
                        class="menu-item danger"
                        role="menuitem"
                        type="button"
                        id="com-decline"
                    >
                        <i class="fas fa-times mi-icon"></i>
                        <?php echo $this->user->lang('Decline'); ?>
                    </button>

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

                    <button
                        class="menu-item"
                        role="menuitem"
                        type="button"
                        id="com-markpaid"
                    >
                        <i class="fas fa-dollar-sign mi-icon"></i>
                        <?php echo $this->user->lang('Mark Paid Out'); ?>
                    </button>
                </div>
            </div>
        </div>

    </div>
</div>

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

    <?php if ($this->affiliateId != -1) { ?>
    commissions.affiliateId = '<?php echo $this->affiliateId; ?>';
    <?php } ?>

    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=affiliates&action=getcommissions&controller=commission&comma=yes&limit=0';
        var table = $('#commissions-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: 'commissions', // The root is commissions in the ajax call.
                data: function(d) {
                    d.status = $('#filterByStatus').val();
                }
            },
            "columns": [
                { data: null, defaultContent: '', orderable: false, },
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                { "data": "id" },
                {
                    "data": "client",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            var name = clientexec.htmlspecialchars(row.client);

                            if (name == '') {
                                url = String.format('<b>Bonus Deposit</b>');
                            } else {
                                url = String.format('<a href="index.php?fuse=clients&controller=userprofile&view=profilecontact&frmClientID={1}">{0}</a></span>', name, row.client_id);
                            }

                            return url;
                        }

                        return data;
                    }
                },
                {
                    "data": "affiliate",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            var name = clientexec.htmlspecialchars(row.affiliate);
                            return String.format('<a href="index.php?fuse=clients&controller=userprofile&view=profileaffiliate&frmClientID={1}">{0}</a></span>', name, row.affiliate_client_id);
                        }

                        return data;
                    }
                },
                {
                    "data": "user_package",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            var name = clientexec.htmlspecialchars(row.user_package);

                            if (name == '') {
                                url = String.format('<b>-</b>');
                            } else {
                                url = String.format('<a href="index.php?fuse=clients&controller=userprofile&view=profileproduct&selectedtab=groupinfo&id={1}&frmClientID={2}">{0}</a></span>', name, row.user_package_id, row.client_id);
                            }

                            return url;
                        }

                        return data;
                    }
                },
                { "data": "clearing_date" },
                { "data": "order_value" },
                { "data": "amount" },
                {
                    "data": "status",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            return String.format("{0}", row.status_name);
                        }

                        return data;
                    }
                }
            ],
            "order": [[2, 'asc']]
        });

        $('#commissions-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 {
                var expanderBody = '<b>' + clientexec.lang('Date') + ': </b>';
                expanderBody += row.data().date;
                expanderBody += '<br/><b>' + clientexec.lang('Package') + ': </b>';
                expanderBody += row.data().user_package;
                row.child(expanderBody).show();
                tr.addClass('shown');
            }
        });

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

        $('#filterByStatus').on('change', function () {
            commissions.disableButtons();
            table.ajax.reload();
        });

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

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

            action = id;
            if (action == 'markpaid') {
                action = 'mark as paid out';
            }

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

                    commissions.disableButtons();
                    commissions.performaction(id)
                }
            );
        });

        commissions.performaction = function (id) {
            var rowIds = table.getSelectedRows();

            var data = {
                ids: rowIds
            };

            if (id != 'markpaid') {
                id = id + "commissions";
            }

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

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

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

        commissions.enableButtons = function () {
            const $dd = $('#commissionActions');
            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);
        };

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




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