<?php
$fields_hide = smc_session()['default_setting']['production_process_touch_fields_hide'] != '' ? explode(",", smc_session()['default_setting']['production_process_touch_fields_hide']) : [];
//die(print_r($fields_hide));
?>
<style >
    .main-div{
        min-height: 800px;
    }
    .block-div{
        height:50%;
        border:1px solid #ddd;
        padding:0;
    }
    .p-0{
        padding:0 !important;
    }
    .panel{
        border:0 !important;
    }
    .in-items th,.out-items th{
        background: #3B4752;
        z-index: 999;
        /* position: absolute; */
        color: #fff !important;
        padding: 9px 7px;
        top: 0;
        margin-left: -8px;
        line-height: normal;
    }
    .in-items, .out-items{
        margin:0 !important;
    }
    .pers{
        -webkit-perspective:1200px;
        -moz-perspective:1200px;
        perspective:1200px;
        -webkit-transform: translateZ(0);
    }
    .product_divs{
        display: block;
        /*max-height:135px;*/
        /*height:135px;*/
        max-width: 100%;
        border-radius: 3px;
        color:#969696;
        background-color: #40D9CA;
        /*position: absolute;*/
        padding:15%;

    }
    .group_divs{
        display: block;
        /*max-height:135px;*/
        /*height:135px;*/
        max-width: 100%;
        border-radius: 3px;
        color:#969696;
        background-color: #4c0870!important;
        /*position: absolute;*/
        padding:15%;

    }
    .product-container{
        /*padding-top: 75%;*/
        /*position: relative;*/
        width: 100%;
        height: 100%;
        padding:0;
    }
    #keypad{
        width:100%;
        height:100%;
        border:solid 1px black;
        /*display:none;*/
        /*position:absolute;*/
        /*top:22px;*/
        /*left:1px;*/
    }
    .key{
        border:solid 1px #bfbfbf;
        /*background-color:#bfbfbf;*/
        background-color:#e2e2e2;
        text-align:center;
        font-weight:bold;
        color:#555555;
        cursor:pointer;
        width:20%;
    }
    .key:hover{
        background-color:LightBlue;
    }
    .key:active{
        background-color:white;
    }
    .empty_key{
        border:solid 1px #bfbfbf;
        /*background-color:#bfbfbf;*/
        background-color:#e2e2e2;
        text-align:center;
        font-weight:bold;
        color:#555555;
        cursor:pointer;
        width:20%;
    }
    .empty_key:hover{
        background-color:LightBlue;
    }
    .empty_key:active{
        background-color:white;
    }
    .key1{
        border:solid 1px #bfbfbf;
        /*background-color:#bfbfbf;*/
        background-color:#e2e2e2;
        text-align:center;
        font-weight:bold;
        color:#555555;
        cursor:pointer;
        width:20%;
    }
    .choosen{
        background-color:DarkGray;
    }
    .key1:hover{
        background-color:DarkGray;
    }
    /*    .key1:active{
            background-color:LightGray;
        }*/
    .page-container .page-content-wrapper .content{
        padding-bottom:0px;
    }
    .page-content-wrapper .container-fluid{
        padding-right:0px;
        padding-left:0px;
    }
    .prod-card,.group-card{
        cursor:pointer;
    }
    .fn-btn {
        width: 20% !important;
        margin-bottom: 5px;
    }
    .fn-btn button,btn-back button {
        width: 100%;
        /*background: #ddd;*/
        padding:15%;
    }
    .fn-btn button:hover {
        background-color:#626c75;
    }
    .btn-nb{
        background-color: #ddd;  
        width:100%;
        /*padding-right: 1%;*/
        /*padding: 20%;*/
    }
    .btn-back{
        background-color: #ddd;  
    }
    .prod-card:hover .product_divs{
        background-color: #4c0870;
    }
    .prod-card,.group-card{
        height:100px;
        min-width:141.25px;
    }
    .group-card:hover.group_divs{
        background-color: #red;
    }
    .card-name{
        color: #fff;
        text-shadow: 0 0 3px black;
    }
    .del-tr{
        cursor:pointer;
    }
    .tr-gray {
        background-color: #e2e2e2 !important;
    }
    .btn-default{
        background-color:#ddd;
    }
    .main-border{
        /*border:  solid 0.5px #bfbfbf;*/
    }
    .btn{
        white-space: normal;
    }
    .template_id,.template_cat{
        height: 75px;
        padding:3% !important;
        overflow:hidden;
    }
    .white{
        color: white !important;
    }
    .width41{
        width:51% !important;
    }
    .width45{
        width:55% !important;
    }

</style>

<div style="width:100%;height:calc(100vh - 60px);"><!-- subtract the header height-->

    <div style="float:left;width:35%;height:100%;" >

        <div class="scroll-div-scrollable dragscroll main-border" style="width:100%;height:50%;background:white;overflow:auto;">

            <table class="table in-items scroll-div-contents">
                <thead>
                <th class="text-center"   style="width:5%"></th>
                <th class="text-center <?php echo !in_array(0, $fields_hide) ? '' : 'hidden' ?>" style="width:20%"><?php echo CommonLanguage::getMessage('Code') ?></th>
                <th class="text-center" style="width:34%"><?php echo CommonLanguage::getMessage('raw_material') ?></th>
                <th class="text-center" style="width:20%"><?php echo CommonLanguage::getMessage('qty') ?></th>
                <th class="text-center <?php echo !in_array(1, $fields_hide) ? '' : 'hidden' ?>" style="width:19%"><?php echo CommonLanguage::getMessage('UOM') ?></th>
                <th class="text-center" style="width:7%"></th>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
        <div class="scroll-div-scrollable dragscroll main-border" style="width:100%;height:50%;background:white;overflow:auto;">
            <table class="table out-items scroll-div-contents">
                <thead>
                <th class="text-center"  style="width:5%"></th>
                <th class="text-center <?php echo !in_array(0, $fields_hide) ? '' : 'hidden' ?>" style="width:20%"><?php echo CommonLanguage::getMessage('Code') ?></th>
                <th class="text-center" style="width:34%"><?php echo CommonLanguage::getMessage('finished_goods') ?></th>
                <th class="text-center" style="width:27%"><?php echo CommonLanguage::getMessage('qty') ?></th>
                <th class="text-center <?php echo !in_array(1, $fields_hide) ? '' : 'hidden' ?>" style="width:19%"><?php echo CommonLanguage::getMessage('UOM') ?></th>
                <th class="text-center" style="width:7%"></th>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <div style="float:left;width:10%;height:100%;" >
        <table id="keypad" style="">
            <tbody>
                <tr><td class="key1 bg-danger white"  data-role="template"><?php echo CommonLanguage::getMessage('template') ?></td></tr>
                <tr><td class="key1 bg-success-darker white" data-role="submit"><?php echo CommonLanguage::getMessage('Save') ?></td>
                <tr><td class="key1 all-caps" data-role="CLR">CLR</td></tr>

                <tr><td class="key">1</td></tr>
                <tr><td class="key">2</td></tr>
                <tr><td class="key">3</td></tr>
                <tr><td class="key">4</td></tr>
                <tr><td class="key">5</td></tr>
                <tr><td class="key">6</td></tr>
                <tr><td class="key">7</td></tr>
                <tr><td class="key">8</td></tr>
                <tr><td class="key">9</td></tr>
                <tr><td class="key">.</td></tr>
                <tr><td class="key">0</td></tr>

            </tbody></table>
    </div>
    <div class="home_col_div" style="float:left;width:4%;height:100%;" >
        <div class=" main-border text-center" style="width:100%;height:50%;background:white;overflow:auto;">
            <span class="fa fa-home fa-3x cursor" id="needed_home"></span>
        </div>
        <div class=" main-border text-center" style="width:100%;height:50%;background:white;overflow:auto;border-top:solid 2px #bfbfbf;">
            <span class="fa fa-home fa-3x cursor" id="finished_home"></span>
        </div>

    </div>
    <div class="scroll_main_cntnr products_main_div width41" style="float:right;height:100%;" >
        <div class="scroll-div-scrollable dragscroll main-border" style="width:100%;height:50%;background:white;overflow:auto;border-left:solid 2px #bfbfbf;">
            <div class="scroll-div-contents ">
                <div class='cards-div'>

                </div>

                <div style="clear:both;"></div>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div class="main-border scroll-div-scrollable dragscroll" style="width:100%;height:50%;background:white;border-top:solid 2px #bfbfbf;border-left:solid 2px #bfbfbf;">
            <div class="scroll-div-contents ">
                <div class='prod-cards-div'>

                </div>

                <div style="clear:both;"></div>
            </div>
        </div>
    </div>
    <div style="clear:both;"></div>
</div>
<div class="modal fade" id="production_template_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content-wrapper">
            <div class="modal-content">
                <div class="modal-header clearfix text-left">
                    <h5 class="add-label bold"></h5>
                    <div id="temp_alert"></div>
                </div>
                <div class="modal-body">
                    <form id="production_form" method="POST" onsubmit="return false">

                        <div class="row ">
                            <div class="col-xs-12 col-md-12 m-b-10">
                                <?php for ($i = 0; $i <= 9; $i++) { ?>
                                    <div class=" col-xs-6 col-sm-4 col-md-1 col-lg-1 p-0"><button type="button" class="btn btn-default btn-nb "><?php echo $i; ?></button></div>
                                <?php } ?>
                                <div class=" col-xs-6 col-sm-4 col-md-1 col-lg-1 p-0"><button type="button" class="btn btn-default btn-nb btn-back"><i class="fa fa-arrow-left "></i></button></div>

                            </div>
                            <div class="col-md-12 m-b-10 form-group">
                                <div class="col-md-3"> 
                                    <label><?php echo CommonLanguage::getMessage('quantity') ?><span class="red-star">*</span></label>
                                    <input type="number" id="template_nb" name="template_id" class="form-control"/>
                                </div>
                                <div class="col-md-3"> 
                                    <label><?php echo CommonLanguage::getMessage('line') ?><span class="hidden line-label red-star">*</span></label>
                                    <input type="hidden" id="line_id" name="line_id" class="full-width"/>
                                </div>
                            </div>
                        </div>
                        <div class="row ">
                            <h4><?php echo CommonLanguage::getMessage('template') ?><span class="red-star">*</span></h4>

                            <div id="temp_main_div">
                                <?php foreach ($templates_cat as $cat) { ?>
                                    <div class="btn-group col-xs-12 col-sm-6 col-md-3 col-lg-3  fn-btn m-b-10">

                                        <button type="button" class="btn btn-primary w-100  template_cat text-center"  >

                                            <span class="f-s-10 font-montserrat  temp-card" data-id="<?php echo $cat['category_id'] ?>" data-required="<?php echo $cat['is_line_required'] ?>"><?php echo $cat['category_name'] ?></span>
                                        </button>
                                    </div>
                                <?php } ?>
                                <?php foreach ($templates as $temp) { ?>
                                    <div class="btn-group col-xs-12 col-sm-6 col-md-3 col-lg-3  fn-btn m-b-10">

                                        <button type="button" class="btn btn-default w-100  template_id text-center"  >

                                            <span class="f-s-10 font-montserrat  temp-card" data-id="<?php echo $temp['template_id'] ?>" data-required="<?php echo $temp['is_line_required'] ?>"><?php echo $temp['template_name'] ?></span>
                                        </button>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" id="cancel_btn" class="col-md-3 btn btn-danger  " data-dismiss="modal"><?php echo CommonLanguage::getMessage('Cancel') ?></button>
                    <button type="button" id="next_btn" class="col-md-3 btn btn-info pull-right" ><?php echo CommonLanguage::getMessage('next') ?></button>
                </div>

            </div>
        </div>
    </div>
</div>
<?php echo Forms::ModalLoader('process_loader') ?>
<script src="<?php echo SITE_LINK; ?>Views/files/scroll-div.js"></script>
<script type="text/javascript">
                        var choose_temp_qty = <?php echo json_encode(CommonLanguage::getMessage('choose_temp_qty')) ?>,
                                Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')) ?>,
                                Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')) ?>,
                                fill_in_out_items = <?php echo json_encode(CommonLanguage::getMessage('fill_in_out_items')) ?>,
                                fill_uom_items = <?php echo json_encode(CommonLanguage::getMessage('fill_uom_items')) ?>,
                                today = <?php echo json_encode(date('Y-m-d')); ?>,
                                local_currency = <?php echo json_encode(smc_session()['default_setting']['local_currency']); ?>,
                                depot_id = <?php echo json_encode(smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']); ?>,
                                fields_hide = <?php echo json_encode($fields_hide); ?>,
                                template_id = 0, mytr = '', template_qty = 0,line_id=0;
                        var variables = [], id_val = [], id_content = [], calculated_vars = [], loop_count = 0, max_loop = 500, row_val = {};
                        var tr_temp = '<tr><td><span class="is_formula fa fa-superscript hidden"></span></td><td class="pr-code text-center '+(fields_hide.includes('0') ? 'hidden' : '')+'"></td><td class="pr-name text-center"></td>' +
                                '<td class=" text-center"><input type="text" min="0" step="any" class="pr-qty cur_val form-control" /></td><td class="pr-uom '+(fields_hide.includes('1') ? 'hidden' : '')+'"><input class="pr-uom full-width" type="hidden"></td><td class="red-star del-td" ><i class="del-tr fa fa-2x fa-trash"></i></td></tr>';
                        var card_temp = ' <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3 m-b-5 m-t-5 p-l-5 p-r-5 prod-card ">'
                                + '<div class="product-container">'
                                + '<div class="product_divs product-container" >'
                                + '<div class="panel-heading">'
                                + '<div class="panel-title text-black  hint-text text-center">'
                                + '<b class="card-name">Tab3</b>'
                                + '</div>'
                                + ' </div>'
                                + '</div>'
                                + ' </div>'
                                + ' </div>';
                        $(function () {
//                            console.log(fields_hide)

                            build_select2($("#line_id"), "xhr/CommonSearch?col_name=line_name&col_id=line_id&table=tbl_line");

                            init_scroll_obj($('.scroll_main_cntnr'));
                            $("#production_template_modal").modal("show")

                            $(".btn-nb").on("click", function () {
                                var input_val = $("#template_nb").val(),
                                        text = $(this).text(),
                                        new_val = input_val + text;
                                if (input_val == '' && text == '0')
                                    return;
                                $("#template_nb").val(new_val)

                            })
                            //
                            $(".btn-back").on("click", function () {
                                var input_val = $("#template_nb").val();
                                $("#template_nb").val(input_val.substring(0, input_val.length - 1))
                            })
                            //
                            $("#temp_main_div").on("click", ".template_cat", function () {
                                template_id = 0;
                                line_id = 0;
                                var cat_id = $(".temp-card", $(this)).attr("data-id");
                                $.ajax({
                                    url: "MaintenanceAjax/get_production_templates",
                                    data: {id: cat_id},
                                    dataType: "json",
                                    complete: function (v1, v2) {
                                        if (v2 == "success") {
                                            build_templates(v1.responseJSON)

                                        }
                                    }
                                })
                            })
                            //
                            $("#temp_main_div").on("click", ".back_cat", function () {
                                $.ajax({
                                    url: "MaintenanceAjax/get_production_categories",
                                    data: {},
                                    dataType: "json",
                                    complete: function (v1, v2) {
                                        if (v2 == "success") {
                                            build_cat_templates(v1.responseJSON)

                                        }
                                    }
                                })
                            })
                            //
                            $("#temp_main_div").on("click", ".template_id", function () {
                                $(".template_id").removeClass("btn-info").addClass("btn-default")
                                $(this).removeClass("btn-default").addClass("btn-info")
                                template_id = $(".temp-card", $(this)).attr("data-id");
                                if ($(this).find(".temp-card").attr("data-required") == 1) {
                                    $("#line_id").prop("required", true)
                                    $(".line-label").removeClass("hidden")
                                } else {
                                    $("#line_id").prop("required", false)
                                    $(".line-label").addClass("hidden")


                                }
                            })
                            //
                            $("#needed_home").on("click", function () {
                                $.ajax({
                                    url: "InventoryAjax/get_template_details",
                                    data: {id: template_id},
                                    dataType: "json",
                                    complete: function (v1, v2) {
                                        if (v2 == "success") {
                                            var data = v1.responseJSON;
                                            $(".cards-div").empty()
                                            //groups
                                            set_needed_groups(data['groups'], 'in')

                                            //products that may be used
                                            set_needed_items(data['products']);

                                        }
                                    }
                                })
                            })
                            $("#finished_home").on("click", function () {
                                $.ajax({
                                    url: "InventoryAjax/get_template_details",
                                    data: {id: template_id},
                                    dataType: "json",
                                    complete: function (v1, v2) {
                                        if (v2 == "success") {
                                            var data = v1.responseJSON;
                                            $(".prod-cards-div").empty()
                                            //groups
                                            set_needed_groups(data['groups'], 'out')

                                            //products that may be used
                                            set_finished_items(data['produced_products'])

                                        }
                                    }
                                })
                            })
                            //
                            $("#next_btn").on("click", function () {
                                if (!$("#production_form").valid())
                                    return;
                                line_id= $("#line_id").val();
                                row_val = {};
                                if ($("#template_nb").val() == '' || template_id == 0) {
                                    $("#temp_alert").attr("class", "alert alert-danger").html(choose_temp_qty)
                                    return;
                                }
                                template_qty = parseFloat($("#template_nb").val());
                                $.ajax({
                                    url: "InventoryAjax/get_template_details",
                                    data: {id: template_id},
                                    dataType: "json",
                                    complete: function (v1, v2) {
                                        if (v2 == "success") {
                                            var data = v1.responseJSON;
                                            variables = data['variables'];
                                            id_val = data['id_val'];
                                            id_content = data['id_content'];
                                            $(".out-items tbody").empty()
                                            $(".in-items tbody").empty()
                                            if (data['groups'].length == 0) {
                                                $(".products_main_div").removeClass("width41").addClass("width45")
                                                $(".home_col_div").addClass("hidden")
                                            } else {
                                                $(".products_main_div").addClass("width41").removeClass("width45")
                                                $(".home_col_div").removeClass("hidden")
                                            }
                                            $(".cards-div,.prod-cards-div").empty()
                                            var row_indx = 0;
                                            //out items
                                            for (var i = 0; i < data['products_out'].length; i++) {
                                                var pr_row = data['products_out'][i];
                                                var tr = $(tr_temp);
                                                tr.attr("data-formula", pr_row['formula'])
                                                tr.attr("data-identifier", pr_row['new_identifier'])

                                                tr.attr("data-service", pr_row['is_service'])
                                                tr.attr("data-id", pr_row['Product_ID'])
                                                tr.attr("data-depot", pr_row['Depot_ID'])
                                                tr.attr("data-init-qty", pr_row['current_quantity'])
                                                if (pr_row['formula'] != '')
                                                    $(".is_formula", tr).removeClass("hidden")
//                            $("td.del-td", tr).remove()
                                                $("td.pr-code", tr).html(pr_row['Product_Code'])
                                                $("td.pr-name", tr).html(pr_row['Product_Name'])
                                                $("input.pr-qty", tr).val((template_qty * parseFloat(pr_row['current_quantity'])))
                                                $("input.pr-qty", tr).attr("data-indx", row_indx++)
                                                $("input.pr-uom", tr).val(pr_row['UOM_ID']).attr("data-select-name", pr_row['UOM_Name'])
                                                build_select2($("input.pr-uom", tr), "xhr/productuomSearch?pid=" + pr_row['Product_ID']);
                                                tr.appendTo($(".out-items tbody"));

                                            }
                                            //in items (raw materials)
                                            for (var i = 0; i < data['products_in'].length; i++) {
                                                var pr_row = data['products_in'][i];
                                                var tr = $(tr_temp);
                                                tr.attr("data-formula", pr_row['formula'])
                                                tr.attr("data-identifier", pr_row['new_identifier'])
                                                tr.attr("data-service", pr_row['is_service'])
                                                tr.attr("data-id", pr_row['Product_ID'])
                                                tr.attr("data-depot", pr_row['Depot_ID'])
                                                tr.attr("data-init-qty", pr_row['current_quantity'])
                                                if (pr_row['formula'] != '')
                                                    $(".is_formula", tr).removeClass("hidden")
                                                $("td.pr-code", tr).html(pr_row['Product_Code'])
                                                $("td.pr-name", tr).html(pr_row['Product_Name'])
                                                $("input.pr-qty", tr).val((template_qty * parseFloat(pr_row['current_quantity'])))
                                                $("input.pr-qty", tr).attr("data-indx", row_indx++)
                                                $("input.pr-uom", tr).val(pr_row['UOM_ID']).attr("data-select-name", pr_row['UOM_Name'])
                                                build_select2($("input.pr-uom", tr), "xhr/productuomSearch?pid=" + pr_row['Product_ID']);
                                                tr.appendTo($(".in-items tbody"));

                                            }
                                            //groups
                                            set_needed_groups(data['groups'], 'in')
                                            set_needed_groups(data['groups'], 'out')

                                            //products that may be used
                                            set_needed_items(data['products']);

                                            //products that may be used (produced)
                                            set_finished_items(data['produced_products'])


                                            $("#production_template_modal").modal("hide")
                                        }
                                    }
                                })
                            })
                            $(".cards-div").on("click", ".group-card", function () {
                                $.ajax({
                                    url: "MaintenanceAjax/get_group_temp_products",
                                    data: {id: template_id, group: $(this).attr("data-name"), operation: '-'},
                                    dataType: "json",
                                    complete: function (v1, v2) {
                                        if (v2 == "success") {
                                            $(".cards-div").empty()
                                            set_needed_items(v1.responseJSON['products'])
                                        }
                                    }
                                })

                            })
                            $(".prod-cards-div").on("click", ".group-card", function () {
                                $.ajax({
                                    url: "MaintenanceAjax/get_group_temp_products",
                                    data: {id: template_id, group: $(this).attr("data-name"), operation: '+'},
                                    dataType: "json",
                                    complete: function (v1, v2) {
                                        if (v2 == "success") {
                                            $(".prod-cards-div").empty()
                                            set_finished_items(v1.responseJSON['products'])
                                        }
                                    }
                                })

                            })
                            //
                            $(".cards-div").on("click", ".prod-card", function () {
                                var tr = $(tr_temp);
                                tr.attr("data-id", $(this).attr('data-id'))
                                tr.attr("data-depot", $(this).attr('data-depot'))
                                tr.attr("data-service", $(this).attr('data-service'))
                                tr.attr("data-formula", $(this).attr('data-formula'))
                                tr.attr("data-identifier", $(this).attr('data-identifier'))
                                var qty = template_qty * (parseFloat($(this).attr("data-init-qty")) || 0)
                                tr.attr("data-init-qty", qty)

                                $("td.pr-code", tr).html($(this).attr('data-code'))
                                $("td.pr-name", tr).html($(this).attr('data-name'))
                                $("input.pr-qty", tr).val(qty).attr("data-indx", get_next_indx())
                                $("input.pr-uom", tr).val($(this).attr('data-uom')).attr("data-select-name", $(this).attr('data-uom-name'))
                                build_select2($("input.pr-uom", tr), "xhr/productuomSearch?pid=" + $(this).attr('data-id'));
                                tr.appendTo($(".in-items tbody"));
                                mytr = tr;
                                $("table td").removeClass("tr-gray");
                                $("td", mytr).addClass("tr-gray");
                                trigger_qty_change($("input.pr-qty", tr))
                                if ($(this).attr('data-formula') != '') {
                                    $(".is_formula", tr).removeClass("hidden")
                                    $("input.pr-qty", tr).prop('readonly', true)
                                } else {
                                    $("input.pr-qty", tr).focus().select()
                                }
                            })
                            $(".prod-cards-div").on("click", ".prod-card", function () {
                                var tr = $(tr_temp);
                                tr.attr("data-id", $(this).attr('data-id'))
                                tr.attr("data-depot", $(this).attr('data-depot'))
                                tr.attr("data-service", $(this).attr('data-service'))
                                tr.attr("data-formula", $(this).attr('data-formula'))
                                tr.attr("data-identifier", $(this).attr('data-identifier'))
//            tr.attr("data-init-qty", 1)
                                var qty = template_qty * (parseFloat($(this).attr("data-init-qty")) || 0)
                                tr.attr("data-init-qty", qty)
                                $("td.pr-code", tr).html($(this).attr('data-code'))
                                $("td.pr-name", tr).html($(this).attr('data-name'))
                                $("input.pr-qty", tr).val(qty).attr("data-indx", get_next_indx())
                                $("input.pr-uom", tr).val($(this).attr('data-uom')).attr("data-select-name", $(this).attr('data-uom-name'))
                                build_select2($("input.pr-uom", tr), "xhr/productuomSearch?pid=" + $(this).attr('data-id'));
                                tr.appendTo($(".out-items tbody"));
                                mytr = tr;
                                $("table td").removeClass("tr-gray");
                                $("td", mytr).addClass("tr-gray");
                                trigger_qty_change($("input.pr-qty", tr))
                                if ($(this).attr('data-formula') != '') {
                                    $(".is_formula", tr).removeClass("hidden")
                                    $("input.pr-qty", tr).prop('readonly', true)
                                } else {
                                    $("input.pr-qty", tr).focus().select()
                                }

                            })
                            //
                            $("table").on("click", ".del-tr", function () {
                                var identifier = $(this).parents("tr").attr("data-identifier");
                                calculated_vars = [];
                                loop_count = 0;

                                $(this).parents("tr").remove();
                                calculate_formulas(identifier);
                            })
                            //
                            $("table.in-items,table.out-items").on("click", "tr", function () {
                                $("table td").removeClass("tr-gray")
                                $("td", $(this)).addClass("tr-gray")
                                $("input.pr-qty", $(this)).focus().select()
                                mytr = $(this)
                            })
                            //
                            $(".key,.key1").on("click", function () {
                                if ($(this).attr('data-role') === 'template') {
                                    change_template()
                                    return
                                } else if ($(this).attr('data-role') === 'submit') {
                                    submit_process()
                                    return
                                }
                                if (mytr == '')
                                    return false;
                                var input = $("input.pr-qty", mytr);
                                var start = input.prop("selectionStart"),
                                        end = input.prop("selectionEnd"),
                                        prefixStr = input.val().substring(0, start),
                                        sufixStr = input.val().substring(end, input.val().length),
                                        selectedStr = input.val().substring(start, end);


                                if (mytr.attr("data-formula") != '' && $(this).attr('data-role') != 'template' && $(this).attr('data-role') != 'submit')
                                    return false;
                                if ($(this).attr('data-role') == 'CLR') {
                                    $("input.pr-qty", mytr).val("0");
                                    trigger_qty_change($("input.pr-qty", mytr));
                                } else {
                                    old_text = $("input.pr-qty", mytr).val();
                                    var new_val = '';
//                console.log(this.innerHTML)
                                    if (old_text.indexOf('.') != -1 && this.innerHTML == '.')
                                        return;
                                    if (selectedStr != '') {
                                        new_val = prefixStr + this.innerHTML + sufixStr;
                                    } else {
                                        new_val = (old_text == '0' ? this.innerHTML : old_text + this.innerHTML);
                                    }
                                    $("input.pr-qty", mytr).val(new_val);
                                    if (this.innerHTML != '.')//since when calculating formula '.' is removed
                                        trigger_qty_change($("input.pr-qty", mytr));

                                }
                            })

                            $("body").on("input", ".pr-qty", function (e) {
//            var old_val = $(this).data("old-val") != undefined ? $(this).data("old-val") : "";
//            console.log(($(this).val().match(/\./g) || []).length + ' === ' + old_val + ' === ' + $(this).val())
//            if (($(this).val().match(/\./g) || []).length > 1) {
//                $(this).val(old_val);
//                $(this).data("old-val", $(this).val());
//                return false;
//            }
//            if (old_val != "") {
//                //if we add only one digit which is '.'
//                if ($(this).val().length == (old_val.length + 1) && $(this).val()[$(this).val().length - 1] == '.')
//                    return false;
//            }
//            $(this).data("old-val", $(this).val());
                                trigger_qty_change($(this));
                            })
                        });
                        function change_template() {
//        $("#cancel_btn").removeClass("hidden")
                            $("#template_nb").val('')
                            $(".template_id").removeClass("btn-info").addClass("btn-default")
                            template_id = 0;
                            $("#production_template_modal").modal("show")
                            //        $("#template_nb").
                        }
                        function submit_process() {
                            $("#process_loader").removeClass("hidden")
                            var data = {
                                template_id: template_id,
                                line_id: line_id,
                                date: today,
                                total_cost: 0,
                                process_note: '',
                                process_qty: template_qty,
                                Currency_ID: local_currency,
                                items: []
                            };
                            var validate_uom = true, validate_qty = true,
                                    number_pattern = /^\d+(\.\d+)?$/;
                            $(".in-items tbody tr").each(function () {
//            console.log($(this).attr("data-depot"))
                                var qty = $(this).find(".pr-qty").val();
                                if ($(this).find("input.pr-uom").val() != '' && number_pattern.test(qty) && qty > 0) {
                                    data.items.push({
                                        item_uom: $(this).find("input.pr-uom").val(),
                                        item_qty: qty,
                                        item_id: $(this).attr("data-id"),
                                        initial_qty: $(this).attr("data-init-qty"),
                                        is_service: $(this).attr("data-service"),
                                        formula: $(this).attr("data-formula"),
                                        identifier: $(this).attr("data-identifier"),
                                        operation: '-',
                                        item_cost: 0,
                                        item_depot: $(this).attr("data-depot") !== undefined ? $(this).attr("data-depot") : depot_id
                                    })
                                } else {
                                    if ($(this).find("input.pr-uom").val() == '')
                                        validate_uom = false;
                                    else
                                        validate_qty = false;
                                }
                            })
                            $(".out-items tbody tr").each(function () {
                                var qty = $(this).find(".pr-qty").val();

                                if ($(this).find("input.pr-uom").val() != '' && number_pattern.test(qty) && qty > 0) {
                                    data.items.push({
                                        item_uom: $(this).find("input.pr-uom").val(),
                                        item_qty: qty,
                                        item_id: $(this).attr("data-id"),
                                        initial_qty: $(this).attr("data-init-qty"),
                                        is_service: $(this).attr("data-service"),
                                        formula: $(this).attr("data-formula"),
                                        identifier: $(this).attr("data-identifier"),
                                        operation: '+',
                                        item_cost: 0,
                                        item_depot: $(this).attr("data-depot") !== undefined ? $(this).attr("data-depot") : depot_id
                                    })
                                } else {
                                    if ($(this).find("input.pr-uom").val() == '')
                                        validate_uom = false;
                                    else
                                        validate_qty = false;
                                }
                            })
                            if (!validate_uom) {
                                toastr.error(fill_uom_items)
                                return;
                            }
                            if (!validate_qty) {
                                toastr.error('<?php echo CommonLanguage::getMessage('check_item_qty') ?>')
                                return;
                            }
                            if ($(".in-items tbody tr").length == 0 || $(".out-items tbody tr").length == 0) {
                                toastr.error(fill_in_out_items)
                                return;
                            }
                            $.ajax({
                                url: "InventoryAjax/add_production_process",
                                data: data,
                                method: 'post',
                                complete: function (v1, v2) {
                                    if (v2 == "success") {

                                        toastr.success(Submitted_Successfully)
                                        $(".out-items tbody").empty()
                                        $(".in-items tbody").empty()
                                        $(".cards-div").empty()
//                    $("#cancel_btn").addClass("hidden")
                                        $("#template_nb").val('')
                                        $(".template_id").removeClass("btn-info").addClass("btn-default")
                                        template_id = 0;
                                        line_id=0;
                                        $("#production_template_modal").modal("show")
                                        $("#process_loader").addClass("hidden")

                                    } else {
                                        toastr.error(Failed_Submit)
                                    }
                                }
                            })
                        }

                        function build_templates(data) {
                            var html = '';
                            $.each(data, function (indx, val) {
                                html += '<div class="btn-group col-xs-12 col-sm-6 col-md-3 col-lg-3  fn-btn m-b-10">' +
                                        '<button type="button" class="btn btn-default w-100  template_id text-center"  >' +
                                        '<span class="f-s-10 font-montserrat  temp-card" data-id="' + val['template_id'] + '" data-required="' + val['is_line_required'] + '">' + val['template_name'] + '</span>' +
                                        '</button>' +
                                        '</div>';
                            })
                            html += '<div class="btn-group col-xs-12 col-sm-6 col-md-3 col-lg-3  fn-btn m-b-10">' +
                                    '<button type="button" class="btn btn-default w-100  back_cat text-center"  >' +
                                    '<span class=" fa fa-arrow-left  " ></span>' +
                                    '</button>' +
                                    '</div>';
                            html = $(html);
                            $("#temp_main_div").empty().append(html)
                        }
                        function build_cat_templates(data) {
                            var html = '';
                            $.each(data, function (indx, val) {
                                html += '<div class="btn-group col-xs-12 col-sm-6 col-md-3 col-lg-3  fn-btn m-b-10">' +
                                        '<button type="button" class="btn btn-' + (val['is_cat'] == 1 ? 'primary' : 'default') + ' w-100  ' + (val['is_cat'] == 1 ? 'template_cat' : 'template_id') + ' text-center"  >' +
                                        '<span class="f-s-10 font-montserrat  temp-card cat-card" data-id="' + val['id'] + '" data-required="' + val['is_line_required'] + '">' + val['name'] + '</span>' +
                                        '</button>' +
                                        '</div>';
                            })

                            html = $(html);
                            $("#temp_main_div").empty().append(html)
                        }
                        function trigger_qty_change(me, is_auto) {
                            if (typeof (is_auto) == undefined || !is_auto) {
                                calculated_vars = [];
                                loop_count = 0;
                            }
                            var identifier = me.parents("tr").attr("data-identifier");
                            calculate_formulas(identifier);
                        }
                        function calculate_formulas(identifier) {
                            var id_arr = variables[identifier];
                            if (id_arr == undefined)
                                id_arr = [];
                            $.each(id_arr, function (indx, id) {
                                try {
                                    loop_count++;
                                    calculate_id_value(id);
                                } catch (e) {
                                    return false;   //break
                                }
                            });
                            //
                            if (loop_count > max_loop)
                                alert('too many recursions..');
                            else {
//            console.log(row_val)
                                $.each(row_val, function (indx, value) {
                                    value = parseFloat(value) || 0;
                                    if (loop_count > max_loop)
                                        return false;   //break
                                    if ($(".cur_val[data-indx=" + indx + "]").parents("tr").attr("data-formula") != "")
                                        $(".cur_val[data-indx=" + indx + "]").val(round_number(value, 3));
                                    if (!calculated_vars.includes(indx)) {//to check if value set before then do not trigger the change of value
                                        calculated_vars.push(indx);
                                        trigger_qty_change($(".cur_val[data-indx=" + indx + "]"), true);
                                    }
                                });

                            }
                        }


                        function calculate_id_value(identifier) {
                            //
                            id_val[identifier] = 0;
//        row_val[e]=0;
//console.log($(".AddRow[data-identifier=" + identifier + "] input.cur_val"))
                            $("tr[data-identifier=" + identifier + "] .cur_val").each(function () {
//            console.log(e)
//            console.log($(this))
//            row_val[e]=0;
                                var parent = $(this).parents("tr");
                                if (parent.attr("data-formula") != '') {
                                    var id_arr = id_content[identifier];
                                    if (id_arr != undefined) {
                                        $.each(id_arr, function (indx, id) {
                                            id_val[id] = calculate_id_value(id)
                                        });
                                    }
                                    var formula = parent.attr("data-formula");
                                    $.each(id_val, function (indx, value) {
                                        formula = formula.replace(new RegExp(indx, "g"), value)
                                    });
                                    try {
                                        id_val[identifier] += eval(formula);
                                        row_val[$(this).attr("data-indx")] = eval(formula);
                                    } catch (e) {
                                        alert("Error Evaluate Formula: [Identifier: " + identifier + "]\r\nMain Formula: " + parent.attr("data-formula") + "\r\nEval Formula: " + formula + "\r\nError: " + e)
                                        throw 'error_eval_formula';
                                    }
                                } else {
                                    id_val[parent.attr("data-identifier")] += (parseFloat($(this).val()) || 0);
                                    if (isNaN($(this).val()))
                                        $(this).val(parseFloat($(this).val()) || 0);
                                    row_val[$(this).attr("data-indx")] = (parseFloat($(this).val()) || 0)
                                }
                            });
                            return id_val[identifier];
                        }
                        function get_next_indx() {
                            var maximum = 0;
                            $('.cur_val').each(function () {
                                var value = parseFloat($(this).attr('data-indx'));
                                maximum = (value > maximum) ? value : maximum;
                            });
                            return (maximum + 1);
                        }
                        function set_needed_items(products) {

                            for (var i = 0; i < products.length; i++) {
                                var card_row = products[i];
                                var card = $(card_temp);
                                card.attr("data-service", card_row['is_service']);
                                card.attr("data-id", card_row['Product_ID']);
                                card.attr("data-depot", card_row['Depot_ID']);
                                card.attr("data-name", card_row['Product_Name'])
                                card.attr("data-code", card_row['Product_Code'])
                                card.attr("data-uom", card_row['default_view_uom_id'])
                                card.attr("data-uom-name", card_row['UOM_Name'])
                                card.attr("data-formula", card_row['formula'])
                                card.attr("data-identifier", card_row['new_identifier'])
                                card.attr("data-init-qty", card_row['current_quantity'])
                                $(".card-name", card).html(card_row['Product_Name'])
                                card.appendTo($(".cards-div"));
                            }
                        }
                        function set_needed_groups(groups, type) {
                            for (var i = 0; i < groups.length; i++) {
                                var group_name = groups[i];
                                var card = $(card_temp);
                                card.removeClass("prod-card").addClass("group-card")
                                card.find('.product_divs').removeClass("product_divs").addClass("group_divs")
//                            card.attr("data-service", card_row['is_service']);
                                card.attr("data-name", group_name)
                                $(".card-name", card).html(group_name)
                                if (type == 'in')
                                    card.appendTo($(".cards-div"));
                                else
                                    card.appendTo($(".prod-cards-div"));
                            }
                        }
                        function set_finished_items(products) {
                            for (var i = 0; i < products.length; i++) {
                                var card_row = products[i];
                                var card = $(card_temp);
                                card.attr("data-service", card_row['is_service']);
                                card.attr("data-id", card_row['Product_ID']);
                                card.attr("data-depot", card_row['Depot_ID']);
                                card.attr("data-name", card_row['Product_Name'])
                                card.attr("data-code", card_row['Product_Code'])
                                card.attr("data-uom", card_row['default_view_uom_id'])
                                card.attr("data-uom-name", card_row['UOM_Name'])
                                card.attr("data-formula", card_row['formula'])
                                card.attr("data-identifier", card_row['new_identifier'])
                                card.attr("data-init-qty", card_row['current_quantity'])
                                $(".card-name", card).html(card_row['Product_Name'])
                                card.appendTo($(".prod-cards-div"));
                            }
                        }
</script>