<?php
if ($permissions->hasPermission('add_production_process')) {
    include("Views/Maintenance/add_production_process.php");
}
?>
<div id="test2"></div>
<style>
    <?php   foreach( $color as $key => $value ){ ?>
       
      <?php  echo  ".color_".$value['position_name']."{
        background-color: ".$value['color_name'].";
    }";
    ?>
    <?php } ?>
</style>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"> <?php print CommonLanguage::getMessage('production_process'); ?></div>
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <div class="row">
                <?php echo Forms::FloatingAddButton('652d90', '#add_production_process', CommonLanguage::getMessage('add')); ?>
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('Date') ?></label>
                    <div class="input-group">
                        <span class="input-group-addon bg-success-dark"><i class="fa fa-calendar"></i></span>
                        <input id="From_To_Date" type="text" class="form-control" name="From_To_Date" autocomplete="off" >
                    </div>
                </div> 
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('barcode'); ?></label>
                    <input  id="barcode" name="barcode" type="hidden" class="full-width salesman " />
                </div>

            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="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" style="width:15%" ><?php print CommonLanguage::getMessage('Date'); ?></th>
                                    <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center no-print" style="width:15%"><?php print CommonLanguage::getMessage('state'); ?></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>
</div>
<iframe id="barcode_frame" name="ifrm" style="width:0;height:0;visibility: hidden;" ></iframe>


<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('production_template')) ?>,
            activate_lot = <?php echo json_encode(smc_session()['default_setting']['activate_product_lot_nb']); ?>,
            activate_serial = <?php echo json_encode(smc_session()['default_setting']['activate_product_serial_nb']); ?>,
            activate_expiry_date = <?php echo json_encode(smc_session()['default_setting']['activate_expiry_date']); ?>;
    var IsEdit = false,
            IDToEdit = null;
    $(function () {
        changetable()
        build_select2($("#barcode"), "xhr/CommonSearch?col_name=barcode_nb&col_id=barcode_nb&table=tbl_production_process");
        $('#barcode').on('change', function () {
            changetable();
        });
        $("input[name=From_To_Date]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }, locale: {
                cancelLabel: 'Clear'
            }, allowEmpty: false,
            autoUpdateInput: false
        });

        $("input[name=From_To_Date]").on('apply.daterangepicker', function (ev, picker) {
            window.startDate = picker.startDate.format('YYYY-MM-DD'),
                    window.endDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            changetable();
        });
        $("input[name=From_To_Date]").on('cancel.daterangepicker', function (ev, picker) {
            window.startDate = ''
            window.endDate = ''
            $(this).val('');
            changetable();
        });

        $(".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"))
            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_process .add-label").removeClass("hidden")
            $("#slide2").removeClass("active")
            $("#slide1").addClass("active")
        })
        //        RebuildDataTable(title, [0], "InventoryAjax/production_template_list")
        //get_production_template_id
        $("#tableWithSearch tbody").on("click", ".Edit", function () {
            IsEdit = true;
            IDToEdit = $(this).attr("data-id");
            $("#add_production_process .edit-label").removeClass("hidden")
            $.ajax({
                url: "InventoryAjax/get_production_process_id",
                method: "GET",
                dataType: "json",
                data: {id: IDToEdit},
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        var mydata = v1.responseJSON;
                        variables = mydata['variables'];
                        id_val = mydata['id_val'];
                        id_content = mydata['id_content'];
                        $("#template_id").val(mydata['main']['template_id']).attr("data-select-name", mydata['main']['template_name'])
                        build_select2($("#template_id"), ("xhr/templateSearch"))
                        build_select2($("#optional_need_items"), "xhr/opt_temp_prod_search?is_needed=1&template_id=" + mydata['main']['template_id'])
                        build_select2($("#optional_prod_items"), "xhr/opt_temp_prod_search?is_needed=0&template_id=" + mydata['main']['template_id'])

                        $("#process_date").val(mydata['main']['date'])
                        $("#process_qty").val(mydata['main']['process_quantity'])
                        $("#process_note").val(mydata['main']['process_note'])
                        $("#CurrencyDropDown button input").val(mydata['main']['Currency_ID'])
                        $("#CurrencyDropDown button span").html(mydata['main']['Currency_Name'] + " - " + mydata['main']['Currency_Symbol'])
                        
                        $('#line_id').val(mydata['main']['line_id']);
                        $('#line_id').attr('data-select-name', mydata['main']['line_name']);
                        build_select2($("#line_id"), "xhr/CommonSearch?col_name=line_name&col_id=line_id&table=tbl_line");

                        $('#production_color').val(mydata['main']['id']);
                        $('#production_color').attr('data-select-name', mydata['main']['position_name']);
                        build_select2($("#production_color"), "xhr/commonSearch?table=tbl_production_color&col_id=id&col_name=position_name");

                        $('#states_name').val(mydata['main']['states_name']);
                        $('#states_name').attr('data-select-name', mydata['main']['states_name']);
                        build_select2($("#states_name"), "xhr/CommonSearch?col_name=state_name&col_id=state_name&table=tbl_production_process_states");
                        
                        if($('#states_name').val()== 'Finished'){
                            $('#submit_pro').css('display', 'none');
                        }
                        $("#CurrencyDropDown").attr("data-symbol", mydata['main']['Currency_Symbol'])
                        //                        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")
                        //
                        //                            }
                        //                        }
                        var details = mydata['details'],
                                plus_array = mydata['plus'],
                                minus_array = mydata['minus'],
                                expenses = mydata['expense'],
                                production_emp_type = mydata['employee_type'],
                                out_row = $("#out_items .AddRow:eq(0)").clone(),
                                in_row = $("#in_items .AddRow:eq(0)").clone(),
                                production_emp_type_row = $("#production_emp_type_div .AddRow:eq(0)").clone(),
                                out_expiry_row = $('#out_items .AddRow .out_items_expiry .out_items_expiry_row:eq(0)').clone(),
                                in_expiry_row = $('#in_items .AddRow .in_items_expiry .in_items_expiry_row:eq(0)').clone(),
                                ex_row = $("#template_expenses .AddRow:eq(0)").clone();

                        $("#out_items,#in_items,#template_expenses").empty();
                        var row_indx = 0;
                        $.each(plus_array, function (i, value) {
                            var expiry_data = plus_array[i]['details'], is_product_has_expiry = plus_array[i]['is_expiry'];
                            out_row = (out_row === null ? $("#out_items .AddRow:eq(0)").clone() : out_row);
                            $("#out_items").append(out_row)
                            out_row.find(".out_prod_name").html(plus_array[i]['Product_Name'] + " (" + plus_array[i]['initial_current_quantity'] + " " + plus_array[i]['UOM_Name'] + ")");
                            $(out_row).find('.out_items_expiry').empty();
                            $.each(expiry_data, function (j, value) {
                                out_expiry_row = (out_expiry_row === null ? $("#out_items .AddRow .out_items_expiry .out_items_expiry_row:eq(0)").clone() : out_expiry_row);
                                $('.out_items_expiry', out_row).append(out_expiry_row)
                                $(".select2-container", out_expiry_row).empty().remove()
                                out_expiry_row.attr("data-prod", expiry_data[j]['Product_ID'])
                                out_expiry_row.attr("data-uom", expiry_data[j]['UOM_ID'])
                                out_expiry_row.attr("data-service", expiry_data[j]['is_service'])
                                out_expiry_row.attr("data-is-serial", expiry_data[j]['is_serial'])
                                out_expiry_row.attr("data-is-lot", expiry_data[j]['is_lot'])
                                out_expiry_row.attr("data-is-expiry", expiry_data[j]['is_expiry'])
                                out_expiry_row.attr("data-depot-val", expiry_data[j]['Depot_ID'])
                                out_row.attr("data-formula", expiry_data[j]['formula'])
                                out_row.attr("data-identifier", expiry_data[j]['identifier'])
                                out_expiry_row.find("input[name=out_depot]").val(expiry_data[j]['Depot_ID']).attr("data-select-name", expiry_data[j]['Depot_Name'])
                                build_select2(out_row.find("input[name=out_depot]"), "xhr/depotSearch")
                                out_expiry_row.find(".out_qty").val(expiry_data[j]['current_quantity'])
                                out_expiry_row.find(".out_qty").attr("data-qty", expiry_data[j]['initial_current_quantity'])
                                out_expiry_row.find(".out_qty").attr("data-indx", row_indx++);
                                if (expiry_data[j]['formula'] != '') {
                                    out_expiry_row.find(".out_qty").prop('readonly', true)
                                    out_expiry_row.find(".edit_row_qty").removeClass('hidden')
                                } else {
                                    out_expiry_row.find(".out_qty").prop('readonly', false)
                                    out_expiry_row.find(".edit_row_qty").addClass('hidden')
                                }
                                out_expiry_row.find(".out_cost").val(expiry_data[j]['cost']);
                                if (is_product_has_expiry == 1) {
                                    $("input[name=out_expiry_date]", out_expiry_row).val(expiry_data[j]['expiry_date']).removeClass('hidden').datepicker({autoclose: true});
                                    $("input[name=out_expiry_date]", out_expiry_row).datepicker({autoclose: true});
//                                    $("input[name=out_expiry_date]", out_expiry_row).val(expiry_data[j]['expiry_date']).attr('data-select-name', expiry_data[j]['expiry_date'])
//                                    build_select2($("input[name=out_expiry_date]", out_expiry_row), "xhr/get_product_expiry?product_id=" + expiry_data[j]['Product_ID']);

                                } else {
                                    out_expiry_row.find("input[name=out_expiry_date]").addClass('hidden')
                                }
                                if (plus_array[i]['is_lot'] == 1) {
                                    $("input.out_lot", out_expiry_row).removeClass('hidden')
                                    $("input.out_lot", out_expiry_row).val(expiry_data[j]['lot_nb'])
//                                    build_select2($("input.out_lot", out_expiry_row), "xhr/get_product_lot?product_id=" + expiry_data[j]['Product_ID']);

                                } else {
                                    out_expiry_row.find("input.out_lot").addClass('hidden')
                                }
                                if (plus_array[i]['is_serial'] == 1) {
                                    $("input.out_serial", out_expiry_row).removeClass('hidden')
                                    $("input.out_serial", out_expiry_row).val(expiry_data[j]['serial_nb'])
//                                    build_select2($("input.out_serial", out_expiry_row), "xhr/get_product_serial?product_id=" + expiry_data[j]['Product_ID']);

                                } else {
                                    out_expiry_row.find("input.out_serial").addClass('hidden')
                                }
                                $(".select2-container", out_row).show();
                                out_expiry_row = null;
                            });
                            out_row = null;
                        })
                        $.each(minus_array, function (i, value) {
                            var expiry_data = minus_array[i]['details'], is_product_has_expiry = minus_array[i]['is_expiry'];
                            in_row = (in_row === null ? $("#in_items .AddRow:eq(0)").clone() : in_row);
                            $("#in_items").append(in_row)
                            in_row.find(".in_prod_name").html(minus_array[i]['Product_Name'] + " (" + minus_array[i]['initial_current_quantity'] + " " + minus_array[i]['UOM_Name'] + ")")
                            $(in_row).find('.in_items_expiry').empty();
                            $.each(expiry_data, function (j, value) {
                                in_expiry_row = (in_expiry_row === null ? $("#in_items .AddRow .in_items_expiry .in_items_expiry_row:eq(0)").clone() : in_expiry_row);
                                $('.in_items_expiry', in_row).append(in_expiry_row)
                                $(".select2-container", in_expiry_row).empty().remove()
                                in_expiry_row.attr("data-prod", expiry_data[j]['Product_ID'])
                                in_expiry_row.attr("data-uom", expiry_data[j]['UOM_ID'])
                                in_expiry_row.attr("data-service", expiry_data[j]['is_service'])
                                in_expiry_row.attr("data-is-serial", expiry_data[j]['is_serial'])
                                in_expiry_row.attr("data-is-lot", expiry_data[j]['is_lot'])
                                in_expiry_row.attr("data-is-expiry", expiry_data[j]['is_expiry'])
                                in_expiry_row.attr("data-depot-val", expiry_data[j]['Depot_ID'])
                                in_row.attr("data-formula", expiry_data[j]['formula'])
                                in_row.attr("data-identifier", expiry_data[j]['identifier'])
                                in_expiry_row.find("input[name=in_depot]").val(expiry_data[j]['Depot_ID']).attr("data-select-name", expiry_data[j]['Depot_Name'])
                                build_select2(in_row.find("input[name=in_depot]"), "xhr/depotSearch")
                                in_expiry_row.find(".in_qty").val(expiry_data[j]['current_quantity'])
                                in_expiry_row.find(".in_qty").attr("data-qty", expiry_data[j]['initial_current_quantity'])
                                in_expiry_row.find(".in_qty").attr("data-indx", row_indx++);
                                if (expiry_data[j]['formula'] != '') {
                                    in_expiry_row.find(".in_qty").prop('readonly', true)
                                    in_expiry_row.find(".edit_row_qty").removeClass('hidden')
                                } else {
                                    in_expiry_row.find(".in_qty").prop('readonly', false)
                                    in_expiry_row.find(".edit_row_qty").addClass('hidden')
                                }
                                in_expiry_row.find(".in_cost").val(expiry_data[j]['cost']);
                                if (is_product_has_expiry == 1) {
                                    $("input[name=in_expiry_date]", in_expiry_row).val(expiry_data[j]['expiry_date']).attr('data-select-name', expiry_data[j]['expiry_date'])
                                    build_select2($("input[name=in_expiry_date]", in_expiry_row), function () {
                                        return "xhr/get_product_expiry?product_id=" + this.parents('.in_items_expiry_row').attr("data-prod") + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
                                    }, '', 'expiry_width');
                                    in_expiry_row.find("input[name=in_expiry_date]").removeClass('hidden');
                                } else {
                                    in_expiry_row.find("input[name=in_expiry_date]").addClass('hidden')
                                }
                                if (minus_array[i]['is_lot'] == 1) {
                                    $("input.in_lot", in_expiry_row).removeClass('hidden')
                                    $("input.in_lot", in_expiry_row).val(expiry_data[j]['lot_nb']).attr('data-select-name', expiry_data[j]['lot_nb'])
                                    build_select2($("input.in_lot", in_expiry_row), function () {
                                        return "xhr/get_product_lot?product_id=" + this.parents('.in_items_expiry_row').attr("data-prod") + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
                                    }, '', 'expiry_width');

                                } else {
                                    in_expiry_row.find("input.in_lot").addClass('hidden')
                                }
                                if (minus_array[i]['is_serial'] == 1) {
                                    $("input.in_serial", in_expiry_row).removeClass('hidden')
                                    $("input.in_serial", in_expiry_row).val(expiry_data[j]['serial_nb']).attr('data-select-name', expiry_data[j]['serial_nb'])
                                    build_select2($("input.in_serial", in_expiry_row), function () {
                                        return "xhr/get_product_serial?product_id=" + this.parents('.in_items_expiry_row').attr("data-prod") + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
                                    }, '', 'expiry_width');

                                } else {
                                    in_expiry_row.find("input.is_serial").addClass('hidden')
                                }
                                $(".select2-container", in_row).show();
                                in_expiry_row = null;
                            });
                            in_row = null;
                        });
                        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()
                            $("#template_expenses").append(ex_row)
                            $(".select2-container", ex_row).empty().remove()
                            ex_row.attr("data-account", expenses[i]['Account_ID'])
                            ex_row.find("span.exp_account_name").html(expenses[i]['Account_Name'] + " (" + expenses[i]['cost'] + " " + mydata['main']['Currency_Symbol'] + ")")
                            ex_row.find(".expense_cost").val(expenses[i]['cost'])
                            //                            ex_row.find(".is_total").attr("checked", expenses[i]['is_total'] ? "checked" : "")
                            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;
                        }
                        $("#all_items,#template_expenses,#temp_ex").removeClass("hidden");
                        var production_emp_type_arr = mydata['employee_type'];
                        if (production_emp_type_arr.length > 0) {
                            $('#production_emp_type_div').removeClass('hidden');
                            $("#production_emp_type_div .AddRow").remove();
                            for (var i = 0; i < production_emp_type_arr.length; i++) {
                                production_emp_type_row = production_emp_type_row == null ? $("#production_emp_type_div .AddRow:eq(0)").clone() : production_emp_type_row;
                                $("#production_emp_type_div").append(production_emp_type_row);
                                production_emp_type_row.attr('data-id', production_emp_type_arr[i]['type_id']);
                                $('span.production_emp_type_title', production_emp_type_row).html(production_emp_type_arr[i]['type_name']);
                                var employee_row = $('.production_emp_type_row:eq(0)', production_emp_type_row).clone();
                                if ('employees' in production_emp_type_arr[i] && production_emp_type_arr[i]['employees'].length > 0) {
                                    $('.production_emp_type_row', production_emp_type_row).remove();
                                    for (var j = 0; j < production_emp_type_arr[i]['employees'].length; j++) {
                                        var employee_current_val = production_emp_type_arr[i]['employees'][j];
                                        employee_row = employee_row == null ? $('.production_emp_type_row:eq(0)', production_emp_type_row).clone() : employee_row;
                                        $(".production_emp_type_div", production_emp_type_row).append(employee_row)
                                        $(".select2-container", employee_row).remove();
                                        $("input[name=production_emp_cost]", employee_row).val(employee_current_val['cost'])
                                        $("input[name=production_emp_id]", employee_row).val(employee_current_val['employee_id']).attr('data-select-name', employee_current_val['employee_name']);
                                        build_select2($("input[name=production_emp_id]", employee_row), ("xhr/employeeSearch"));
                                        $(".select2-container", employee_row).show();
                                        employee_row = null;
                                    }
                                } else {
                                    $(".select2-container", production_emp_type_row).remove();
                                    $("input", production_emp_type_row).val('');
                                    $('.production_emp_type_row:gt(0)', production_emp_type_row).remove();
                                    build_select2($("input[name=production_emp_id]", production_emp_type_row), ("xhr/employeeSearch"));
                                    $(".select2-container", production_emp_type_row).show();
                                }
                                production_emp_type_row = null;
                            }
                            calculate_emp_total_cost()
                        } else {
                            $('#production_emp_type_div').addClass('hidden')
                            $('#production_emp_type_div .AddRow:gt(0),#production_emp_type_div .AddRow .production_emp_type_row:gt(0)').remove();
                            $('#production_emp_type_div .production_emp_type_row input').val('').trigger('change');
                        }
                        $("#template_expenses .expense_cost").trigger("keyup")
                    }
                }
            })
        })

        $('#tableWithSearch').on('click', '.delete', function () {
            var entry_value = $(this).parents('div.Action').attr('data-id');
            IncludeDeleteModal(common_delete_modal, {process_id: entry_value}, function () {
                changetable()
            }, "InventoryAjax/deleteProductionProcess");
        });
        $('#tableWithSearch').on('click', '.print', function () {
             var data = {production_process_id:  $(this).parents('div.Action').attr('data-id')};
                    $('#barcode_frame').attr('src', "InventoryAjax/print_production_process?" + $.param(data));

        });
 
    })



    function changetable() {
        RebuildDataTable(title, [0, 1], "InventoryAjax/production_process_list",
                {from_date: window.startDate,
                    to_date: window.endDate,barcode:$("#barcode").val()})
    }


</script>