<div class="page-title">
    <h1><?php echo $this->user->lang("Taxes");?></h1>
    <span><?php echo $this->user->lang("Add tax support to your Clientexec."); ?></span>

</div>

<div class="cm-holder settings-wrapper dt-info">
    <div class="head">
        <button class="action-buttons blue" id="add-button">
            <i class="icon-ic-21"></i>
            <?php echo $this->user->lang('Add Tax'); ?>
        </button>
    </div>
    <div class="dt-wrapper pull-top">
        <div class="table-responsive">
            <table id="taxes-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th style="text-align: center">
                            <input type="checkbox" id="checkAll">
                        </th>
                        <th class="width3 relative"><?php echo $this->user->lang('Name'); ?></th>
                        <th class="width3"><?php echo $this->user->lang('Country'); ?></th>
                        <th class="width3"><?php echo $this->user->lang('Division'); ?></th>
                        <th class="width3 "><?php echo $this->user->lang('Level'); ?></th>
                        <th class="width3 "><?php echo $this->user->lang('Compound'); ?></th>
                        <th class="width3 "><?php echo $this->user->lang('VAT'); ?></th>
                        <th class="width3 "><?php echo $this->user->lang('Rate'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="table-actions">
            <button class="action-buttons" id="delete" disabled="disabled"><i class="icon-ic-25"></i><?php echo $this->user->lang('Delete'); ?></button>
        </div>
    </div>

</div>
<div class="card p-2">
    <?php echo $this->user->lang('If a tax rule is applied to all countries, it will be the default tax unless otherwise specified.'); ?><br />
    <?php echo $this->user->lang('If a tax rule is applied to all states, it will be the countries default tax unless otherwise specified.'); ?>
</div>

<script>
    $(document).ready(function () {
        var ajaxUrl = 'index.php?fuse=billing&controller=tax&action=gettaxrules';
        var table = $('#taxes-list').DataTable({
            columnDefs: [{
                targets: 0,
                orderable: false,
                className: 'select-checkbox',
                checkboxes: {
                    selectRow: true
                },
                width: '5%'
            },
            { width: '50px', targets: 4},
            { width: '50px', targets: 5},
            { width: '50px', targets: 6},
            { width: '50px', targets: 7},
            ],
            select: {
                style: 'multi',
                selector: 'td:first-child'
            },
            "searching": false,
            "ajax": {
                url: ajaxUrl,
                dataSrc: 'rules'
            },
            "columns": [
                { data: null, defaultContent: '', orderable: false, },
                {
                    "data": "name",
                    render: taxes.renderer.name,
                },
                {
                    "data": "country",
                    render: taxes.renderer.country,
                },
                {
                    "data": "state",
                    render: taxes.renderer.state,
                },
                {
                    "data": "level",
                },
                {
                    "data": "compound",
                    render: taxes.renderer.yesno,
                },
                {
                    "data": "vat",
                    render: taxes.renderer.yesno,
                },
                {
                    "data": "tax",
                    render: taxes.renderer.displayrate,
                }

            ],
            "order": [[1, 'asc']]
        });


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


        var addEditWindow = new RichHTML.window({
            url: 'index.php?fuse=billing&controller=tax&view=edit',
            actionUrl: 'index.php?fuse=billing&controller=tax&action=save',
            showSubmit: true,
            title: clientexec.lang('Add/Edit Tax Rule'),
            onSubmit: function (data) {
                clientexec.parseResponse(data);
                table.ajax.url(ajaxUrl);
                table.ajax.reload();
            }
        });

        $('#add-button').on('click', function(){
            addEditWindow.show();
        });

        $('#delete').click(function () {
            var rowIds = [];
            var selectedRows = table.rows({ selected: true }).data();
            selectedRows.each(function(value, index) {
                rowIds.push(value.id);
            });

            $.post('index.php?fuse=billing&controller=tax&action=delete', { ids: rowIds }, function(data) {
                clientexec.parseResponse(data);
                table.ajax.url(ajaxUrl);
                table.ajax.reload();
            });
        });


        $('#taxes-list').on('click', 'a', function(event) {
            addEditWindow.show({
                params: {
                    id: $(this).attr('data-id')
                }
            });
            event.preventDefault;
        });

        table.on('select.dt deselect.dt', function() {
            var selectedRows = table.rows({ selected: true }).count();
            if (selectedRows > 0) {
               $('.table-actions .action-buttons').prop('disabled', false);

            } else {
                $('.table-actions .action-buttons').prop('disabled', true);
            }
        });
    });

    var taxes = {
        dom: {
            buttonAddTax: $('#button-addTax'),
            buttonDeleteTax: $('#button-deleteTax'),
            selectTaxesGridFilterCount: $('#select-taxes-grid-filter-count'),
            divTaxesGrid: $('#div-taxes-grid'),
            currentCountry: ''
        },
        renderer: {
            'country': function(text) {
                if (text == '_ALL') {
                    return clientexec.lang('All (Default)');
                } else {
                    return text;
                }
            },
            'state': function(text, display, row) {
                if (text == '_ALL') {
                    return clientexec.lang('All (Default)');
                } else {
                    return row.statename;
                }
            },
            'yesno': function(text) {
                return text == 'true' ? clientexec.lang('Yes') : clientexec.lang('No');
            },
            'displayrate': function(text) {
                return parseFloat(text) + '%';
            },
            'name': function(text, display, row) {
                 return '<a class="link2" data-id="'+row.id+'">'+text+'</a>';
            }
        },
        list: {
            countries: [],
            states: []
        },
        checkLists: function() {
            var that = this;

            return new Promise(function(resolve, reject) {
                if (that.list.countries && that.list.countries.length > 0) {
                    resolve(that.list.countries);
                } else {
                    $.getJSON('index.php?fuse=admin&controller=settings&action=getcountrylist')
                        .done(function(response) {
                            that.list.countries = response.countries.map(function(item) {
                                return {
                                    id: item.iso,
                                    name: item.name,
                                    division: item.division,
                                    divisionPlural: item.division_plural
                                };
                            });
                            resolve(that.list.countries);
                        })
                        .fail(function(err) {
                            reject(err);
                        });
                }
            });
        },
        checkListsStates: function(countryId, selectedStateId) {
            var that = this;

            return new Promise(function(resolve, reject) {
                if (that.list.states && that.list.states.length > 0) {
                    resolve(that.list.states);
                } else {
                    $.getJSON('index.php?fuse=admin&controller=settings&action=getstatelist&countryIso='+countryId+'&stateIso='+selectedStateId+'&displayAll=1')
                    .done(function(response) {
                        that.list.states = response.states.map(function(item) {
                            return {
                                id: item.iso,
                                name: item.name
                            };
                        });
                        resolve(that.list.states);
                    })
                    .fail(function(err) {
                        reject(err);
                    });
                }
            });
        }
    };
</script>