<script type="text/javascript">
    $(document).on("keyup","#amount_all_house_used",function(){
        $(".amount-house-used").html($("#amount_all_house_used").val()+" houses");
    });
    var data_detail = <?php echo json_encode($data_detail); ?>;
    var product_get = <?php echo json_encode($product_get); ?>;
    function get_boq_detail(boq_id,title){
        var route = "<?php echo e(route('construction.boq.get_edit_product_info')); ?>";
        var tr_body="";
        $.ajax({
            url:route,
            type:"POST",
            dataType:"JSON",
            async: false,
            data:{
                boq_id:boq_id,
                title:title,
                "_token":"<?php echo e(csrf_token()); ?>"
            },
            success:function(data)
            {
                
                $.each(data,function(ind,val){
                    var button = ``;
                    var product ="<option value=''>Please Select</option>";
                    if(ind==0){
                        button = `<button type="button" class="btn btn-sm btn-danger" disabled>
                                    <span class="fa fa-trash"></span></button>`;
                    }else{
                        button = `<button type="button" class="btn btn-sm btn-danger">
                        <span class="fa fa-trash" onclick="remove(this)"></span></button>
                    `;
                    }
                    $.each(product_get,function(i,v){
                        if(v.id==val.product_id){
                            product +=`<option selected value="${v.id}">${v.name}</option>`;
                        }else{
                            product +=`<option value="${v.id}">${v.name}</option>`;
                        }
                    });
                    tr_body+=`<tr>
                                <td width="4%">
                                    <span>${ind+1}</span>
                                </td>
                                <td width="12%">
                                    <select name="product_id[]" class="form-control select2" onchange="selected_product(this)">
                                        ${product}
                                    </select>
                                </td>
                                <td width="8%">
                                    <input type="text" class="form-control" value="${val.subcategory_name}" name="subcategory[]" readonly="readonly">
                                </td>
                                <td width="6%">
                                    <input type="text" class="form-control" name="unit[]" value="${val.unit_name}" readonly="readonly">
                                </td>
                                <td>
                                    <input type="text" class="form-control number-only" required value="${(val.specific?val.qty_used_one_house:'')}" name="qty_used_one_house[]" onchange="calculate_qty_using_all_house(this,'one_house_press_key')" ${(val.specific?'':'readonly')}>
                                </td>
                                <td>
                                    <input type="text" class="form-control number-only" required value="${(val.specific?val.loss_percentage:'')}" name="loss_percentage[]" onchange="calculate_qty_using_all_house(this,'loss_press_key')" ${(val.specific?'':'readonly')}>
                                </td>
                                <td>
                                    <input type="text" class="form-control number-only" required value="${(val.specific?val.qty_used_all_amount_of_house:'')}" name="qty_used_all_amount_of_house[]" ${(val.specific?'':'readonly')}>
                                </td>
                                <td>
                                    <input type="hidden" class="form-control" name="title[]" value="${(val.title?val.title:'')}">
                                    <textarea name="description[]" placeholder="Description" class="form-control" rows="2">${val.description==null?"":val.description}</textarea>
                                </td>
                                <td>
                                    <input type="hidden" name="specific_status[]" value="${val.specific}" class="input-status">
                                    <label class="checkbox-list">
                                        <input type="checkbox" name="specific[]" value="1" class="specific" ${(val.specific?"checked":"")}>
                                        <span class="checkmark"></span>
                                    </label>
                                </td>
                                <td>
                                    ${button}
                                </td>
                            </tr>`;
                });
                
            }
        });
        return tr_body;
    }
    $(document).ready(function() {
        var boq_table_form = "";
        $.each(data_detail,function(index,value){
            var head_div="";
            if(index==0){
                head_div="";
            }else{
                head_div = `<div style="border: 1px solid gray;height:1px;margin-bottom:35px;"></div>
                            <p style="color: #045FB4 !important;font-size: 90%;margin-top: -30px;background-color: white !important;
                                width: 90px !important;text-align: center;font-family: 'Khmer OS Muol Light';position: absolute;right:30px;" >
                                <span class="button_danger btn-sm plus_ens" style="cursor:pointer;" onclick="$(this).closest('div').remove()">Remove</span>
                            </p>`;
            }
            
             boq_table_form += `<div class="row table-responsive" style="padding:15px;">
                                    ${head_div}
                                    <div class="col-sm-4" style="padding: 0px;" > <label>Title : </label><input class="form-control" name="t[]" placeholder="Title" value="${value.title==null?"":value.title}" id="title-resultbody${index+1}" onkeyup="title_press_key(this)" onchange="title_press_key(this)">
                                            <br/>
                                        </div>
                                        <table class="table table-striped table-bordered nowrap" width="100%">
                                            <thead>
                                                <tr>
                                                    <th>No</th>
                                                    <th>
                                                        <label class="required">
                                                            Product Name
                                                        </label>
                                                    </th>
                                                    <th style="min-width: 200px;">
                                                        <label class="required">
                                                            Sub Category
                                                        </label>
                                                    </th>
                                                    <th style="min-width: 100px;">
                                                        <label class="required">
                                                            Unit
                                                        </label>
                                                    </th>
                                                    <th>
                                                        <label class="required">
                                                            Qty of using for one house
                                                        </label>
                                                    </th>
                                                    <th>
                                                        <label class="required">
                                                            Loss Percentage(%)
                                                        </label>
                                                    </th>
                                                    <th>
                                                        <label class="required">
                                                            Qty of using for <span class="amount-house-used"></span>
                                                        </label>
                                                    </th>
                                                    <th style="min-width: 200px;">Other</th>
                                                    <th>Specific</th>
                                                    <th>
                                                        <span class="pull-right button_primary btn-sm plus_ens fa fa-plus" onclick="add_row_product(this)"></span>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody class="resultbody${index+1}">
                                                ${get_boq_detail(value.boq_id,value.title)}
                                            </tbody>
                                        </table>
                                    </div>`;
        });
        $("#boq-table-form").append(boq_table_form);
        $(".select2").select2();
        $(".amount-house-used").html($("#amount_all_house_used").val());
    });
    function add_table_boq(obj)
    {
        var count_table = $("#boq-table-form").find("table").length;
        var div = `<div class="row table-responsive" style="padding:15px;">
                    <div style="border: 1px solid gray;height:1px;margin-bottom:35px;"></div>
                    <p style="color: #045FB4 !important;font-size: 90%;margin-top: -30px;background-color: white !important;
                        width: 90px !important;text-align: center;font-family: 'Khmer OS Muol Light';position: absolute;right:30px;" >
                        <span class="button_danger btn-sm plus_ens" style="cursor:pointer;" onclick="$(this).closest('div').remove()">Remove</span>
                    </p>
                    <div class="col-sm-4" style="padding: 0px;" > <label>Title : </label><input class="form-control" name="t[]" placeholder="Title" id="title-resultbody${count_table+1}" onkeyup="title_press_key(this)" onchange="title_press_key(this)">
                        <br/>
                    </div>
                    <table class="table table-striped table-bordered nowrap" width="100%">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>
                                    <label class="required">
                                        Product Name
                                    </label>
                                </th>
                                <th style="min-width: 200px;">
                                    <label class="required">
                                        Sub Category
                                    </label>
                                </th>
                                <th style="min-width: 100px;">
                                    <label class="required">
                                        Unit
                                    </label>
                                </th>
                                <th>
                                    <label class="required">
                                        Qty of using for one house
                                    </label>
                                </th>
                                <th>
                                    <label class="required">
                                        Loss Percentage(%)
                                    </label>
                                </th>
                                <th>
                                    <label class="required">
                                        Qty of using for <span class="amount-house-used"></span>
                                    </label>
                                    
                                </th>
                                <th style="min-width: 200px;">Other</th>
                                <th colspan='2'>
                                    <span class="pull-right button_primary btn-sm plus_ens fa fa-plus" onclick="add_row_product(this)"></span>
                                </th>
                            </tr>
                        </thead>
                        <tbody class="resultbody${count_table+1}">
                            <tr>
                                <td width="4%">
                                    <span>1</span>
                                </td>
                                <td width="12%">
                                    <select name="product_id[]" class="form-control select2" onchange="selected_product(this)">
                                        <?php echo $products; ?>

                                    </select>
                                </td>
                                <td width="8%">
                                    <input type="text" class="form-control" name="subcategory[]" readonly="readonly">
                                </td>
                                <td width="6%">
                                    <input type="text" class="form-control" name="unit[]" readonly="readonly">
                                </td>
                                <td width="15%">
                                    <input type="text" class="form-control number-only" required name="qty_used_one_house[]" onchange="calculate_qty_using_all_house(this,'one_house_press_key')">
                                </td>
                                <td width="15%">
                                    <input type="text" class="form-control number-only" required name="loss_percentage[]" onchange="calculate_qty_using_all_house(this,'loss_press_key')">
                                </td>
                                <td width="15%">
                                    <input type="text" class="form-control number-only" required name="qty_used_all_amount_of_house[]">
                                </td>
                                <td>
                                    <input type="hidden" class="form-control" name="title[]">
                                    <?php echo Form::textarea('description[]', null, array('placeholder' => 'Description','class' => 'form-control','rows'=>'2')); ?>

                                </td>
                                <td>
                                    <input type="hidden" name="specific_status[]" value="1" class="input-status">
                                    <label class="checkbox-list">
                                        <input type="checkbox" name="specific[]" value="1" class="specific" checked>
                                        <span class="checkmark"></span>
                                    </label>
                                </td>
                                <td><button class="btn btn-sm btn-danger" disabled>
                                    <span class="fa fa-trash"></span></button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>`;
        $("#boq-table-form").append(div);
        $(".select2").select2();
        $(".amount-house-used").html($("#amount_all_house_used").val()+" houses");
    }
    function add_row_product(obj)
    {
        var tr_class =  $(obj).closest("table").find('tbody').attr('class');
        var tr = `<tr class="tr-table-${tr_class}">
                    <td width="4%">
                        <span>${ $(obj).closest("table").find("tbody").find("tr").length+1}</span>
                    </td>
                    <td width="12%">
                        <select name="product_id[]" class="form-control select2" onchange="selected_product(this)">
                            <?php echo $products; ?>

                        </select>
                    </td>
                    <td width="8%">
                        <input type="text" class="form-control" name="subcategory[]" readonly="readonly">
                    </td>
                    <td width="6%">
                        <input type="text" class="form-control" name="unit[]" readonly="readonly">
                    </td>
                    <td width="15%">
                        <input type="text" class="form-control number-only" required name="qty_used_one_house[]" value="0" onchange="calculate_qty_using_all_house(this,'one_house_press_key')">
                    </td>
                    <td width="15%">
                        <input type="text" class="form-control number-only" required name="loss_percentage[]" value="0" onchange="calculate_qty_using_all_house(this,'loss_press_key')">
                    </td>
                    <td width="15%">
                        <input type="text" class="form-control number-only" required name="qty_used_all_amount_of_house[]" value="0">
                    </td>
                    <td>
                        <input type="hidden" class="form-control" name="title[]">
                        <?php echo Form::textarea('description[]', null, array('placeholder' => 'Description','class' => 'form-control','rows'=>'2')); ?>

                    </td>
                    <td>
                        <input type="hidden" name="specific_status[]" value="1" class="input-status">
                        <label class="checkbox-list">
                            <input type="checkbox" name="specific[]" value="1" class="specific" checked>
                            <span class="checkmark"></span>
                        </label>
                    </td>
                    <td><button type="button" class="btn btn-sm btn-danger">
                        <span class="fa fa-trash" onclick="remove(this)"></span></button>
                    </td>
                </tr>`;

        var table = $(obj).closest("table");
            
        $(table).find("tbody").append(tr);
        var title = $("#title-"+tr_class).val();
        get_title(table,title);
        $(".select2").select2();
    }
    function remove(obj)
    {
        var index = 1;
        var tr_class =  $(obj).closest("table").find('tbody').attr('class');
        $(obj).closest('tr').remove();
        $("tr.tr-table-"+tr_class).each(function(){
            $(this).find('td:eq(0)').html(`<span>${++index}</span>`);
        });
    }
    function selected_product(obj){
        var id = $(obj).val();
        if(id==""){

        }else{
            $("#main-spinner").show();
        }
        
        var route = "<?php echo e(route('construction.boq.get_product_info',':id')); ?>";
        route = route.replace(":id",id);
        $.ajax({
            url:route,
            dataType:"JSON",
            type:"GET",
            success:function(data){
                $("#main-spinner").hide();
                $(obj).closest('tr').find("td:eq(2)").find("input").val(data.subcategory_name);
                $(obj).closest('tr').find("td:eq(3)").find("input").val(data.unit_name);
            },
            error:function(){
                $(obj).closest('tr').find("td:eq(2)").find("input").val("");
                $(obj).closest('tr').find("td:eq(3)").find("input").val("");
            }
        });
    }
    function get_title(table_obj,title){
        $(table_obj).find("tbody").find("tr").each(function(){
            $(this).find("td:eq(7)").find('input').first().val(title);
        });
    }
    function title_press_key(obj){
        var id_name = $(obj).attr("id");
        var title_value = $(obj).val();
        var table_name_class = id_name.split("-")[1];
        var table = $("tbody."+table_name_class).closest("table");
        get_title(table,title_value);
    }
    function calculate_qty_using_all_house(obj,witch)
    {
        var one_house_value = 0;
        var loss_value = 0;
        var result = 0;
        var amount_all_house = Number($("#amount_all_house_used").val());
        if(witch=="one_house_press_key"){
            one_house_value = Number($(obj).val());
            loss_value = Number($(obj).closest('tr').find("td:eq(5)").find('input').val());
        }
        else{
            loss_value = Number($(obj).val());
            one_house_value = Number($(obj).closest('tr').find("td:eq(4)").find('input').val());
        }
        result = Number((Number(one_house_value)+(Number(one_house_value)*Number(loss_value/100)))*Number(amount_all_house));
        $(obj).closest('tr').find('td:eq(6)').find('input').val(result);
    }
    $(document).on('change','.specific',function(){
        var tr      = $(this).closest('tr');
        var status  = false;
        if($(this).is(':checked')){
            status  = true;
            $(this).closest("td").find("input.input-status").val(1);
        }else{
            $(this).closest("td").find("input.input-status").val("");
        }

        if(status === true){
            tr.find('td').each(function(){
                $(this).find('input[name="qty_used_one_house[]"],input[name="loss_percentage[]"],input[name="qty_used_all_amount_of_house[]"]').prop('required',true).prop('readOnly',false);
            });
        }else{
            tr.find('td').each(function(){
                $(this).find('input[name="qty_used_one_house[]"],input[name="loss_percentage[]"],input[name="qty_used_all_amount_of_house[]"]').removeAttr('required').prop('readOnly',true).val('');
            });
        }
    });
</script>