<style>
    .bg-gray{
        background-color: #e5e5e5 !important;
    }
</style>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"><?php print $title ?></div>
            <form  target="_blank" action="Inventory/view_category_trial_balance" method="post" >
                <input type="hidden" name="is_actual" value="<?php echo $is_actual ? 1 : 0; ?>"/>
                <input type="hidden" name="is_sales" value="<?php echo $is_sales ? 1 : 0; ?>"/>
                <div class="row form-group">
                    <div class="col-md-2 <?= $is_disc ? 'hidden' : ''; ?>" ><!-- dcafe don't want to show his users in discounted report-->
                        <label><?php echo CommonLanguage::getMessage('users'); ?></label>
                        <input type="hidden" class="full-width" name="users" multiple id="users"/>
                    </div>
                    <div class=" col-md-3 input-daterange" id="datepicker-range-invoice">
                        <label><?php print CommonLanguage::getMessage('range_date_invoice'); ?></label>
                        <input id="From_To_Date" type="text" autocomplete="off" class="form-control" name="From_To_Date" required >
                    </div>
                    <div class=" col-md-3 input-daterange" id="datepicker-range">
                        <label><?php print CommonLanguage::getMessage('range_date_created'); ?></label>
                        <input id="created_date" type="text" autocomplete="off" class="form-control" name="created_date" >
                    </div>

                    <div class=" col-md-2 <?php echo $is_sales ? '' : 'hidden' ?>" <?php echo $is_sales ? 'style="display:grid"' : '' ?>>
                        <label><?php print CommonLanguage::getMessage('based_end_day'); ?></label>
                        <input id="is_end_day" type="checkbox"  name="is_end_day" >
                    </div>
                    <div class=" col-md-2">
                        <label><?php print CommonLanguage::getMessage($is_sales ? 'choose_customer' : 'choose_supplier'); ?></label>
                        <input id="customer_id" type="hidden"  class="full-width" name="customer_id" >
                    </div>
                    <?php if ($is_disc) { ?>
                        <div class="col-md-2  m-t-25">
                            <button type="submit" class="btn btn-primary pull-right" name='per_day' ><?php echo CommonLanguage::getMessage('print_per_days'); ?></button>
                        </div>
                    <?php } ?>
                </div>
                <div class="row form-group">
                    <div class=" col-md-2 <?php echo $permissions->hasPermission('Branches') ? '':'hidden'; ?>">
                        <label><?php print CommonLanguage::getMessage('branch'); ?></label>
                        <input id="branch_id" name="branch_id" type="hidden"  class="full-width"    >
                    </div>
                    <div class=" col-md-2 <?php echo!$is_sales ? 'hidden' : '' ?>">
                        <label><?php print CommonLanguage::getMessage('salesman'); ?></label>
                        <input type="hidden" name="sales_man_id" id="sales_man_id" class="full-width"/>
                    </div>
                    <div class="col-md-3 " >
                        <label><?php echo CommonLanguage::getMessage('type') ?></label>
                        <select id="type" name="type" class="full-width" data-init-plugin="select2">
                            <option value="0"><?php echo CommonLanguage::getMessage('All') ?></option>
                            <option value="1"><?php echo CommonLanguage::getMessage('only_cat') ?></option>
                            <option value="2"><?php echo CommonLanguage::getMessage('only_products') ?></option>
                        </select>
                    </div>
                    <div class="col-md-3 " >
                        <label><?php echo CommonLanguage::getMessage($is_sales ? 'customer_group' : 'supplier_group') ?></label>
                        <input type="hidden" name="group_id" id="group_id" class="full-width"/>

                    </div>
                    <div class="col-md-2 " style="    margin-top: 24px;">
                        <button id="Generate_Report" type="button" class="btn btn-primary pull-right" data-toggle="dropdown" aria-expanded="false">
                            <?php print CommonLanguage::getMessage('generate_report'); ?></button>
                    </div>
                </div>
            </form>
        </div>
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table  inventory" id="tableWithSearch">
                    <thead>
                        <tr>
                            <th class="text-left"><?php print CommonLanguage::getMessage('Name') ?></th>
                            <th class="text-left"><?php print CommonLanguage::getMessage('quantity') ?></th>
                            <th class="text-center"><?php print CommonLanguage::getMessage('total') . ' (' . smc_session()['local_currency_symbol'] . ')' ?></th>
                            <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('vat') . ' (' . smc_session()['local_currency_symbol'] . ')'; ?></th>
                            <?php if (smc_session()['default_setting']['activate_second_vat'] == 1) { ?>
                                <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('vat2_amount') . ' (' . smc_session()['local_currency_symbol'] . ')'; ?></th>
                            <?php } ?>
                            <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('total_amount') . ' (' . smc_session()['local_currency_symbol'] . ')'; ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                    <tfoot>
                    <th colspan="2"></th>
                    <th><strong id="total">0</strong>&nbsp;<strong><?php echo smc_session()['local_currency_symbol'] ?></strong></th>
                    <th><strong id="total_vat1">0</strong>&nbsp;<strong><?php echo smc_session()['local_currency_symbol'] ?></strong></th>
                    <?php if (smc_session()['default_setting']['activate_second_vat'] == 1) { ?>
                        <th><strong id="total_vat2">0</strong>&nbsp;<strong><?php echo smc_session()['local_currency_symbol'] ?></strong></th>
                    <?php } ?>
                    <th><strong id="total_amount">0</strong>&nbsp;<strong><?php echo smc_session()['local_currency_symbol'] ?></strong></th>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>
<script>
    var title = <?php echo json_encode($title); ?>;
    var is_actual = <?php echo $is_actual ? 1 : 0; ?>,
            is_disc = <?php echo $is_disc ? 1 : 0; ?>,
            is_sales = <?php echo $is_sales ? 1 : 0; ?>;
    var default_start_time = <?php echo json_encode(smc_session()['default_setting']['default_start_time']); ?>,
            datatable_msg =<?php echo json_encode(isset(smc_session()['datatable_header_temp']['sales_per_category']) ? smc_session()['datatable_header_temp']['sales_per_category'] : null) ?>;

    $(function () {
        var default_end_time = subtractFromTime(default_start_time, 1, 'seconds');
        build_select2($("#users"), "xhr/CommonSearch?col_id=User_ID&col_name=User_Name&table=tbl_common_users", 1);
        build_select2($("#customer_id"), is_sales ? "xhr/customerSearch" : "xhr/supplierSearch");
        build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches");
        build_select2($('#sales_man_id'), 'xhr/employeeSearch');
        build_select2($("#group_id"), "xhr/general_group_Search?group_type=" + (is_sales ? 'cust' : 'supp'));

        ChangeTable();
        $("input[name=From_To_Date]").daterangepicker({
            //            locale: {
            //                format: 'YYYY-MM-DD'
            //            },
            //            startDate: moment(moment().format('YYYY-MM-DD')),
            //            endDate: moment(moment().add(1, 'days').format('YYYY-MM-DD')),
            ranges: {
                'Today': [moment(moment(new Date().getTime()).format('YYYY-MM-DD')),
                    moment(moment(new Date().getTime()).format('YYYY-MM-DD'))],
                'Yesterday': [moment(moment().subtract(1, 'days').format('YYYY-MM-DD')),
                    moment(moment().subtract(1, 'days').format('YYYY-MM-DD'))],
                'Last 7 Days': [moment(moment().subtract(6, 'days').format('YYYY-MM-DD')),
                    moment(moment(new Date().getTime()).format('YYYY-MM-DD'))],
                'Last 30 Days': [moment(moment().subtract(29, 'days').format('YYYY-MM-DD')),
                    moment(moment(new Date().getTime()).format('YYYY-MM-DD'))],
                'This Month': [moment(moment().startOf('month').format('YYYY-MM-DD')),
                    moment(moment().endOf('month').format('YYYY-MM-DD'))],
                'Last Month': [moment(moment().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')),
                    moment(moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD'))]
            }, allowEmpty: true,
            //            autoApply: true,
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        }, function (start, end, label) {
            //            window.startDate = start.format("YYYY-MM-DD"),
            //                    window.endDate = end.format("YYYY-MM-DD")
            //            ChangeTable()
        });
        $('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) {
            startDate = ''
            endDate = ''
            $(this).val('');

        });
        $("input[name=created_date]").daterangepicker({
            timePicker: true,
            locale: {
                format: 'YYYY-MM-DD HH:mm:ss',
//                  cancelLabel: 'Clear'
            },
            startDate: moment(moment().format('YYYY-MM-DD') + ' ' + default_start_time),
            endDate: moment(moment().add(1, 'days').format('YYYY-MM-DD') + ' ' + default_end_time),
            ranges: {
                'Today': [moment(moment(new Date().getTime()).format('YYYY-MM-DD') + ' ' + default_start_time),
                    moment(moment().add(1, 'days').format('YYYY-MM-DD') + ' ' + default_end_time)],
                'Yesterday': [moment(moment().subtract(1, 'days').format('YYYY-MM-DD') + ' ' + default_start_time),
                    moment(moment(new Date().getTime()).format('YYYY-MM-DD') + ' ' + default_end_time)],
                'Last 7 Days': [moment(moment().subtract(6, 'days').format('YYYY-MM-DD') + ' ' + default_start_time),
                    moment(moment(new Date().getTime()).format('YYYY-MM-DD') + ' ' + default_end_time)],
                'Last 30 Days': [moment(moment().subtract(29, 'days').format('YYYY-MM-DD') + ' ' + default_start_time),
                    moment(moment(new Date().getTime()).format('YYYY-MM-DD') + ' ' + default_end_time)],
                'This Month': [moment(moment().startOf('month').format('YYYY-MM-DD') + ' ' + default_start_time),
                    moment(moment().endOf('month').format('YYYY-MM-DD') + ' ' + default_end_time)],
                'Last Month': [moment(moment().subtract(1, 'month').startOf('month').format('YYYY-MM-DD') + ' ' + default_start_time),
                    moment(moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD') + ' ' + default_end_time)]
            },
//            allowEmpty: true,
            //            autoApply: true,
//            autoUpdateInput: false,
        },
                function (start, end, label) {
                    window.startDate = start.format("YYYY-MM-DD HH:mm:ss"),
                            window.endDate = end.format("YYYY-MM-DD HH:mm:ss")
                });
//        $("input[name=created_date]").daterangepicker({
//            timePicker: true,
//            locale: {
//                format: 'YYYY-MM-DD HH:mm:ss',
//                  cancelLabel: 'Clear'
//            },
//            //            locale: {
//            //                format: 'YYYY-MM-DD'
//            //            },
//            //            startDate: moment(moment().format('YYYY-MM-DD')),
//            //            endDate: moment(moment().add(1, 'days').format('YYYY-MM-DD')),
//            ranges: {
//                'Today': [moment(moment(new Date().getTime()).format('YYYY-MM-DD')),
//                    moment(moment(new Date().getTime()).format('YYYY-MM-DD'))],
//                'Yesterday': [moment(moment().subtract(1, 'days').format('YYYY-MM-DD')),
//                    moment(moment().subtract(1, 'days').format('YYYY-MM-DD'))],
//                'Last 7 Days': [moment(moment().subtract(6, 'days').format('YYYY-MM-DD')),
//                    moment(moment(new Date().getTime()).format('YYYY-MM-DD'))],
//                'Last 30 Days': [moment(moment().subtract(29, 'days').format('YYYY-MM-DD')),
//                    moment(moment(new Date().getTime()).format('YYYY-MM-DD'))],
//                'This Month': [moment(moment().startOf('month').format('YYYY-MM-DD')),
//                    moment(moment().endOf('month').format('YYYY-MM-DD'))],
//                'Last Month': [moment(moment().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')),
//                    moment(moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD'))]
//            }, allowEmpty: true,
//            //            autoApply: true,
//            autoUpdateInput: false,
////            locale: {
////                cancelLabel: 'Clear'
////            }
//        }, function (start, end, label) {
//            //            window.start_created = start.format("YYYY-MM-DD"),
//            //                    window.end_created = end.format("YYYY-MM-DD")
//            //            ChangeTable()
//        });
//        $('input[name="created_date"]').on('apply.daterangepicker', function (ev, picker) {
//            window.start_created = picker.startDate.format('YYYY-MM-DD'),
//                    window.end_created = picker.endDate.format('YYYY-MM-DD');
//            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
//
//        });
//        $('input[name="created_date"]').on('cancel.daterangepicker', function (ev, picker) {
//            window.end_created = ''
//            window.start_created = ''
//            $(this).val('');
//
//        });

        $("#Generate_Report").on("click", function () {
            ChangeTable()
        })
    });
    function ChangeTable() {
        var data = {
            From_Date: window.startDate ? window.startDate : '',
            To_Date: window.endDate ? window.endDate : '',
            date_created_from: window.start_created ? window.start_created : '',
            date_created_to: window.end_created ? window.end_created : '',
            customer_id: $("#customer_id").val(),
            users: $("#users").val(),
            is_actual: is_actual,
            branch_id: $("#branch_id").val(),
            sales_man_id: $("#sales_man_id").val(),
            group_id: $("#group_id").val(),
            type: $("#type").val(),
            is_end_day: $("#is_end_day").is(":checked") ? 1 : 0,
            is_sales: is_sales,
            is_disc: is_disc
        };
        $.ajax({
            url: "InventoryAjax/category_trial_balance",
            data: data,
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == 'success') {
                    $("#tableWithSearch").DataTable().destroy();
                    $("#tableWithSearch tbody").empty().html(v1.responseJSON['html'])

                    var totals = v1.responseJSON['totals'];
                    $("#total").text(AddCommas(public_round_number(totals['total'])))
                    $("#total_vat1").text(AddCommas(public_round_number(totals['total_vat'])))
                    $("#total_vat2").text(AddCommas(public_round_number(totals['total_vat2'])))
                    $("#total_amount").text(AddCommas(public_round_number(totals['total_amount'])))
                    var msg = '';
//                    console.log(CurrentDate.From_Date_invoice+'==='+CurrentDate.To_Date_invoice)
                    if (datatable_msg != null) {
                        msg = datatable_msg.replace("[[from_date]]", data.From_Date)
                        msg = msg.replace("[[to_date]]", data.To_Date)
                        msg = msg.replace("[[date_class]]", data.From_Date != '' && data.To_Date != '' ? '' : 'hidden')


                        var users_text = '';
                        if ($("#users").val() != '' && $("#users").select2('data') != null) {
                            $.each($("#users").select2('data'), function (key, val) {
                                users_text += ((users_text == '' ? '' : ', ') + val['text']);
                            })
                        }
                        msg = msg.replace("[[users]]", users_text)
                        msg = msg.replace("[[users_class]]", users_text != '' ? '' : 'hidden')

                        if ($("#customer_id").val() != '')
                            msg = msg.replace("[[customer]]", $("#customer_id").select2("data").text)
                        msg = msg.replace("[[customer_class]]", $("#customer_id").select2("data") != null ? '' : 'hidden')
                        if ($("#branch_id").val() != '')
                            msg = msg.replace("[[branch]]", $("#branch_id").select2("data").text)
                        msg = msg.replace("[[branch_class]]", $("#branch_id").select2("data") != null ? '' : 'hidden')
                        if ($("#sales_man_id").val() != '')
                            msg = msg.replace("[[salesman]]", $("#sales_man_id").select2("data").text)
                        msg = msg.replace("[[salesman_class]]", $("#sales_man_id").select2("data") != null ? '' : 'hidden')
                        if ($("#group_id").val() != '')
                            msg = msg.replace("[[customer_group]]", $("#group_id").select2("data").text)
                        msg = msg.replace("[[customer_group_class]]", $("#group_id").select2("data") != null ? '' : 'hidden')
                    }
                    RebuildDataTable(title, [], "", {}, '', '',{msg:msg})
                }
            }
        });
    }
</script>