<?php
if ($permissions->hasPermission('add_production_template')) {
    include("Views/Maintenance/add_production_template.php");
}
?>
<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('production_template'); ?></div>
            <?php echo Forms::FloatingAddButton('652d90', '#add_production_template', CommonLanguage::getMessage('add')); ?>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered maintenance-table" id="tableWithSearch" >
                        <thead>
                            <tr>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('template_name'); ?></th>
                                <th class="text-center no-print" style="width:15%"><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('production_template')) ?>,
            is_adv = <?php echo json_encode($is_adv) ?>;
    var IsEdit = false,
            IDToEdit = null;
    $(function () {
        $(".floatingContainer").on("click", function () {
            IsEdit = false;
            $("#in_items .AddRow:gt(0),#out_items .AddRow:gt(0),#template_expenses .AddRow:gt(0)").remove()
            $("input.in_qty,input.out_qty,input.expense_cost").val('')
            $("input[name=in_product],input[name=out_product],input[name=in_uom],input[name=out_uom],input[name=account_id]").val('').attr("data-select-name", "");
            build_select2($("input[name=in_product],input[name=out_product]"), ("xhr/ProductSearch?Status_ID=1"))
            build_select2($("input[name=out_uom]"), "xhr/productuomSearch?pid=" + $("input[name=out_product]").val())
            build_select2($("input[name=in_uom]"), "xhr/productuomSearch?pid=" + $("input[name=in_product]").val())
            build_select2($("input[name=account_id]"), "xhr/allAccountsSearch")
            $("#add_production_template .add-label").removeClass("hidden")
            $("#slide2").removeClass("active")
            $("#slide1").addClass("active")
        })
        RebuildDataTable(title, [0], "InventoryAjax/production_template_list", {is_adv: is_adv})
        $('#tableWithSearch').on('click', '.delete', function () {
            var entry_value = $(this).parents('div.Action').attr('data-id');
            IncludeDeleteModal(common_delete_modal, {id: entry_value}, function () {
                RebuildDataTable(title, [0], "InventoryAjax/production_template_list", {is_adv: is_adv})
            }, "MaintenanceAjax/delete_production_template");
        });
        //get_production_template_id
        $("#tableWithSearch tbody").on("click", ".Edit", function () {
            $("#add_production_template .edit-label").removeClass("hidden")
            IsEdit = true;
            IDToEdit = $(this).parents('.Action').attr("data-id");
            fill_template_modal(IDToEdit)

        })
        $("#tableWithSearch tbody").on("click", ".copy", function () {
            $("#add_production_template .edit-label").addClass("hidden")
            $("#add_production_template .add-label").removeClass("hidden")
            $("#slide2").removeClass("active")
            $("#slide1").addClass("active")
            IsEdit = false;
            var temp_id = $(this).parents('.Action').attr("data-id");
            fill_template_modal(temp_id)

        })
    })
    function fill_template_modal(temp_id) {
        $.ajax({
            url: "InventoryAjax/get_production_template_id",
            method: "GET",
            dataType: "json",
            data: {id: temp_id, with_optional: 1},
            complete: function (v1, v2) {
                if (v2 == 'success') {
                    var mydata = v1.responseJSON;
                    $("#template_name").val(mydata['main']['template_name'])
                    $("#is_line_required").prop('checked', mydata['main']['is_line_required'] == "1" ? true : false)
                    $("#CurrencyDropDown button input").val(mydata['main']['Currency_ID'])
                    $("#CurrencyDropDown button span").html(mydata['main']['Currency_Name'] + " - " + mydata['main']['Currency_Symbol'])
                    $("#CurrencyDropDown").attr("data-symbol", mydata['main']['Currency_Symbol'])
                    $("#production_category_id").val(mydata['main']['category_id']).attr("data-select-name", mydata['main']['category_name']).trigger("change")
                    $('#out_product_ids').select2('val', [])
                    $('#out_product_ids').data().select2.updateSelection(mydata['products']);
                    $('#in_product_ids').select2('val', [])
                    $('#in_product_ids').data().select2.updateSelection(mydata['produced_products']);
                    $('#production_emp_type_ids').select2('val', [])
                    $('#production_emp_type_ids').data().select2.updateSelection(mydata['production_emp_type']);
                    $("#groups_tag").tagsinput("add", mydata['main']['groups'].join(','))
                    //                        if (mydata['main']['create_trans'] == 1) {
                    //                            if (!$("#create_trans").is(":checked"))
                    //                                $("#create_trans").trigger("click")
                    //
                    //                        } else {
                    //                            if ($("#create_trans").is(":checked")) {
                    //                                $("#create_trans").trigger("click")
                    //
                    //                            }
                    //                        }
                    $("select.out_group option[value!=''],select.in_group option[value!='']").remove()
                    if (mydata['main']['groups'].length > 0) {
                        $.each(mydata['main']['groups'], function (indx, value) {
                            $("select.out_group,select.in_group").each(function () {
                                $('<option value=' + value + '>' + value + '</option>').appendTo($(this))
                            })
                        })
                    }
                    var details = mydata['details'];
                    var out_row = $("#out_items .AddRow:eq(0)").clone(),
                            in_row = $("#in_items .AddRow:eq(0)").clone();

                    var in_filled = false, out_filled = false;
                    for (var i = 0; i < details.length; i++) {
                        if (details[i]['operation'] == "+") {
                            if (!out_filled) {
                                $("#out_items").empty();
                                out_filled = true;
                            }
                            out_row = (out_row === null ? $("#out_items .AddRow:eq(0)").clone() : out_row);
                            $("#out_items").append(out_row)
                            $(".select2-container", out_row).empty().remove()
                            out_row.find('.out_optional').prop("checked", details[i]['optional'] == 1 ? true : false)

                            out_row.find("input[name=out_product]").val(details[i]['Product_ID']).attr("data-select-name", details[i]['Product_Name'])
                            build_select2(out_row.find("input[name=out_product]"), ("xhr/ProductSearch?is_edited=" + details[i]['Product_ID']))
                            out_row.find("input[name=out_depot]").val(details[i]['Depot_ID']).attr("data-select-name", details[i]['Depot_Name'])
                            build_select2(out_row.find("input[name=out_depot]"), "xhr/depotSearch")
                            out_row.find("input[name=out_uom]").val(details[i]['UOM_ID']).attr("data-select-name", details[i]['UOM_Name'])
                            build_select2(out_row.find("input[name=out_uom]"), "xhr/productuomSearch?pid=" + out_row.find("input[name=out_product]").val())
                            out_row.find(".out_qty").val(details[i]['value_type'] == 1 ? details[i]['current_quantity'] : details[i]['formula'])
                            out_row.find("select.out_value_type").val(details[i]['value_type']).select2()
                            out_row.find("select.out_group").val(details[i]['group_name']).select2()
                            out_row.find("input.out_identifier").val(details[i]['identifier'])
                            out_row.find("input.out_use_product").prop("checked", details[i]['use_product'] == 1 ? true : false)
                            $(".select2-container", out_row).show();
                            out_row = null;
                        } else {

                            if (!in_filled) {
                                $("#in_items").empty();
                                in_filled = true;
                            }
                            in_row = (in_row === null ? $("#in_items .AddRow:eq(0)").clone() : in_row);
                            $("#in_items").append(in_row)
                            $(".select2-container", in_row).empty().remove()
                            in_row.find('.in_optional').prop("checked", details[i]['optional'] == 1 ? true : false)
                            in_row.find("input[name=in_product]").val(details[i]['Product_ID']).attr("data-select-name", details[i]['Product_Name'])
                            build_select2(in_row.find("input[name=in_product]"), ("xhr/ProductSearch?is_edited=" + details[i]['Product_ID']))
                            in_row.find("input[name=in_depot]").val(details[i]['Depot_ID']).attr("data-select-name", details[i]['Depot_Name'])
                            build_select2(in_row.find("input[name=in_depot]"), "xhr/depotSearch")
                            in_row.find("input[name=in_uom]").val(details[i]['UOM_ID']).attr("data-select-name", details[i]['UOM_Name'])
                            build_select2(in_row.find("input[name=in_uom]"), "xhr/productuomSearch?pid=" + in_row.find("input[name=in_product]").val())
                            in_row.find(".in_qty").val(details[i]['value_type'] == 1 ? details[i]['current_quantity'] : details[i]['formula'])
                            in_row.find("select.in_value_type").val(details[i]['value_type']).select2()
                            in_row.find("select.in_group").val(details[i]['group_name']).select2()
                            in_row.find("input.in_identifier").val(details[i]['identifier'])
                            in_row.find("input.in_use_product").prop("checked", details[i]['use_product'] == 1 ? true : false)
                            $(".select2-container", in_row).show()
                            in_row = null;
                        }
                    }
                    var expenses = mydata['expense'];
                    var ex_row = $("#template_expenses .AddRow:eq(0)").clone();
                    $("#template_expenses").empty();
                    if (expenses.length > 0) {
                        for (var i = 0; i < expenses.length; i++) {
                            ex_row = (ex_row === null ? $("#template_expenses .AddRow:eq(0)").clone() : ex_row);
                            $("#template_expenses").append(ex_row)
                            $(".select2-container", ex_row).empty().remove()
                            ex_row.find("input[name=account_id]").val(expenses[i]['Account_ID']).attr("data-select-name", expenses[i]['Account_Name'])
                            build_select2($("input[name=account_id]"), "xhr/allAccountsSearch")
                            ex_row.find(".expense_cost").val(expenses[i]['cost'])
                            if (expenses[i]['is_total'] == 1) {
                                ex_row.find(".is_total").prop("checked", true)
                            } else {
                                ex_row.find(".is_total").removeAttr("checked")
                            }
                            $(".select2-container", in_row).show()
                            ex_row = null;
                        }
                    } else {
                        $("#template_expenses").append(ex_row)
                        $(".select2-container", ex_row).empty().remove()
                        ex_row.find("input[name=account_id]").val(0).attr("data-select-name", '')
                        build_select2($("input[name=account_id]"), "xhr/allAccountsSearch")
                        $(".select2-container", in_row).show()
                    }
                    $("#add_production_template").modal("show")
                }
            }
        })
    }
</script>