<script src="<?php echo THEME_PATH ?>js/jquery-barcode.js"></script>
<script src="<?php echo THEME_PATH ?>js/jQuery.print.js"></script>
<div id="Barcode" ></div>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div id="barcodealert"></div>
            <div class="panel-title"> <?php print CommonLanguage::getMessage('print_barcodes'); ?></div>
        </div>
        <div class="panel-body">
            <div class="row m-b-20 form-group">
                <div class="col-md-2 hidden">
                    <label><?php print CommonLanguage::getMessage('Name'); ?></label>
                    <select  id="Name"  class="full-width  " data-init-plugin="select2">
                        <option value="" disabled selected></option>
                        <option value="Beauty House">Beauty House</option>
                        <option value="G.A">G.A</option>
                        <option value="Robenson">Robenson</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('pricing_class'); ?></label>
                    <input  name="Select_Class" id="Select_Class" type="hidden" class="full-width"/>
                </div>
                <div class="col-md-2">      
                    <label><?php print CommonLanguage::getMessage('paper_size'); ?></label> 
                    <select required id = "paper_size" name="paper_size"  class="full-width paper_size " data-init-plugin="select2">
                        <?php foreach ($printer_size as $size): ?>
                            <option value="<?php echo $size['paper_size']; ?>" data-height="<?php echo $size['height_cm']; ?>" data-width="<?php echo $size['width_cm']; ?>"><?php echo $size['paper_size']; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('nb_copies'); ?></label> 
                    <input type="number" min="1" value="1" id="print_count" class="form-control  ">
                </div>
                <div class="col-md-2" style="display: inline-grid;">
                    <label><?php print CommonLanguage::getMessage('multi_barcode'); ?></label> 
                    <input type="checkbox" id="is_multi" name="is_multi"/>
                </div>
                <div class="col-md-2 start_div hidden">
                    <label><?php print CommonLanguage::getMessage('start'); ?></label> 
                    <input type="number" min="1" id="start" name="start" class="form-control  "/>
                </div>
                <div class="col-md-2 template_div">
                    <label><?php print CommonLanguage::getMessage('template'); ?></label> 
                    <input type="hidden" id="template_id" name="template_id" class="full-width"/>
                </div>
            </div>
            <div class="row form-group">
                <div class="col-md-3">
                    <label><?php print CommonLanguage::getMessage('Item'); ?><span class="red-star">*</span>
                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1&is_new=1" style="color:#8a7dbe;cursor:pointer"></span>   
                    </label>
                </div>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('UOM'); ?></label>
                </div>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('barcode'); ?></label>
                </div>
            </div>
            <div id="ItemUOMBarCode">
                <div class="row AddRow m-t-10">
                    <div class="col-md-3">
                        <input type="text" class="form-control AutoComplete Product" name="Product" />
                    </div>
                    <div class="col-md-2">     
                        <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">
                        <input type="text"  class="form-control  myBarcode" data-code="" data-desc=""  name="myBarcode" />
                    </div>
                    <div class="col-md-1 AddButtons">
                        <span class="fa fa-plus-circle" style="color:#4c0870;margin-right:25px;cursor:pointer;"></span>
                        <span class="fa fa-minus-circle" style="color:#ed9421;cursor:pointer;"></span>
                    </div>
                </div>
            </div>
            <div class="row m-t-10">
                <div class="col-md-4 col-md-offset-4">                        
                    <button class=" btn btn-primary btn-cons  pull-right" id="printbtn" type="button" style="margin-top:24px;"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>
                </div>
            </div>
        </div>
    </div>
</div>
<iframe id="barcode_frame" name="ifrm" style="width:0;height:0;visibility: hidden;" ></iframe><br>
<select required id="Select_UOM" name="Select_UOM"  class="full-width Select_UOM hidden" 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>
<script>
    var zero_price = <?php echo json_encode(CommonLanguage::getMessage('zero_price')) ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')) ?>,
            current_product = <?php echo json_encode($selected_product); ?>,
            current_price_class_name = <?php echo json_encode($current_price_class_name); ?>,
            default_barcode_class_id = <?php echo json_encode(smc_session()['default_setting']['default_barcode_class_id']); ?>,
            barcode_sumatra_print = <?php echo json_encode(smc_session()['default_setting']['barcode_sumatra_print']); ?>;
    $(function () {
        EnableAutoComplete($("input.AutoComplete.Product"));
        if (default_barcode_class_id) {
            $("#Select_Class").val(default_barcode_class_id);
            $("#Select_Class").attr('data-select-name', default_barcode_class_id == 0 ? '<?php echo CommonLanguage::getMessage('zero_price'); ?>' : current_price_class_name);
        }

        build_select2($("#Select_Class"), "xhr/PricingClassCurrencySearch?zero_class=1");
        build_select2($("#template_id"), "xhr/printTemplateSearch");
        new Switchery($("#is_multi").get(0), {color: $.Pages.getColor("primary")});
        $("#is_multi").on("change", function () {
            if ($("#is_multi").is(":checked")) {
                $(".start_div").removeClass('hidden');
                $(".template_div").addClass('hidden');
                $('#template_id').val('').trigger('change');
            } else {
                $(".start_div").addClass('hidden');
                if ($('.AddRow').length == 1)
                    $('.template_div').removeClass('hidden');

                $("#start").val("1");
            }
        });
        $("#printbtn").on("click", function () {
            var bar_code = [];
//            if ($(".myBarcode").attr("data-code") == '') {
            if ($(".myBarcode").val() == '') {
                $("#barcodealert").attr("class", "alert alert-danger").html(Required_Fields);
                return false;
            }
            $('.AddRow').each(function () {
                bar_code.push({
//                    Code: $('.myBarcode', $(this)).attr("data-code"),
                    Code: $('.myBarcode', $(this)).val(),
                    Desc: $('.myBarcode', $(this)).attr("data-desc"),
                    product_code: $('.myBarcode', $(this)).attr("data-prod-code"),
                    UOM_ID: $('select[name=UOM_ID]', $(this)).val(),
                    Product_ID: $('input[name=Product]', $(this)).attr('data-id')
                });
            });
            var data_param = {Name: $("#Name").val(),
//                Code: $(".myBarcode").attr("data-code"),
                Code: $(".myBarcode").val(),
                Desc: $(".myBarcode").attr("data-desc"),
                product_code: $(".myBarcode").attr("data-prod-code"),
                UOM_ID: $('select[name=UOM_ID]').val(),
                Product_ID: $('input[name=Product]').attr('data-id'),
                repeat: $("#print_count").val(),
                price: $("#Select_Class").val(),
                paper_height: $("#paper_size option:selected").attr("data-height"),
                paper_width: $("#paper_size option:selected").attr("data-width"),
                paper_size: $("#paper_size").val(),
                is_multi: $("#is_multi").is(":checked") ? 1 : 0,
                start: $("#start").val(),
                bar_code: bar_code,
                template_id: ($("#is_multi").is(":checked") || $('.AddRow').length == 1) ? $('#template_id').val() : ''
            };
            if (barcode_sumatra_print == 1) {
                $.ajax({
                    url: "InventoryAjax/PrintBarCode",
                    data: data_param,
                    complete: function (v1, v2) {
                        console.log(v1)
                        console.log(v2)
                        
                        $("#barcodealert").addClass("hidden");
                    }
                })
            } else {
                $('#barcode_frame').attr('src', "InventoryAjax/PrintBarCode?" + $.param(data_param));
                console.log("InventoryAjax/PrintBarCode?" + $.param(data_param))

            }
            $('.template_div').removeClass('hidden')
            $(".AddRow input").val("")
            $(".AddRow:gt(0)").empty().remove()
            $(".AddRow input[name=Product]").attr("data-id", "");
        });
        $("select.UOM_ID").on("change", function () {
            var me = $(this).parents("tr");
            var UOMData = {
                pid: $(".myBarcode").attr("data-prod-id"),
                uid: $(this).val(),
                class_id: $("#Select_Class").val()
            };
            $.ajax({
                url: "InventoryAjax/ReturnProductUOMPriceCon",
                data: UOMData,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        $(".myBarcode").attr("data-code", v1.responseJSON['Bar_Code']).val(v1.responseJSON['Bar_Code']);
                    }
                }
            })
        });
        $("#ItemUOMBarCode").on("click", ".AddButtons > .fa-plus-circle", function (e) {
            $(".AddButtons > .fa-minus-circle").css("display", "");
            var Parent = $(this).parents(".AddRow"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find("input").val('');
            $(".select2-container", NewItem).empty().remove();
            NewItem.find(".UOM_ID").show().select2();
            EnableAutoComplete($("input.AutoComplete.Product", NewItem).removeClass('AutoAdded'));
            $('.template_div').addClass('hidden');
            $('#template_id').val('').trigger('change');
        });
        $("#ItemUOMBarCode").on("click", ".AddButtons > .fa-minus-circle", function (e) {
            if ($(".AddRow").length != 1) {
                $(this).closest(".AddRow").empty().remove();
            }
            if ($(".AddRow").length == 1 && !$("#is_multi").is(":checked")) {
                $('.template_div').removeClass('hidden');
                $(".AddRow input").val("")
                $(".AddRow input[name=Product]").attr("data-id", "");
            }
        });
        if (current_product)
            fillData(current_product);
    });
    function EnableAutoComplete(who) {
        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: function (request, response) {
                    var classID = $("#Select_Class").val();
                    $.getJSON('xhr/ajaxProducts?class=' + classID, request, function (s, status, xhr) {
                        response(s);
                    });
                },
                minLength: 0,
                select: function (event, ui) {
                    var parent = $(this).parents('.AddRow');
                    $("input.AutoComplete.Product", parent).attr('data-id', ui.item.ID);
                    $("input.AutoComplete.Product", parent).val((ui.item.Name + ' - ' + ui.item.Code));
                    $("select[name=UOM_ID]", parent).empty().html($("#Select_UOM").html()).select2();
                    $("select[name=UOM_ID] > option[value=" + ui.item.UOM_ID + "]", parent).attr("selected", true);
                    $("select[name=UOM_ID]", parent).select2();
                    $(".myBarcode", parent).val(ui.item.Bar_Code);
                    $(".myBarcode", parent).attr("data-code", ui.item.Bar_Code);
                    $(".myBarcode", parent).attr("data-desc", ui.item.Disc);
                    $(".myBarcode", parent).attr("data-prod-id", ui.item.ID);
                    $(".myBarcode", parent).attr("data-prod-code", ui.item.Code);
                    $("select[name=UOM_ID]", parent).empty().html($("#Select_UOM").html());
                    //                    var units_arr = ui.item.uom;
                    $("select[name=UOM_ID] > option", parent).each(function () {
                        if (!($(this).attr("value") in ui.item.uom)) {
                            $(this).remove();
                        }
                    })
                    $("select[name=UOM_ID]", parent).val(ui.item.UOM_ID).select2();
                    apply_autocomplete($(".myBarcode"), 'xhr/search_additional_barcodes?product_id=' + $("input[name=Product]").attr("data-id"), function (event, ui, who) {
                        console.log(ui);
                        who.val(ui.item.text);
                    });
                    return false;
                }
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width()) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            };
            who.autocomplete("instance")._renderItem = function (ul, item) {
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + (item.Code + ' - ' + item.Name + ' - ' + item.Product_Price) + "</td></tr></table>").appendTo(ul);
            };
            who.addClass("AutoAdded");
        }
        $(document).keydown(function (e) {
            if (e.which == 8 && e.target.tagName.toLowerCase() != "input") {
                e.preventDefault();
            }
        });
    }
    function fillData(prod_arr) {
        $.each(prod_arr, function (indx, item) {
            if (indx == 0) {
                $("input.AutoComplete.Product").attr('data-id', item.ID);
                $("input.AutoComplete.Product").val((item.Name + ' - ' + item.Code));
                $("select[name=UOM_ID]").empty().html($("#Select_UOM").html()).select2();
                $("select[name=UOM_ID] > option[value=" + item.UOM_ID + "]").attr("selected", true);
                $("select[name=UOM_ID]").select2();
                $(".myBarcode").val(item.Bar_Code);
                $(".myBarcode").attr("data-code", item.Bar_Code);
                $(".myBarcode").attr("data-desc", item.Disc);
                $(".myBarcode").attr("data-prod-code", item.Code);
                $(".myBarcode").attr("data-prod-id", item.ID);
                $("select[name=UOM_ID]").empty().html($("#Select_UOM").html());
                $("select[name=UOM_ID] > option").each(function () {
                    if (!($(this).attr("value") in item.uom)) {
                        $(this).remove();
                    }
                })
//                $(".select2-container").empty().remove();

                $("select[name=UOM_ID]").val(item.UOM_ID).select2();
            } else {
                var Parent = $("#ItemUOMBarCode"), NewItem = $(".AddRow:eq(0)").clone().appendTo(Parent);
                $("input.AutoComplete.Product", NewItem).attr('data-id', item.ID);
                $("input.AutoComplete.Product", NewItem).val((item.Name + ' - ' + item.Code));
                $("select[name=UOM_ID]", NewItem).empty().html($("#Select_UOM").html()).select2();
                $("select[name=UOM_ID] > option[value=" + item.UOM_ID + "]", NewItem).attr("selected", true);
                $("select[name=UOM_ID]", NewItem).select2();
                $(".myBarcode", NewItem).val(item.Bar_Code);
                $(".myBarcode", NewItem).attr("data-code", item.Bar_Code);
                $(".myBarcode", NewItem).attr("data-desc", item.Disc);
                $(".myBarcode", NewItem).attr("data-prod-code", item.Code);
                $(".myBarcode", NewItem).attr("data-prod-id", item.ID);
                $("select[name=UOM_ID]", NewItem).empty().html($("#Select_UOM").html());
                $("select[name=UOM_ID] > option", NewItem).each(function () {
                    if (!($(this).attr("value") in item.uom)) {
                        $(this).remove();
                    }
                });
                $(".select2-container", NewItem).empty().remove();
                $("select[name=UOM_ID]", NewItem).val(item.UOM_ID).select2();
            }
        });
    }
</script>
