<div class="modal fade" data-backdrop="static" id="assignProductLocation" tabindex="-1" role="dialog" aria-hidden="true" >
    <div class="modal-dialog " style="width:90%;">
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label bold"><?php echo CommonLanguage::getMessage('Assign_Product_Location'); ?></h5>
            </div>
            <div class="modal-body" id="AddForm">
                <div id="LocationValidationAlert" class="WizardValidationAlert alert"></div>
                <form id="AssignProductLocationPostForm" method="POST" onsubmit="return false">
                    <div class="row">
                        <div class="col-md-12 form-group">
                            <div class="col-md-4">
                                <label><?php print CommonLanguage::getMessage('Category'); ?></label>
                                <div class="input-group m-b "><span class="input-group-btn">
                                        <button type="button" class="btn btn-bg-complete-darker"><i class="fa fa-certificate"></i> </button> </span>
                                    <input class=" full-width " id="category_filter"  type="hidden" />
                                </div>
                            </div>
                            <div class="col-md-8">
                                <label><?php print CommonLanguage::getMessage('Product'); ?></label>
                                <span class='red-star'>*</span>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1" style="color:#4c0870;cursor:pointer"></span>
                                <div class="input-group m-b Product_Code"><span class="input-group-btn">
                                        <button type="button" class="btn btn-bg-complete-darker"><i class="fa fa-certificate"></i> </button> </span>
                                    <input class=" full-width Product_Code" id="Product_Code" name="Product_Code" type="hidden" />
                                </div>
                            </div>
                        </div>
                        <div class="col-md-12 form-group">
                            <label><?php echo CommonLanguage::getMessage('trans_note') ?></label>
                            <textarea id="trans_note" class="form-control" rows="4" style="resize:vertical;"></textarea>

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 form-group">
                            <div class="col-md-1">
                                <label><?php print CommonLanguage::getMessage('Quantity'); ?></label>
                                <span class='red-star'>*</span>
                            </div>
                            <div class="col-md-1">
                                <label><?php print CommonLanguage::getMessage('UOM'); ?></label>
                                <span class='red-star'>*</span>
                            </div>
                            <div class="col-md-2 expiry-td <?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?>">
                                <label><?php print CommonLanguage::getMessage('Expiry_Date'); ?></label>
                                <span class="red-star  ">*</span>
                            </div>
                            <div class="col-md-1 lot-td <?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 0 ? 'hidden' : ''; ?>">
                                <label><?php print CommonLanguage::getMessage('lot'); ?></label>
                            </div>
                            <div class="col-md-1 serial-td <?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 0 ? 'hidden' : ''; ?>">
                                <label><?php print CommonLanguage::getMessage('serial'); ?></label>
                            </div>
                            <div class="col-md-1">
                                <label><?php print CommonLanguage::getMessage('Cost'); ?></label>
                            </div>
                            <div class="col-md-2">
                                <label><?php print CommonLanguage::getMessage('Currency'); ?></label>
                            </div>
                            <div class="col-md-2">
                                <label><?php print CommonLanguage::getMessage('Depot'); ?>
                                    <span class='red-star'>*</span>
                                </label>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#4c0870;cursor:pointer"></span>
                            </div>
                        </div>
                        <div class="col-md-12 add-row AddRow m-t-10">
                            <div class="col-md-1">
                                <input required type="text" min='0' class="form-control Product_Quantity_Val digits" >
                            </div>
                            <div class="col-md-1">
                                <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                    <?php foreach ($all_uom as $uom): ?>
                                        <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2 expiry-td <?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?>">
                                <input type="text"  class="form-control expiry_date " >
                            </div>
                            <div class="col-md-1 lot-td <?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 0 ? 'hidden' : ''; ?>">
                                <input type="text"  class="form-control lot_nb " >
                            </div>
                            <div class="col-md-1 serial-td <?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 0 ? 'hidden' : ''; ?>">
                                <input type="text"  class="form-control serial_nb " >
                            </div>
                            <div class="col-md-1">
                                <input type="text"  class="form-control Product_Product_Cost digits" >
                            </div>
                            <div class="col-md-2">
                                <?php echo Forms::CurrencyDropDown(1, 'bg-complete-darker', 1); ?>
                            </div>
                            <div class="col-md-2">
                                <input required class=" full-width Product_Depot_Loc" id="Product_Depot_Loc" name="Product_Depot_Loc" type="hidden" value="<?php echo smc_session()['default_depot_id'] ?>" data-select-name='<?= json_encode(smc_session()['default_depot_name']) ?>'/>
                            </div>
                            <div class="col-md-1 ExpiryDate">
                                <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;display:none"></span>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" id="CloseProductLocation" data-dismiss="modal"  > <?php print CommonLanguage::getMessage('Close'); ?> </button>
                <button class="btn btn-bg-complete-darker " id="SubmitProductLocation"  > <?php print CommonLanguage::getMessage('Save'); ?>   </button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    var Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>;
    //	var sum = 0,TotalQuantity=0;
    var TotalQty = 0;
    var default_depot_id = <?php echo json_encode(smc_session()['default_depot_id']); ?>,
            default_depot_name = <?php echo json_encode(smc_session()['default_depot_name']); ?>;
    $(function () {
        build_select2($("#category_filter"), "xhr/catSearch")
        build_select2($("#Product_Code"), ("xhr/ProductSearch?cat=" + $("#category_filter").val() + '&Status_ID=1&is_not_service=1'))
        build_select2($("#Product_Depot_Loc"), ("xhr/depotSearch"))
        $(".expiry_date").datepicker({autoclose: true});
        $("#category_filter").on("change", function () {
            $("#Product_Code").val("").attr("data-select-name", "")
            build_select2($("#Product_Code"), ("xhr/ProductSearch?cat=" + $("#category_filter").val() + '&Status_ID=1&is_not_service=1'))
        })
        $("#AddForm").on("click", ".ExpiryDate > .fa-plus-circle", function (e) {
            $(".ExpiryDate > .fa-minus-circle").css("display", "")
            var Parent = $(this).parents(".AddRow"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".Product_Quantity_Val,.Product_Product_Cost,.lot_nb,.serial_nb").val('');
            $(".select2-container", NewItem).empty().remove();
            $(".UOM_ID", NewItem).show().select2();
            NewItem.find("input[name=Currency_ID]").val('');
            $("div.DropDownForForms button > span", NewItem).html('<?php echo CommonLanguage::getMessage('Select_Currency'); ?>');
            NewItem.find(".Product_Depot_Loc").show();
            NewItem.find(".Product_Depot_Loc").attr('data-select-name', '').val('')
            build_select2(NewItem.find(".Product_Depot_Loc"), 'xhr/depotSearch');
            NewItem.find("input.expiry_date").val("").datepicker({autoclose: true});
        })
        $("#AddForm").on("click", ".ExpiryDate > .fa-minus-circle", function (e) {
            $(this).closest(".AddRow").empty().remove();
            $("#AddForm").each(function () {
                $(".ExpiryDate > .fa-minus-circle", $(this).parent()).css({"display": $(".ExpiryDate", $(this).parent()).length <= 1 ? "none" : "inline-block"})
            })
        })
        $("#Product_Code").on("change", function () {
            var Type = $(this).data("TypeListTarget"),
                    Catolder = $("#s2id_" + $(this).attr("id"));
            $("#s2id_Product_Code").append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'><img style='height:25px;margin-top:5px;' src='img/demo/progress.svg' /></div>")
            Catolder.append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'></div>")
            $.ajax({
                url: "StockAjax/getProductUOM",
                dataType: "json",
                data: {pid: $(this).val()},
                complete: function (v, vv) {
                    if (vv == "success") {
                        //console.log($(".AddRow"))
                        var ToBeAdded = "";
                        for (var x = 0; x < v.responseJSON.length; x++) {
                            $("#Product_Code").attr("data-expiry", v.responseJSON[x]['is_expiry'])
                            if (v.responseJSON[x]['is_expiry'] == 0) {
                                $(".expiry-td").addClass("hidden")
                            } else {
                                $(".expiry-td").removeClass("hidden")
                            }
                            if (v.responseJSON[x]['is_lot'] == 0) {
                                $(".lot-td").addClass("hidden")
                            } else {
                                $(".lot-td").removeClass("hidden")
                            }
                            if (v.responseJSON[x]['is_serial'] == 0) {
                                $(".serial-td").addClass("hidden")
                            } else {
                                $(".serial-td").removeClass("hidden")
                            }
                            ToBeAdded += "<option value='" + v.responseJSON[x]["uom_from"] + "'>" + v.responseJSON[x]["from_name"] + "</option>"
                        }
                        $(".AddRow").each(function () {
                            $(this).find("select[name=UOM_ID]").select2("destroy").empty()
                            $(this).find("select[name=UOM_ID]").html(ToBeAdded).select2();
                        })
                        $(">.LoadingCities", Catolder).remove()
                    }
                }
            })
        }).data("MyModuleListTarget", "#Module_ID").trigger("change")
        //        $(".Product_Expiry_Date").datepicker({autoclose:true})
        $("#SubmitProductLocation").on("click", function () {
            //            $("#AssignProductLocationPostForm").validate();
            //            if ($("#AssignProductLocationPostForm").valid()) {
            var is_valid = true;
            $("#LocationIsBusy").remove();
            $("#assignProductLocation").append('<div id="LocationIsBusy" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:9999;opacity:0"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>');
            $("#LocationIsBusy").animate({opacity: 1});
            var Data = {
                Product_Code: $("#Product_Code").val(),
                Product_ID: $("#Product_Code").val(),
                trans_note: $("#trans_note").val(),
                Category_ID: 0,
                Transaction_Type_ID: 10,
                Products: []
            }
            if (Data.Product_ID == '')
                is_valid = false;
            else {
                $(".AddRow").each(function () {
                    var me = $(this);
                    var RowData = {
                        Item_Quantity: me.find('.Product_Quantity_Val').val(),
                        Item_Cost: me.find(".Product_Product_Cost").val(),
                        UOM_ID: me.find("select.UOM_ID").val(),
                        Depot_ID: me.find("input.Product_Depot_Loc").val(),
                        Currency_ID: me.find(".DropDownForForms button input").val(),
                        expiry_date: me.find("input.expiry_date").val(),
                        lot_nb: me.find("input.lot_nb").val(),
                        serial_nb: me.find("input.serial_nb").val(),
                        Product_ID: $("#Product_Code").val()
                    };
                    if (RowData.Item_Quantity <= 0 || RowData.UOM_ID == '' || RowData.Depot_ID == '' || RowData.Currency_ID == '') {
                        is_valid = false;
                        return false;
                    }
                    if ($("#Product_Code").attr("data-expiry") == 1 && me.find("input.expiry_date").val() == '') {
                        is_valid = false;
                        return false;
                    }
                    Data.Products.push(RowData);
                });
            }
            if (!is_valid) {
                $("#LocationIsBusy").remove();
                $("#LocationValidationAlert").attr("class", "alert alert-danger").empty().html("<span>" + Required_Fields + "</span>");
                return false;
            }
            $.ajax({
                url: "StockAjax/assignProductLocationAjax",
                method: "POST",
                data: Data,
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        $("#LocationIsBusy").remove();
                        RebuildDataTable(title, [0, 1, 2], 'StockAjax/ProductLocationListRequest', {cat: $("#category_main_filter").val()});
                        $("#LocationValidationAlert").attr("class", "alert alert-success").empty().html("<span>" + Submitted_Successfully + "</span>");
                        setTimeout(function () {
                            $("#assignProductLocation").modal('hide')
                            $("input[name=Currency_ID]").val('');
                            $("div.DropDownForForms button > span").html('<?php echo CommonLanguage::getMessage('Select_Currency'); ?>');
                            $("#LocationValidationAlert").hide()
                        }, 1500)
                    } else {
                        $("#LocationValidationAlert").attr("class", "alert alert-danger").empty().html("<span>" + Failed_Submit + "</span>");
                    }
                    $("#LocationIsBusy").remove();
                }
            });
        });
        $("#assignProductLocation").on("shown.bs.modal", function () {
            $("#assignProductLocation input:not([name=Currency_ID])").val('');
            $("#Product_Depot_Loc").val(default_depot_id)
            $("#Product_Depot_Loc").attr("data-select-name", default_depot_name)
            build_select2($("#Product_Depot_Loc"), ("xhr/depotSearch"))
        });
    });
</script>
