<div class="page-title">
    <h1><?php echo $this->user->lang("Commissions");?></h1>
</div>

<div class="cm-holder settings-wrapper dt-info">
    <div class="head">
        <div class="filter-block" style="">
            <table>
                <tr>
                    <td>
                        <?php echo $this->user->lang("Show");?>
                        <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>
                    </td>
                </tr>
            </table>
        </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="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="com-approve"><?php echo $this->user->lang('Approve'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="com-decline"><?php echo $this->user->lang('Decline'); ?></button></li>
                        <li><button class="dropdown-item d-none" id="com-markpaid"><?php echo $this->user->lang('Mark Paid Out'); ?></button></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    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() {
            $(".table-actions .btn-group").removeClass("d-none");
            $(".table-actions .btn-group button").removeClass("d-none");
        };

        commissions.disableButtons = function() {
            $(".table-actions .btn-group").addClass("d-none");
            $(".table-actions .btn-group button").addClass("d-none");
        };

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