@extends('layouts.app')

@section('title')
Update Work Order
@stop

@section('breadcrumb')
<ol class="breadcrumb pull-right">
        <li><a href="{{route('home')}}"><i class="fa fa-dashboard"></i> Home</a></li>

        <li class="active">Update Work Order</li>
      </ol>
@stop

@section('css')
 <link href="{{asset('css/procurement_css.css')}}" rel="stylesheet">
@stop

@section('content')
  <div class="container-fluid">
  <div class="row">
                    <div class="col-sm-12">
                        <div class="white-box">
                            <h3 class="box-title m-b-0">Update Work Order</h3>
                            <p class="text-muted m-b-30 font-13">  </p>
                            <form class="form-horizontal" method="POST" onsubmit="return addWorkOrder(this)" >
                            	 {{csrf_field()}}
                                <div class="form-group" style="margin-bottom: 25px;">
                             
                                <div class="col-md-6">
                                    <label>Name</label>
                                    <input type="text" class="form-control" placeholder ="Type Task Name ...." value="{{$task->text}}" id="name" name="name">
                                </div>


                                    <div class="col-md-6" style="" id="task_list">
                                        <label>Task List</label>

                                        <div class="row">
                                        <div class="col-md-12">


                                       <select readonly class="form-control chosen-select task_chosen-select" name="category" id="sub_task">
                                        <option value="0">None</option>
                                        @if($tasks->count() > 0  )

                                        @foreach($tasks as $parent_list)
                                         
                                        <optgroup label="{{$parent_list->text}}">

                                        <option <?= ($task->parent == $parent_list->id) ? 'selected' : '' ?> value="{{ $parent_list->id }}">
                                            {{ $parent_list->text }} 
                                         @if(count($parent_list->childs) )

                                            @include('procurement.work-order.child-layout.manage-child-edit',['childs' => $parent_list->childs , 'parent' => $task->parent])
                                         @endif
                                        </option> 
                                       
                                        </optgroup>
                                        
                                        @endforeach
                                    
                                        @endif
                                        </select>

                                            
                                        </div>
   
                                      </div>

                                    </div>

                                   <div id="form_fileds" style="">
                                    <div class="col-md-12" style="margin-top:1rem;">

                                    <center>
                                        <h3 class="us-nav">
                                           Task Details
                                        </h3>
                                    </center>

                                
                                    </div>

                                    <div id="main_form" >

                                        <div class="col-md-4">
                                        <label>Start date</label>
                                        <input readonly type="date" value="{{date('Y-m-d' , strtotime($task->start_date))}}"  id="start_date" class="form-control" name="">
                                        </div>

                                        <div class="col-md-4">
                                        <label>Duration</label>
                                        <input type="text" id="duration"  placeholder="Duration in days" value="{{$task->duration}}" class="form-control" name="">
                                        </div>

                                        <?php
                                        $number_array=['1','2','3','4','5','6','7','8','9'];

                                        $progress = explode('.', $task->progress);

                                        if (!empty($progress[1]) && in_array($progress[1], $number_array)) 
                                        {
                                             $progress = $progress[1] * 1;
                                        }
                                        else if(!empty($progress[1]) && $progress[0] < 1)
                                        {
                                            $progress = $progress[1];
                                        }
                                        else if(!empty($progress[1]) && $progress[0] > 0)
                                        {
                                             $progress = 100;
                                        }
                                        else
                                        {
                                              $progress = 0;
                                        }
                                        ?>

                                        <div class="col-md-4">
                                        <label>Progress <span id="txt_prog"></span>% </label>
                                     
                                        <input type="hidden" value="0" maxlength="3" id="progress" >

                                        <div class="slidecontainer" style="margin-top: 1rem;">
                                        <input type="range" min="0" max="100" value="{{$progress}}" id="myRange">
                                        </div>

                                        </div>

                                        <div class="col-md-6" style="margin-top:1rem;">
                                        <label>Task Type</label>
                                        <select class="form-control" id="task_type">
                                            <option <?= ($task->task_type == 'planed') ? 'selected' : '' ?> value="planed">Planed</option>
                                             <option  <?= ($task->task_type == 'unplaned') ? 'selected' : '' ?> value="unplaned">Unplaned</option>
                                        </select>
                                        </div>


                                         <div class="col-md-6" style="margin-top:1rem;">
                                        <label>Task Priorty</label>
                                        <select class="form-control" id="priorty">

                                            <option <?= ($task->task_priority == 'high') ? 'selected' : '' ?> value="high">
                                               High
                                            </option>

                                             <option  <?= ($task->task_priority == 'normal') ? 'selected' : '' ?>  value="normal">Normal</option>


                                             <option <?= ($task->task_priority == 'low') ? 'selected' : '' ?> value="low">
                                               Low
                                             </option>

                                        </select>
                                        </div>

                                        <div class="col-md-6" style="margin-top:1rem;">
                                        <label>Assign To</label>
                                        <input type="text" value="{{$task->assign_to}}" id="assign_to" placeholder="Assign To" class="form-control" name="">
                                        </div>


                                        <div class="col-md-6" style="margin-top:1rem;">
                                        <label>Created By</label>
                                        <input type="text" readonly="readonly" value="{{$task->created_by}}" id="created_by" placeholder="Created By" class="form-control" name="">
                                        </div>

                                        <div class="col-md-12" style="margin-top:1rem;">
                                        <label>Description</label>
                                        <textarea class="form-control" rows="5" placeholder="type here..." id="description">{{$task->description}}</textarea>
                                        </div>

                                        <div class="col-md-12" style="margin-top:1rem;">
                                            <center>
                                                <h3 class="us-nav">
                                                   Bill Of Quantity
                                                </h3>
                                            </center>
                                        </div>

                                        
                                        <div class="col-md-12">

                                        <div class="alert alert-danger" style="display: none;" id="noItemFound">
                                        <strong style="color: white;">Exception!</strong> No more items found.
                                        </div>

                                    @if($bill_of_quantities->count() > 0)

                                    @foreach($bill_of_quantities as $list)  

                                    @if ($loop->first)
                                    <div class="form-group parent_div" >

                                    @else
                                    <div class="form-group parent parent_div" >
                                    @endif

                                    <div class="col-md-5">
                                      @if ($loop->first) <label>Item</label>@endif
                                    <select class="form-control chosen-select item_list" onchange="return getItemLatestPrice(this)"  name="items[]">
                                    @if($items->count() > 0  )
                                    <option value="0">Select Item</option>

                                    @foreach($items as $item_lists)
                                    <option <?= ($list->item_id == $item_lists->id) ? 'selected' : '' ?> value="{{ $item_lists->id }}">{{ $item_lists->item_name }} - {{ $item_lists->unit }}</option> 
                                    @endforeach
                                    @endif
                                    </select>

                                    </div>
                                 

                                    <div class="col-md-6">

                                    <div class="row">

                                    <div class="col-md-6">
                                      @if ($loop->first)  <label>Quantity</label>@endif
                                    <input type="number" maxlength="6" class="form-control item_qty" placeholder ="Quantity..." value="{{$list->quantity}}" name="quantity[]">
                                   
                                    </div>

                                    <div class="col-md-6">
                                       @if ($loop->first) <label>Rate Per Unit</label>@endif
                                    <input type="text" maxlength="10" class="form-control price" placeholder ="Rate  Per Unit ..." value="{{$list->rate_per_unit}}"   name="price[]">
                                  
                                    </div>
                                    </div>

                                    </div>



                                    <div class="col-md-1"  @if ($loop->first) style="margin-top: 2.5rem;" @endif>

                                    @if ($loop->first)

                                    <button type="button" style="width: 100%;" class="btn btn-success waves-effect waves-light m-r-10 " onclick="return add_new_item(this)"><i class="fa fa-plus" aria-hidden="true"></i></button>

                                    @else

                                    <button type="button" style="width: 100%;" class="btn btn-danger waves-effect waves-light m-r-10 " onclick="return remove_item(this)"><i class="fa fa-trash-o" aria-hidden="true"></i></button>

                                    @endif

                                    </div>

                                    </div>

                                    @endforeach

                                    @else

                                    <div class="form-group parent_div" >

                                    <div class="col-md-5">
                                    
                                    <select class="form-control chosen-select item_list" onchange="return getItemLatestPrice(this)"  name="items[]">
                                    @if($items->count() > 0  )
                                    <option value="0">Select Item</option>

                                    @foreach($items as $item_lists)
                                    <option  value="{{ $item_lists->id }}">{{ $item_lists->item_name }} - {{ $item_lists->unit }}</option> 
                                    @endforeach
                                    @endif
                                    </select>

                                    </div>
                                 

                                    <div class="col-md-6">

                                    <div class="row">

                                    <div class="col-md-6">
                                    <input type="number" maxlength="6" class="form-control item_qty" placeholder ="Quatity..." value="" name="quantity[]">
                                   
                                    </div>

                                    <div class="col-md-6">
                                    <input type="number" step="any" maxlength="10" class="form-control price" placeholder ="Rate  Per Unit ..." value=""   name="price[]">
                                  
                                    </div>
                                    </div>

                                    </div>



                                    <div class="col-md-1">
                                   

                                     <button type="button" style="width: 100%;" class="btn btn-success waves-effect waves-light m-r-10 " onclick="return add_new_item(this)"><i class="fa fa-plus" aria-hidden="true"></i></button>

                                    </div>

                                    </div>


                                    @endif

                                    <div id="main_item_section">
                                        <!------Add new item List goes from here---->      
                                    </div>

                                        </div>
                               

                                        
                                        </div>

                                        


                                        <div class="col-md-12" style="margin-top: 3rem;">

                                        <div style="display:none;" id="error_message" class="alert alert-danger" role="alert"></div>

                                        <div class="alert alert-success" style="display:none;" role="alert" id="success_message"></div>

                                        <button type="submit" class="btn btn-success waves-effect waves-light m-r-10 sub_btn">Submit</button>
                                        </div>
                                 

                                   </div>

                                    </div>

                                </div>
                               
                               
    	
                            </form>
                        </div>
                    </div>
                </div>

      </div>
      <input type="hidden" value="{{$items->count()}}"  id="total_item">


@stop 

@section('js')

<script>
var slider = document.getElementById("myRange");
var outputs = document.getElementById("progress");
var txt_prog = document.getElementById("txt_prog");

outputs.value = slider.value;
txt_prog.innerHTML = slider.value

slider.oninput = function() {
outputs.value = this.value;
txt_prog.innerHTML = this.value;
}
</script>

<script type="text/javascript">

function add_new_item(self)
{
    var total_item = parseInt($('#total_item').val());

    var remaining = total_item - 1;

    if(remaining > 0)
 {
  $('#total_item').val(remaining)
  $.ajax({
   url:"{{ route('get-dynamic-items.fetch') }}",
   method:'GET',
   dataType:'json',
   success:function(data)
   {
    if(data.response == 'yes')
    {
    
    var output = '';

    output += ' <div class="form-group parent parent_div" >  <div class="col-md-5">   <select class="form-control chosen-select item_list" onchange="return getItemLatestPrice(this)" id="chosen-select'+data.id+'" name="items[]">';
    output += '<option value="0">Select Item</option>';
    $.each(data.items, function(key, value) {
    output += '<option value="'+value.id+'">'+value.item_name+' - '+value.unit+'</option>';
    });

     output += '</option> </select> </div> <div class="col-md-6"><div class="row"><div class="col-md-6"><input type="number" maxlength="6" class="form-control item_qty" placeholder ="Quantity..." value="" name="quantity[]"></div><div class="col-md-6"><input type="number" step="any" maxlength="6" class="form-control price" placeholder ="Rate Per Unit..." value="" name="price[]"></div></div></div>  <div class="col-md-1"><button type="button" style="width: 100%;" class="btn btn-danger waves-effect waves-light m-r-10 " onclick="return remove_item(this)"><i class="fa fa-trash-o" aria-hidden="true"></i></button></div> </div>';

      $('#main_item_section').append(output);
     $('#chosen-select'+data.id).chosen-select();

    }
    
   }
  })

}
else
{
    $('#noItemFound').show('slow')
    setTimeout(function(){ $('#noItemFound').hide('slow') }, 3000);
}

return false;
}


function remove_item(self)
{
    $(self).closest('.parent').remove()
    var total_item = parseInt($('#total_item').val());
    var remaining = total_item + 1;
    $('#total_item').val(remaining)
    return false;
}


function showFullForm(self) 
{

    if($('#main_form').is(':visible'))
{
    $('#main_form').hide('slow');
    order_status = false;
}
    if($('#main_form').is(':hidden'))
{
    $('#main_form').show('slow');
    order_status = true;
}
    
    return false;
}

function addWorkOrder(self) {

    $(self).find('.sub_btn').html('Procesing...')
$(self).find('.sub_btn').prop('disabled' , true)


let order_status = true;
var name = $('#name').val();
var start_date = $('#start_date').val();
var duration = $('#duration').val();
var progress = $('#progress').val();
var task_type = $('#task_type').val();
var priorty = $('#priorty').val();

var assign_to = $('#assign_to').val();
var created_by = $('#created_by').val();

var description = $('#description').val();

var parent = $('#sub_task').val();
var items = [];

$('.item_list').each(function()
    {
        if ($(this).val() != "")
         {
             items.push({'item_id':$(this).val(),'quantity': $(this).closest('.parent_div').find('.item_qty').val() , 'price' : $(this).closest('.parent_div').find('.price').val()});
         }
   
    });


$.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
        });
        $.ajax({
        url:"{{ route('update.work-order') }}",
        method:'POST',
        dataType:'json',
        data: {name:name , start_date: start_date , duration:duration , progress:progress , parent:parent,task_type:task_type,priorty:priorty,assign_to:assign_to,created_by:created_by , description:description,order_status:order_status, items:items, id:'{{$task->id}}'},
        success:function(data)
        {
            if (data.response == 'updated') 
            {
                $('#success_message').html(data.message)
                $('#success_message').show()
                setTimeout(function(){ location.reload(true) }, 3000);
            }
            else if(data.response == 'error')
            {
                var output = '';
                output += '<ul>';
                if (data.errors.text) 
                {
                     output += '<li>'+data.errors.text+'</li>';
                }

                 if (data.errors.name) 
                {
                     output += '<li>'+data.errors.name+'</li>';
                }
                
                 if (data.errors.start_date)
                 {
                    output += '<li>'+data.errors.start_date+'</li>';
                 } 
                  if (data.errors.duration) 
                 {
                    output += '<li>'+data.errors.duration+'</li>';
                 }
                
                 if (data.errors.progress) 
                {
                    output += '<li>'+data.errors.progress+'</li>';
                }
                
                 if (data.errors.assign_to) 
                {
                    output += '<li>'+data.errors.assign_to+'</li>';
                }
                
                if (data.errors.created_by) 
                {
                    output += '<li>'+data.errors.created_by+'</li>';
                }
                
                if (data.errors.priorty) 
                {
                    output += '<li>'+data.errors.priorty+'</li>';
                }
                
                if (data.errors.parent) 
                {
                    output += '<li>'+data.errors.parent+'</li>';
                }
                
                if (data.errors.task_type) 
                {
                    output += '<li>'+data.errors.task_type+'</li>';
                }
                

                output += '</ul> ';
                $('#error_message').html(output)
                $('#error_message').show()
                $(self).find('.sub_btn').html('Submit')
                $(self).find('.sub_btn').prop('disabled' , false)

            }
            else if(data.response == 'custom_error')
            {
               var output = '';
                output += '<ul>';

                if (data.errors) 
                {
                     output += '<li>'+data.errors+'</li>';
                }

                output += '</ul> ';

                $('#error_message').html(output)
                $('#error_message').show()
                $(self).find('.sub_btn').html('Submit')
                $(self).find('.sub_btn').prop('disabled' , false)
            }
            else
            {
              alert('Something Went Wrong! refresh.')
              location.reload(true)
             }

            setTimeout(function(){ $('#error_message').hide('slow') }, 6000);

          }
        })
            

 return false;
}
    function hideTaskCategory(self) {
        $('#task_list').hide();
        $('#taskCategory').show()
        $('#form_fileds').hide();
    return false;
    }

    function taskCategory(self) {
    if ($(self).val() == 'sub-task')
     {
        $('#task_list').show();
        $('#taskCategory').hide()
        $('#form_fileds').show();
     }
     else if($(self).val() == 'task')
     {
        $('#task_list').hide();
        $('#taskCategory').show()
        $('#form_fileds').show();
     }
     else
     {
          $('#task_list').hide();
        $('#taskCategory').show()
        $('#form_fileds').hide();
     }

    return false;
    }
</script>
@stop