<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div id="bonus_alert"></div>
            <div class="panel-title">
                <h4 class="bold"><?php echo CommonLanguage::getMessage($title); ?> </h4>

            </div>
            <div class="row">
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('Date') ?></label>
                    <span class="red-star">*</span>
                    <div class="input-group">
                        <span class="input-group-addon bg-<?php echo $current_color; ?>"><i class="fa fa-calendar"></i></span>
                        <input id="From_To_Date" type="text" class="form-control" name="From_To_Date" autocomplete="off" >
                    </div>
                </div> 
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('commission') ?></label>
                    <span class="red-star">*</span>
                    <input id="commission_id" type="hidden" class="full-width" name="commission_id" autocomplete="off">
                </div> 
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('salesman') ?></label>
                    <input id="sales_id" type="hidden" class="full-width" name="sales_id" autocomplete="off" >
                </div> 
                <div class="col-md-2 m-t-20 pull-right">
                    <button class="btn btn-<?php echo $current_color; ?> pull-right" id="generate_report"><?php echo CommonLanguage::getMessage('generate_report'); ?></button>
                </div> 
            </div>
        </div>
        <div class="panel-body">
            <div class="row ">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered <?php echo $current_type; ?>" id="tableWithSearch" >
                        <thead>
                            <tr>
                                <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('salesman'); ?></th>
                                <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('total_invoices'); ?></th>
                                <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('total_return'); ?></th>
                                <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('balance'); ?></th>
                                <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('commission'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th><div class="text-center"><strong><span id="total"></span></strong></div></th>
                            </tr>
                            <?php if ($permissions->hasPermission('submit_commission_bonus') && $current_type == 'hrm') { ?>
                                <tr>
                                    <th></th>
                                    <th></th>
                                    <th></th>
                                    <th></th>
                                    <th><button class="btn btn-success full-width" id="submit_sales_commissions"><?php echo CommonLanguage::getMessage('Save'); ?></button></th>
                                </tr>
                            <?php } ?>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var today = <?php echo json_encode($today) ?>, current_type =<?php echo json_encode($current_type); ?>,
            local_currency = <?php echo json_encode(smc_session()['default_setting']['local_currency']); ?>,
            Submitted_Successfully =<?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Failed_Submit =<?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            is_actual =<?php echo $is_actual ? 1 : 0; ?>;
    $(function () {
        build_select2($('#sales_id'), 'xhr/employeeSearch', 1);
        build_select2($('#commission_id'), 'xhr/commonSearch?col_id=commission_id&col_name=commission_name&table=tbl_commission_type');
        $("input[name=From_To_Date]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }, locale: {
                cancelLabel: 'Clear'
            }, allowEmpty: false,
            autoUpdateInput: false
        });
        $('#submit_sales_commissions').on('click', function () {
            $("#bonus_alert").addClass('hidden')
            var Data = {
                bonuses: []
            };
            var row = $("#tableWithSearch").dataTable().fnGetNodes();
            for (var i = 0; i < row.length; i++) {
                if ($(row[i]).find("input.commission").val() != '' && $(row[i]).find("input.commission").val() > 0) {
                    Data.bonuses.push({
                        url: true,
                        IsBonus: true,
                        Employee_ID: $(row[i]).find("input.commission").attr("data-emp"),
                        Deduction_Date: window.endDate,
                        Currency_ID: local_currency,
                        Deduction_Amount: $(row[i]).find("input.commission").val(),
                        Deduction_Description: 'commission',
                        Entry_ID: '',
                        Check_ID: 'addDeduction',
                        is_actual: is_actual
                    })
                }
            }
            $.ajax({
                url: "HRMAjax/add_commission_bonus",
                data: Data,
                method: 'post',
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseText == 'OK') {
                        $("#bonus_alert").attr("class", "alert alert-success").html(Submitted_Successfully)
                        setTimeout(function () {
                            $("#bonus_alert").removeClass('hidden')
                        }, 1500)
                    } else {
                        $("#bonus_alert").attr("class", "alert alert-danger").html(v1.responseText)

                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                }
            })
        });

        $("input[name=From_To_Date]").on('apply.daterangepicker', function (ev, picker) {
            window.startDate = picker.startDate.format('YYYY-MM-DD');
            window.endDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
        });
        $("input[name=From_To_Date]").on('cancel.daterangepicker', function (ev, picker) {
            window.startDate = ''
            window.endDate = ''
            $(this).val('');
        });

        $('#generate_report').on('click', function () {
            ChangeTable();
        })
    })
    function ChangeTable() {
        if (window.startDate && window.endDate && $('#commission_id').val()) {
            var Data = {
                sales_id: $('#sales_id').val(),
                commission_id: $('#commission_id').val(),
                from_date: window.startDate,
                to_date: window.endDate,
                type: current_type,
                is_actual:is_actual
            }
            $.ajax({
                url: "HRMAjax/salesCommissionAjax",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    console.log(v1);
                    if (v2 == 'success') {
                        $("#tableWithSearch").DataTable().destroy();
                        $("#tableWithSearch tbody").empty().html(v1.responseJSON['html'])
                        $("#total").text(v1.responseJSON['total'])
                        RebuildDataTable($('.panel-title h4').html(), [], "", {}, '', '')
                    }
                }
            });
        } else {
            toastr.error('<?php echo CommonLanguage::getMessage('Required_Fields'); ?>')
        }
    }
</script>