<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading ">
            <div class="panel-title">
                <h4 class="bold"><?php echo CommonLanguage::getMessage('item_profit'); ?> </h4>
            </div>
            <input type="hidden" value="<?= !empty($_GET['Invoice_ID_Auto']) ? $_GET['Invoice_ID_Auto'] : "" ?>" id="Invoice_ID_Auto" />
            <div class="row form-group <?= !empty($_GET['Invoice_ID_Auto']) ? "hidden" : "" ?>">
                <div class=" col-md-3">
                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                    <input id="From_To_Date" type="text" class="form-control full-width" name="From_To_Date" autocomplete="off">
                </div>
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('Category') ?></label>
                    <input class=" full-width " id="category_filter" type="hidden" />
                </div>
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('product') ?></label>
                    <input class=" full-width " id="product_filter" type="hidden" />
                </div>
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('choose_customer') ?></label>
                    <input class=" full-width " id="person_filter" type="hidden" />
                </div>
            </div>
            <div class="row form-group">
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('cost_type') ?></label>
                    <select id="cost_type" class="full-width" data-init-plugin="select2">
                        <option value="0"><?php echo CommonLanguage::getMessage('history') ?></option>
                        <option value="1"><?php echo CommonLanguage::getMessage('average') ?></option>
                        <option value="2"><?php echo CommonLanguage::getMessage('last_cost') ?></option>
                    </select>
                </div>
                <div class="col-md-3 <?= !empty($_GET['Invoice_ID_Auto']) ? "hidden" : "" ?>">
                    <label><?php echo CommonLanguage::getMessage('brand') ?></label>
                    <input class=" full-width " id="brand_filter" name="brand_filter" type="hidden" />
                </div>
                <div class="col-md-2 <?= !empty($_GET['Invoice_ID_Auto']) ? "hidden" : "" ?>" style="display:grid;">
                    <label><?php echo CommonLanguage::getMessage('group_by_item') ?></label>
                    <input type="checkbox" id="is_group" name="is_group" />

                </div>
                <div class="col-md-2 <?= !empty($_GET['Invoice_ID_Auto']) ? "hidden" : "" ?>" style="display:grid;">
                    <label><?php echo CommonLanguage::getMessage('zero_price') ?></label>
                    <input type="checkbox" id="zero_price" name="zero_price" />
                </div>
                <div class="col-md-2">
                    <div><label><?php print CommonLanguage::getMessage('return'); ?></label></div>
                    <input type="checkbox" id="with_return" name="with_return" />
                </div>
            </div>
            <div class="row form-group <?php echo $permissions->hasPermission('Branches') ? '':'hidden'; ?>">
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('choose_branch') ?></label>
                    <input id="search_branch_id" type="hidden" class="full-width" name="search_branch_id" >
                </div>

            </div>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12 table-responsive" id="MyTable">
                    <table class="table table-bordered inventory" id="tableWithSearch">
                        <thead>
                            <tr>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('Name'); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('time'); ?></th>
                                <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('quantity'); ?></th>
                                <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('cost'); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('Price'); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('profit'); ?></th>
                                <th class="text-center" style="width:10%">%</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                        <tfoot>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th>
                                <span id='cost'></span>&nbsp;<span><?php echo smc_session()['local_currency_symbol'] ?></span>
                                <br>
                                <span <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?> id='sec_cost'></span>&nbsp;<span <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?>><?php echo smc_session()['second_currency']['symbol'] ?></span>
                            </th>
                            <th><span id='price'></span>&nbsp;<span><?php echo smc_session()['local_currency_symbol'] ?></span>
                                <br>
                                <span <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?> id='sec_price'></span>&nbsp;<span <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?>><?php echo smc_session()['second_currency']['symbol'] ?></span>
                            </th>
                            <th><span id='profit'></span>&nbsp;<span><?php echo smc_session()['local_currency_symbol'] ?></span>
                                <br>
                                <span <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?> id='sec_profit'></span>&nbsp;<span <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?>><?php echo smc_session()['second_currency']['symbol'] ?></span>
                            </th>
                            <th><span id='profit_percent'></span>&nbsp;<span>%</span></th>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var ViewLang = <?php echo json_encode(CommonLanguage::getMessage('view')); ?>;
    var title = <?php echo json_encode(CommonLanguage::getMessage('invoice_per_time')); ?>,
        endDate = '',
        startDate = '',
        datatable_msg = <?php echo json_encode(isset(smc_session()['datatable_header_temp']['item_profit']) ? smc_session()['datatable_header_temp']['item_profit'] : null) ?>;

    var is_actual = <?php echo json_encode($is_actual); ?>;
    $(function() {
        new Switchery($("#is_group").get(0), {
            color: $.Pages.getColor("primary")
        })
        new Switchery($("#zero_price").get(0), {
            color: $.Pages.getColor("primary")
        })
        new Switchery($("#with_return").get(0), {
            color: $.Pages.getColor("primary")
        });

        build_select2($("#brand_filter"), "xhr/CommonSearch?col_id=brand_id&col_name=brand_name&table=tbl_brand_products")
        build_select2($("#search_branch_id"), "xhr/CommonSearch?col_name=branch_name&col_id=branch_id&table=tbl_organization_branches");

        build_select2($("#category_filter"), "xhr/catSearch", 1)
        build_select2($("#product_filter"), "xhr/productSearch")
        build_select2($("#person_filter"), "xhr/customerSearch")
        //        $("input[name=From_To_Date]").daterangepicker({
        //        }, function (start, end, label) {
        //            window.startDate = start.format("YYYY-MM-DD"),
        //                    window.endDate = end.format("YYYY-MM-DD")
        //        });

        $("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
        });

        $("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'));
            ChangeTable();
        });
        $("input[name=From_To_Date]").on('cancel.daterangepicker', function(ev, picker) {
            window.startDate = ''
            window.endDate = ''
            $(this).val('');
            ChangeTable();
        });


        ChangeTable();
        $("#with_return,#category_filter,#product_filter,#is_group,#cost_type,#person_filter,#brand_filter,#zero_price,#search_branch_id").on("change", function() {
            ChangeTable();
        });
    });

    function ChangeTable() {
        var CurrentDate = {
            with_return: $("#with_return").is(":checked") ? 1 : 0,
            Date: $("input[name=From_To_Date]").val(),
            from_date: window.startDate,
            to_date: window.endDate,
            cat_id: $("#category_filter").val(),
            product_id: $("#product_filter").val(),
            person_id: $("#person_filter").val(),
            is_actual: is_actual,
            is_group: $("#is_group").is(":checked") ? 1 : 0,
            cost_type: $("#cost_type").val(),
            brand_id: $("#brand_filter").val(),
            zero_price: $("#zero_price").is(":checked") ? 1 : 0,
            Invoice_ID_Auto: $('#Invoice_ID_Auto').val(),
            search_branch_id: $('#search_branch_id').val()
        };
        $.ajax({
            url: 'InventoryAjax/itemProfitReportRequest',
            data: CurrentDate,
            dataType: 'JSON',
            complete: function(v1, v2) {
                console.log('v1')
                console.log(v1)
                var Data = v1.responseJSON;

                var msg = '';
                if (datatable_msg != null) {
                    msg = datatable_msg.replace("[[from_date]]", window.startDate)
                    msg = msg.replace("[[to_date]]", window.endDate)
                    msg = msg.replace("[[date_class]]", window.endDate != '' && window.startDate != '' ? '' : 'hidden')
                    var cat_text = '';
                    if ($("#category_filter").val() != '' && $("#category_filter").select2('data') != null) {
                        $.each($("#category_filter").select2('data'), function(key, val) {
                            cat_text += ((cat_text == '' ? '' : ', ') + val['text']);
                        })
                    }
                    msg = msg.replace("[[category]]", cat_text)
                    msg = msg.replace("[[category_class]]", cat_text != '' ? '' : 'hidden')
                    if ($("#product_filter").val() != '')
                        msg = msg.replace("[[product]]", $("#product_filter").select2("data").text)
                    msg = msg.replace("[[product_class]]", $("#product_filter").select2("data") != null ? '' : 'hidden')
                    if ($("#person_filter").val() != '')
                        msg = msg.replace("[[customer]]", $("#person_filter").select2("data").text)
                    msg = msg.replace("[[customer_class]]", $("#person_filter").select2("data") != null ? '' : 'hidden')
                    if ($("#brand_filter").val() != '')
                        msg = msg.replace("[[brand]]", $("#brand_filter").select2("data").text)
                    msg = msg.replace("[[brand_class]]", $("#brand_filter").select2("data") != null ? '' : 'hidden')

                }
                //                            console.log(Data)
                RebuildDataTable(title, [0, 1, 2, 3, 4, 5, 6], "InventoryAjax/ItemProfitReportAjax", CurrentDate, '', [], {
                    msg: msg,
                    initComplete: function(settings, json) {
                        //                            console.log(data)
                        $("#cost").html(AddCommas(public_round_number(parseFloat(Data['total_cost']))));
                        $("#sec_cost").html(AddCommas(public_round_number(parseFloat(Data['second_total_cost']))));
                        $("#price").html(AddCommas(public_round_number(parseFloat(Data['total_price']))));
                        $("#sec_price").html(AddCommas(public_round_number(parseFloat(Data['second_total_price']))));
                        $("#profit").html(AddCommas(public_round_number(parseFloat(Data['profit']))));
                        $("#sec_profit").html(AddCommas(public_round_number(parseFloat(Data['second_profit']))));
                        $("#profit_percent").html(AddCommas(public_round_number(parseFloat(Data['profit_percent']))));
                    }
                });
            }
        });
    }
</script>