<?php
include 'Views/Stock/add_damage_items.php';
?>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<style>
    .QuantityVal,.Damaged_Quantity,.Damaged_Reason{
        text-align: center;
        border:none;
        background: #eee;
    }
    .wrong{
        border: 1px solid red !important;
    }
    #tableWithSearch .Hint{
        position: relative;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: -3px;
        right: -144px;
        color: rgb(153, 153, 153);
    }
    .print-only{
        display:none;
    }
    @media print{
        .print-only{
            display:block;
        }
    }
</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 CommonLanguage::getMessage('Depot_Content') ?></div>
            <div id="UpdateStockSuccess" class="alert alert-success hidden"></div>
            <div class="row">
                
                <div class="col-md-2 <?php echo $permissions->hasPermission('Depot') ? '':'hidden'; ?> ">
                    <label><?php echo CommonLanguage::getMessage('Depot') ?></label>
                    <input id="Depot" type="hidden" class="full-width" name="Depot"  >
                </div> 

                <?php if ($is_data_collector) { ?>
                    <div class="  col-md-2 " >
                        <label><?php echo CommonLanguage::getMessage('operation'); ?></label>
                        <select  id="operation"  class="full-width "  data-init-plugin="select2">
                            <option value='0'><?php echo CommonLanguage::getMessage('all') ?></option>
                            <option value='pos'><?php echo CommonLanguage::getMessage('positive') ?></option>
                            <option value='neg'><?php echo CommonLanguage::getMessage('negative') ?></option>
                        </select>
                    </div> 
                <?php } ?>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('Category'); ?></label>
                    <input class=" full-width " id="category_main_filter"  type="hidden" />
                </div>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('supplier'); ?></label>
                    <input type="hidden" id="main_supplier_id" name="main_supplier_id" class="full-width"/>

                </div>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('brand'); ?></label>
                    <input type="hidden" id="brand_id" name="brand_id" class="full-width"/>

                </div>
                <div class="col-md-3 pull-right" >
                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                    <div class="form-group input-group">
                        <input id="Adjust_Date" name="Adjust_Date" class="form-control" value="<?php echo ($today); ?>" />
                        <span class="input-group-addon bg-complete-darker"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('UOM'); ?></label>
                    <select id="uom_filter" class="full-width" data-init-plugin="select2">
                        <option value="1"><?php echo CommonLanguage::getMessage('default_view_uom') ?></option>
                        <option value="2"><?php echo CommonLanguage::getMessage('default_uom') ?></option>
                    </select>

                </div>
            </div>
        </div>
        <div class="panel-body">

            <div class="row">
                <div class="col-md-12">
                    <div class="table-responsive">
                        <table class="table table-bordered stock" id="tableWithSearch" >
                            <thead>
                                <tr>
                                    <th class="text-center" style="width:5%" ><?php print CommonLanguage::getMessage('Code'); ?></th>
                                    <th class="text-center" style="width:5%" ><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('Item'); ?></th>
                                    <th class="text-center" style="width:5%" ><?php print CommonLanguage::getMessage('brand_name'); ?></th>
                                    <th class="text-center" style="width:5%" ><?php print CommonLanguage::getMessage('system_qty'); ?></th>
                                    <th class="text-center" style="width:5%" ><div style="display:flex;"><?php print CommonLanguage::getMessage('real_qty'); ?><input type="number" id="all_inputs" readonly class="form-control m-l-10 no-print" style="width:110px;"/></div></th>
                                    <th class="text-center" style="width:5%" ><?php print CommonLanguage::getMessage('diff'); ?></th>
                                    <?php if ($permissions->hasPermission('show_cost_column_depot_content')) { ?>
                                        <th class="text-center" style="width:5%" ><?php print CommonLanguage::getMessage('cost'); ?></th>
                                        <th class="text-center" style="width:5%" ><?php print CommonLanguage::getMessage('total_costs'); ?></th>
                                    <?php } // if (!$is_data_collector) { ?>
                                    <th class="text-center no-print" style="width:5%" ><?php print CommonLanguage::getMessage('Action'); ?></th>
                                    <?php // } ?>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                        <?php if ($permissions->hasPermission('adjustStock')) { ?>
                            <div class="row form-group">
                                <div class="col-md-6">
                                    <label><?php echo CommonLanguage::getMessage('note') ?></label>
                                    <textarea id="adjust_note" class="form-control" rows="4" style="resize:vertical;"></textarea>
                                </div>
                                <div class="col-md-2 pull-right">
                                    <button class=" btn  btn-cons m-b-10 pull-right hidden" id="AdjustStockSubmitButton" style="color:#fff;background-color:#ed9421 ;padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Adjust_Stock'); ?></span></button>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
<div class="modal fade" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="role-mode" id="add_expiry_modal" aria-hidden="true" >
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label bold text-left"><?php echo CommonLanguage::getMessage('others'); ?></h5>
                <div id="exp_alert" class="hidden"></div>
            </div>
            <form id="expiry_form">
                <div class="modal-body" >
                    <div class="row form-group">
                        <div class="col-md-12">
                            <div class="col-md-3"><label><?php echo CommonLanguage::getMessage('Quantity') ?></label></div>
                            <div class="col-md-3 expiry-main-div"><label><?php echo CommonLanguage::getMessage('Expiry_Date') ?></label></div>
                            <div class="col-md-2 lot-main-div"><label><?php echo CommonLanguage::getMessage('lot') ?></label></div>
                            <div class="col-md-2 serial-main-div"><label><?php echo CommonLanguage::getMessage('serial') ?></label></div>
                            <div class="col-md-2"></div>
                        </div>
                    </div>
                    <div id="exp-rows-div">
                        <div class="row form-group exp-row">
                            <div class="col-md-12 "> 
                                <div  class=" col-md-3 "> 
                                    <input type="number" name="exp-qty"  step="any" min="0"  class="form-control exp-qty " > 
                                </div> 
                                <div class="col-md-3 expiry-main-div">
                                </div>
                                <div class="col-md-2 lot-main-div">
                                    <input type="text" class="form-control lot_nb" />
                                </div>
                                <div class="col-md-2 serial-main-div">
                                    <input type="text" class="form-control serial_nb" />
                                </div>
                                <div  class=" col-md-2 add-exp"> 
                                    <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                    <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
                                </div> 
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal" ><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="submit" style="color:#fff" class="btn bg-complete-darker " id="SubmitExp"><?php print CommonLanguage::getMessage('Save') ?></button>
            </div>
        </div>
    </div>
</div>
<div class="row exp-row-temp form-group  hidden"> 
    <div class="col-md-12 "> 
        <div  class=" col-md-3 "> 
            <input type="number" name="exp-qty"  step="any" min="0"  class="form-control exp-qty " > 
        </div> 
        <div class="col-md-3 expiry-main-div">
        </div>
        <div class="col-md-2 lot-main-div">
<!--            <input type="text" class="form-control lot_nb" />-->
        </div>
        <div class="col-md-2 serial-main-div">
            <!--<input type="text" class="form-control serial_nb" />-->
        </div>
        <div  class=" col-md-2 add-exp"> 
            <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
            <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
        </div> 
    </div>
</div>
<script>
    var Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            adjust_qty_alert = <?php echo json_encode(CommonLanguage::getMessage('adjust_qty_alert')); ?>,
            negative_qty_alert = <?php echo json_encode(CommonLanguage::getMessage('negative_qty_alert')); ?>,
            Damage = <?php echo json_encode(CommonLanguage::getMessage('Damage')); ?>,
            Expiry = <?php echo json_encode(CommonLanguage::getMessage('Expiry')); ?>,
            Notification = <?php echo json_encode(CommonLanguage::getMessage('Notification')); ?>,
            Add_Expiry_Date = <?php echo json_encode(CommonLanguage::getMessage('Add_Expiry_Date')); ?>,
            Add_Damaged_Quantity = <?php echo json_encode(CommonLanguage::getMessage('Add_Damaged_Quantity')); ?>,
            Damage_Reason = <?php echo json_encode(CommonLanguage::getMessage('Damage_Reason')); ?>,
            Action = <?php echo json_encode(CommonLanguage::getMessage('Action')); ?>,
            Sum_of_Quantites = <?php echo json_encode(CommonLanguage::getMessage('Sum_of_Quantites')); ?>,
            title = <?php echo json_encode(CommonLanguage::getMessage('Depot_Content')); ?>,
            is_data_collector = <?php echo json_encode($is_data_collector); ?>,
            file_id = <?php echo json_encode($file_id); ?>,
            negative_sales = <?php echo json_encode(smc_session()['default_setting']['negative_sales']); ?>,
            activate_expiry = <?php echo json_encode(smc_session()['default_setting']['activate_expiry_date']); ?>,
            activate_lot = <?php echo json_encode(smc_session()['default_setting']['activate_product_lot_nb']); ?>,
            activate_serial = <?php echo json_encode(smc_session()['default_setting']['activate_product_serial_nb']); ?>,
            Damaged_Quantity = <?php echo json_encode(CommonLanguage::getMessage('Damaged_Quantity')); ?>,
            is_actual = 0,
            datatable_msg =<?php echo json_encode(isset(smc_session()['datatable_header_temp']['depot_content']) ? smc_session()['datatable_header_temp']['depot_content'] : null) ?>;

    var exp_data = new Array();
    $(function () {        
        build_select2($("#Depot"), "xhr/CommonSearch?col_id=Depot_ID&col_name=Depot_Name&table=tbl_stock_depot_warehouse",1);
        build_select2($("#category_main_filter"), "xhr/catSearch");
        build_select2($("#main_supplier_id"), "xhr/supplierSearch");
        build_select2($("#brand_id"), "xhr/CommonSearch?col_id=brand_id&col_name=brand_name&table=tbl_brand_products");

        build_table();
        $("#category_main_filter,#operation,#main_supplier_id,#brand_id,#uom_filter").on("change", function () {
            build_table();
        });
        $("#Adjust_Date,input.ad-exp-date").datepicker({autoclose: true});
        $("#all_inputs").on("input", function () {
            $(".QuantityVal").val($(this).val()).trigger('keyup')
        })

        $("#exp-rows-div").on("click", " .fa-plus-circle", function (e) {
            $(".AddButtons > .fa-minus-circle").css("display", "")
            var NewItem = $(".exp-row-temp").clone().appendTo($("#exp-rows-div"));
            NewItem.removeClass("exp-row-temp hidden").addClass("exp-row");
            $('.expiry-main-div,.lot-main-div,.serial-main-div', NewItem).empty()
            NewItem.find("input").val('');

            if (NewItem.attr('data-type') == 0) {
                $('.expiry-main-div', NewItem).append('<input class="full-width ad-exp-date"  name="ad-exp-date" type="hidden" required />');
                $('.lot-main-div', NewItem).append('<input class="full-width lot_nb"  name="lot_nb" type="hidden" required />');
                $('.serial-main-div', NewItem).append('<input class="full-width serial_nb"  name="serial_nb" type="hidden" required />');

                build_select2($('.expiry-main-div input.ad-exp-date', NewItem), function () {
                    return 'xhr/get_product_expiry?product_id=' + this.parents('.exp-row').attr('data-product-id') + '&depot=' + $("#Depot").val();
                });
                build_select2($('.lot-main-div input.lot_nb', NewItem), function () {
                    return 'xhr/get_product_lot?product_id=' + this.parents('.exp-row').attr('data-product-id') + '&depot=' + $("#Depot").val();
                });
                build_select2($('.serial-main-div input.serial_nb', NewItem), function () {
                    return 'xhr/get_product_serial?product_id=' + this.parents('.exp-row').attr('data-product-id') + '&depot=' + $("#Depot").val();
                });
            } else {
                $('.expiry-main-div', NewItem).append('<input class="form-control ad-exp-date"  name="ad-exp-date" type="text" required />');
                $('.lot-main-div', NewItem).append('<input class="form-control lot_nb"  name="lot_nb" type="text" required />');
                $('.serial-main-div', NewItem).append('<input class="form-control serial_nb"  name="serial_nb" type="text" required />');

                $(".expiry-main-div input.ad-exp-date", NewItem).datepicker({autoclose: true});
            }

        });
        $("#exp-rows-div").on("click", " .fa-minus-circle", function (e) {
            if ($(".exp-row").length == 1) {
                $(".exp-row input").val("")
            } else {
                $(this).closest(".exp-row").empty().remove();
            }
        })
        $("#SubmitExp").on("click", function () {
            //            var pid=$(this).parents("tr").find("input.QuantityVal").attr("data-id");
            //            var i=0;
            var data_arr = [];
            $(".exp-row").each(function () {
                if ($(this).find("input.exp-qty").val() != ''
                        && ($(this).find("input.ad-exp-date").val() != '' || $(this).find(".expiry-main-div").hasClass("hidden"))) {
                    data_arr.push({
                        qty: $(this).find("input.exp-qty").val(),
                        expiry_date: $(this).find("input.ad-exp-date").val(),
                        lot_nb: $(this).find("input.lot_nb").val(),
                        serial_nb: $(this).find("input.serial_nb").val(),
                    })
                }
            })
            exp_data[Product_ID] = data_arr;
            //            $(this).parents("tr").find("input.QuantityVal").attr("data-exp", JSON.stringify(mydata))
            //            console.log(exp_data)
            $("#add_expiry_modal").modal("hide")
        })
        $("#Depot").on("change", function () {
            $("#all_inputs").val('')
            var DepotID = $(this).val();
            DepotID == 0 ? $("#AdjustStockSubmitButton").addClass('hidden') : $("#AdjustStockSubmitButton").removeClass('hidden');
            if (DepotID == 0) {
                $("#all_inputs").attr("readonly", "readonly")
            } else {
                $("#all_inputs").removeAttr("readonly")
            }
            build_table()
            //            RebuildDataTable(title, [0, 1, 2], 'StockAjax/DepotContentRequest', {Depot_ID: DepotID, cat: $("#category_main_filter").val()});
        })
    })
    $("#tableWithSearch").on("keyup", ".QuantityVal", function () {
        var me = $(this), tr = me.parents("tr"), total_cost = 0, difference = 0;
        difference = (parseFloat(tr.find('td .sys_qty_label').html()) || 0) - (parseFloat(me.val()) || 0);
        total_cost = (parseFloat(difference) || 0) * parseFloat(tr.find('span.cost').attr("data-cost"));

        tr.find("span.total_cost").html(AddCommas(total_cost.toFixed(2)));
        tr.find("td .sys_qty_diff_label").html(AddCommas(difference.toFixed(2)));
    })
    var Parent, Product_ID;
    $("#tableWithSearch").on("click", ".expiry-btn", function () {
        var tr = $(this).parents('tr');
        Product_ID = $(this).attr('data-id'), difference = parseFloat($('td .sys_qty_diff_label', $(this).parents('tr')).html());
        $(".exp-row:gt(0)").empty().remove();
        $('.exp-row:eq(0) .expiry-main-div,.exp-row-temp .expiry-main-div,.exp-row:eq(0) .lot-main-div,.exp-row-temp .lot-main-div,.exp-row:eq(0) .serial-main-div,.exp-row-temp .serial-main-div').empty();
        if (difference == 0) {
            toastr.warning('<?php echo CommonLanguage::getMessage('no_change_difference'); ?>');
            return;
        }

        if (difference < 0) {
            $('.exp-row:eq(0) .expiry-main-div,.exp-row-temp .expiry-main-div').append('<input class="full-width ad-exp-date"  name="ad-exp-date" type="hidden" required />');
            $('.exp-row:eq(0) .lot-main-div,.exp-row-temp .lot-main-div').append('<input class="full-width lot_nb"  name="lot_nb" type="hidden" required />');
            $('.exp-row:eq(0) .serial-main-div,.exp-row-temp .serial-main-div').append('<input class="full-width serial_nb"  name="serial_nb" type="hidden" required />');

            build_select2($('.expiry-main-div input.ad-exp-date'), function () {
                return 'xhr/get_product_expiry?product_id=' + Product_ID + '&depot=' + $("#Depot").val();
            });
            build_select2($('.lot-main-div input.lot_nb'), function () {
                return 'xhr/get_product_lot?product_id=' + Product_ID + '&depot=' + $("#Depot").val();
            });
            build_select2($('.serial-main-div input.serial_nb'), function () {
                return 'xhr/get_product_serial?product_id=' + Product_ID + '&depot=' + $("#Depot").val();
            });
        } else {
            $('.exp-row:eq(0) .expiry-main-div,.exp-row-temp .expiry-main-div').append('<input class="form-control ad-exp-date"  name="ad-exp-date" type="text" required />');
            $('.exp-row:eq(0) .lot-main-div,.exp-row-temp .lot-main-div').append('<input class="form-control lot_nb"  name="lot_nb" type="text" required />');
            $('.exp-row:eq(0) .serial-main-div,.exp-row-temp .serial-main-div').append('<input class="form-control serial_nb"  name="serial_nb" type="text" required />');

            $(".expiry-main-div input.ad-exp-date").datepicker({autoclose: true});
        }
        $('.exp-row:eq(0),.exp-row-temp').attr('data-product-id', Product_ID).attr('data-type', difference < 0 ? 0 : 1)
        $(".exp-row input").val("")
        if (exp_data[Product_ID] != undefined) {
            $("#exp-rows-div").empty();
            for (k = 0; k < exp_data[Product_ID].length; k++) {
                var NewItem = $(".exp-row-temp").clone().appendTo($("#exp-rows-div"));
                NewItem.find(".select2-container").remove();
                NewItem.attr('data-product-id', Product_ID).attr('data-type', difference < 0 ? 0 : 1)
                NewItem.removeClass("exp-row-temp hidden").addClass("exp-row")
                NewItem.find("input.exp-qty").val(exp_data[Product_ID][k]['qty']);
                $(".expiry-main-div input.ad-exp-date", NewItem).val(exp_data[Product_ID][k]['expiry_date']).attr('data-select-name', exp_data[Product_ID][k]['expiry_date']);
                $(".lot-main-div input.lot_nb", NewItem).val(exp_data[Product_ID][k]['lot_nb']).attr('data-select-name', exp_data[Product_ID][k]['lot_nb']);
                $(".serial-main-div input.serial_nb", NewItem).val(exp_data[Product_ID][k]['serial_nb']).attr('data-select-name', exp_data[Product_ID][k]['serial_nb']);
                if (difference < 0) {
                    build_select2($('.expiry-main-div input.ad-exp-date', NewItem), function () {
                        return 'xhr/get_product_expiry?product_id=' + this.parents('.exp-row').attr('data-product-id') + '&depot=' + $("#Depot").val();
                    });
                    build_select2($('.lot-main-div input.lot_nb', NewItem), function () {
                        return 'xhr/get_product_lot?product_id=' + this.parents('.exp-row').attr('data-product-id') + '&depot=' + $("#Depot").val();
                    });
                    build_select2($('.serial-main-div input.serial_nb', NewItem), function () {
                        return 'xhr/get_product_serial?product_id=' + this.parents('.exp-row').attr('data-product-id') + '&depot=' + $("#Depot").val();
                    });
                    $(".select2-container", NewItem).show();
                } else {
                    $(".expiry-main-div input.ad-exp-date", NewItem).datepicker({autoclose: true});
                }
            }
        }
        if (tr.find(".QuantityVal").attr("data-expiry") == 1) {
            $(".expiry-main-div").removeClass('hidden')
        } else {
            $(".expiry-main-div").addClass('hidden')
        }
        if (tr.find(".QuantityVal").attr("data-lot") == 1) {
            $(".lot-main-div").removeClass('hidden')
        } else {
            $(".lot-main-div").addClass('hidden')
        }
        if (tr.find(".QuantityVal").attr("data-serial") == 1) {
            $(".serial-main-div").removeClass('hidden')
        } else {
            $(".serial-main-div").addClass('hidden')
        }
        $("#add_expiry_modal").modal("show")
    })
    $("#tableWithSearch").on("click", ".Damage", function () {
        $(".dep_product").addClass("hidden")
        Product_ID = $(this).attr('data-id');
        var is_expiry = $(this).parents("tr").find(".QuantityVal").attr("data-expiry"),
                is_lot = $(this).parents("tr").find(".QuantityVal").attr("data-lot"),
                is_serial = $(this).parents("tr").find(".QuantityVal").attr("data-serial")
        $("#item_id").val(Product_ID).attr("data-select-name", $(this).parents("tr").find("td:eq(2)").text())
        build_select2($("#item_id"), ("xhr/ProductSearch?Status_ID=1"))
        build_select2($("input.Damaged_UOM"), "xhr/productuomSearch?pid=" + $("#item_id").val())
        $("#depot_id").val($("#Depot").val()).attr("data-select-name", $("#Depot > option:selected").html())
        build_select2($("#depot_id"), "xhr/depotSearch")
        if (is_expiry == 1) {
            $(".expiry-div").removeClass("hidden")
            $(".expiry_date").attr("required", "required")
        } else {
            $(".expiry-div").addClass("hidden")
            $(".expiry_date").removeAttr("required")
        }
        if (is_lot == 1) {
            $(".lot-div").removeClass("hidden")
        } else {
            $(".lot-div").addClass("hidden")
        }
        if (is_serial == 1) {
            $(".serial-div").removeClass("hidden")
        } else {
            $(".serial-div").addClass("hidden")
        }
        //        window.targetTR = $(this).parents("tr");
        //        $("select.Damaged_UOM").html($("#Select_UOM").html()).show().select2()
        //        var units_arr = $(this).parents("tr").find("input.QuantityVal").attr("product-uom").split("/");
        //        $("select.Damaged_UOM > option").each(function () {
        //            if ($.inArray($(this).attr("value"), units_arr) === -1) {
        //                $(this).remove()
        //            }
        //            $("select.Damaged_UOM").show().select2()
        //        })
        $("#add_Damage").modal("show")
    })
    $("#AdjustStockSubmitButton").on("click", function () {
        if (!$('#Adjust_Date').val()) {
            toastr.error('<?php echo CommonLanguage::getMessage('choose_date'); ?>');
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        var validate = true, is_negative = true, expiry_validate = true, lot_validate = true, serial_validate = true;
        var Data = {
            Depot_ID: $("#Depot").val(),
            Adjust_Date: $("#Adjust_Date").val(),
            adjust_note: $("#adjust_note").val(),
            file_id: file_id,
            is_actual: is_actual,
            Products: []
        }
        var row = $("#tableWithSearch").dataTable().fnGetNodes();
        for (var i = 0; i < row.length; i++) {
            var new_qty = parseFloat($(row[i]).find("input.QuantityVal").val()),
                    old_qty = parseFloat($(row[i]).find("input.QuantityVal").attr('data-qty'));
//            console.log(exp_data[pid])
            if (new_qty != old_qty) {

                var pid = $(row[i]).find("input.QuantityVal").attr("data-id");
                Data.Products.push({
                    Product_ID: pid,
                    real_qty: new_qty * parseFloat($(row[i]).find("input.QuantityVal").attr('data-rate')),
                    Quantity: Math.abs(new_qty - old_qty) * parseFloat($(row[i]).find("input.QuantityVal").attr('data-rate')),
                    UOM_ID: $(row[i]).find("input.QuantityVal").attr('data-uom'),
                    Operation: new_qty > old_qty ? '+' : '-',
                    expiry_arr: exp_data[pid]
                })
                var total_qty = 0;
                if ($(row[i]).find("input.QuantityVal").attr('data-expiry') == 1 || $(row[i]).find("input.QuantityVal").attr('data-lot') == 1 || $(row[i]).find("input.QuantityVal").attr('data-serial') == 1) {
                    if (exp_data[pid].expiry_date == undefined && activate_expiry == 1 && $(row[i]).find("input.QuantityVal").attr('data-expiry') == 1) {
                        $("td", $(row[i])).addClass("red-star")
                        expiry_validate = false;
                    } else if (exp_data[pid].lot_nb == undefined && activate_lot == 1 && $(row[i]).find("input.QuantityVal").attr('data-lot') == 1) {
                        $("td", $(row[i])).addClass("red-star")
                        lot_validate = false;
                    } else if (exp_data[pid].serial_nb == undefined && activate_serial == 1 && $(row[i]).find("input.QuantityVal").attr('data-serial') == 1) {
                        $("td", $(row[i])).addClass("red-star")
                        serial_validate = false;
                    } else {
                        for (var j = 0; j < exp_data[pid].length; j++) {
//                            console.log(exp_data[pid].length)
                            total_qty += parseFloat(exp_data[pid][j]['qty']);
                        }
                        if (total_qty != Math.abs(new_qty - old_qty)) {
                            $("td", $(row[i])).addClass("red-star")
                            validate = false;
                        }
                    }
                }
                if (new_qty < 0 && negative_sales == 0) {
                    $("td", $(row[i])).addClass("red-star")
                    is_negative = false;
                }
                //                console.log(total_qty+' == '+Math.abs(new_qty - old_qty))
            }
        }
        if (!expiry_validate) {
            $("#UpdateStockSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_expiry_exist') ?>')
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (!lot_validate) {
            $("#UpdateStockSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_lot_exist') ?>')
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (!serial_validate) {
            $("#UpdateStockSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_serial_exist') ?>')
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (!validate) {
            $("#UpdateStockSuccess").attr("class", "alert alert-danger").html(adjust_qty_alert)
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (!is_negative) {
            $("#UpdateStockSuccess").attr("class", "alert alert-danger").html(negative_qty_alert)
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        $.ajax({
            url: "StockAjax/DepotContentAjax?test=" + Math.random(),
            method: "POST",
            data: Data,
            complete: function (v1, v2) {
                if (v2 == "success") {
                    $("#Depot").trigger("change")
                    exp_data = new Array();
                    $("#UpdateStockSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                    $("#adjust_note").val("")
                } else {
                    $("#UpdateStockSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                }
                $(document.body).animate({scrollTop: 0}, 800)
            }
        });
    });
    function build_table() {
        var depot_name = $('#Depot option:selected').html();
        if (depot_name == 'All') {
            depot_name = '';
        } else {
            depot_name = depot_name;
        }
        //is_data_collector
        var data = {
            Depot_ID: $("#Depot").val(),
            cat: $("#category_main_filter").val(),
            is_data_collector: is_data_collector,
            operation: $("#operation").val(),
            file_id: file_id,
            supplier_id: $("#main_supplier_id").val(),
            uom_filter: $("#uom_filter").val(),
            brand_id: $('#brand_id').val()
        }

        var msg = '';
//                    console.log(CurrentDate.From_Date_invoice+'==='+CurrentDate.To_Date_invoice)
        if (datatable_msg != null) {
            msg = datatable_msg.replace("[[date]]", $("#Adjust_Date").val())
            msg = msg.replace("[[date_class]]", $("#Adjust_Date").val() != '' ? '' : 'hidden')

            if ($("#Depot").val() != '')
                msg = msg.replace("[[depot]]", $("#Depot").select2("data").text)
            msg = msg.replace("[[depot_class]]", $("#Depot").select2("data") != null ? '' : 'hidden')
            if ($("#category_main_filter").val() != '')
                msg = msg.replace("[[category]]", $("#category_main_filter").select2("data").text)
            msg = msg.replace("[[category_class]]", $("#category_main_filter").select2("data") != null ? '' : 'hidden')
            if ($("#brand_id").val() != '')
                msg = msg.replace("[[brand]]", $("#brand_id").select2("data").text)
            msg = msg.replace("[[brand_class]]", $("#brand_id").select2("data") != null ? '' : 'hidden')
            if ($("#main_supplier_id").val() != '')
                msg = msg.replace("[[supplier]]", $("#main_supplier_id").select2("data").text)
            msg = msg.replace("[[supplier_class]]", $("#main_supplier_id").select2("data") != null ? '' : 'hidden')
        }
        var dt_optns = {
            msg:msg,
            cb_ft: function (dt_optns) {
                // stop sorting for column since on click on header checkbox the sorting is triggered
                dt_optns.columnDefs.push({targets: [4], "orderable": false});
            },
        };
        RebuildDataTable(title + '<br/>' + depot_name, [], 'StockAjax/DepotContentRequest', data, '#tableWithSearch', [], dt_optns);
    }
</script>
