@extends('layouts.app')

@section('title')
Edit Purchase Request
@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">Purchase Requests</li>
      </ol>
@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 Purchase Request
                    </h3>

                    <p class="text-muted m-b-30 font-13">  </p>
                    <form class="form-horizontal" method="POST"  action="{{ route('purchase-requests.update') }}">
                    	 {{csrf_field()}}
                         <input type="hidden" name="purchase_request_id" value="{{$purchase_request->id}}">
                        <div class="form-group">
                                   
                        <div class="col-md-6">
                        <label >Select Project</label>
                        <select class="form-control chosen-select"  name="project" >
                        @if($projects->count() > 0  )
                        @foreach($projects as $project_lists)
                        <option <?= ( $project_lists->id == $purchase_request->project_id) ? 'selected' : '' ?> value="{{ $project_lists->id }}">{{ $project_lists->project_name  }}</option> 
                        @endforeach
                        @endif
                        </select>
                        @if ($errors->has('project'))
                        <span >
                        <strong class="error_messages" >{{ $errors->first('project') }}</strong>
                        </span>
                        @endif

                        </div>


                        <div class="col-md-6">
                        <label >Select Department</label>
                        <select class="form-control chosen-select"  name="department" >
                        @if($departments->count() > 0  )
                        @foreach($departments as $department_lists)
                        <option <?= ( $department_lists->id == $purchase_request->department_id) ? 'selected' : '' ?> value="{{ $department_lists->id }}">{{ $department_lists->department_name  }}</option> 
                        @endforeach
                        @endif
                        </select>

                        @if ($errors->has('department'))
                        <span >
                        <strong class="error_messages" >{{ $errors->first('department') }}</strong>
                        </span>
                        @endif

                        </div>


                        </div>

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

                          <h3 class="box-title m-b-0">Item List</h3>
                        <div class="alert alert-danger" style="display: none;" id="noItemFound">
                        <strong>Exception!</strong> No more items found.
                        </div>

                         @if(Session::has('item_errors'))   
                            <div class="alert alert-danger"  >
                            <strong class="error_messages" style="color:white;">
                            {{ Session::get('item_errors') }}
                           </strong>
                            </div>
                            @endif


                          </div>

                         
                         </div>
                  <?php $count = 0; ?>
                      @foreach(\App\PurchaseRequest::find($purchase_request->id)->item as  $key => $item_list)

                         <div class="form-group parent parent_div" >

                          <div class="col-md-3">
                            
                            <select onchange="return getItemLatestPrice(this)" class="form-control chosen-select us_valid"  name="items[]">
                                <option value="0">Select Item</option>
                            @if($items->count() > 0  )
                            @foreach($items as $item_lists)
                            <option <?= ($item_lists->id  == $item_list->item_id) ? 'selected' : '' ?> value="{{ $item_lists->id }}">{{ $item_lists->item_name }} - {{ $item_lists->unit }}</option> 
                            @endforeach
                            @endif
                            </select>

                             @if ($errors->has('items'))
                            <span >
                                <strong class="error_messages" >{{ $errors->first('items') }}</strong>
                            </span>
                                 @endif
                             </div>
                         

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

                            <div class="row">
                            <div class="col-md-6">
                            <input type="number" maxlength="6" class="form-control search" placeholder ="Qty..." id="item_qty" oninput="this.value = Math.abs(this.value)" value="{{$item_list->quantity}}" name="quantity[]">
                            <span style="color:red; display: none;" class="limit_error"></span>

                             @if ($errors->has('quantity.*'))
                            <span >
                            <strong class="error_messages" >{{ $errors->first('quantity.*') }}</strong>
                            </span>
                            @endif

                            </div>

                            <div class="col-md-6">
                            <input type="number" maxlength="6" class="form-control price" placeholder ="Price..." value="{{$item_list->price}}" oninput="this.value = Math.abs(this.value)" name="price[]">
                            @if ($errors->has('price.*'))
                            <span >
                            <strong class="error_messages" >{{ $errors->first('price.*') }}</strong>
                            </span>
                            @endif

                            </div>

                            </div>

                            </div>


                                 <div class="col-md-4">
                                 <textarea class="form-control" name="description[]" placeholder="Item Description / Specification" id="description">{{$item_list->description}}</textarea>
                                 </div>
                         

                            <div class="col-md-1">
                            @if($key  >  0)
                            <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>
                            @else
                            <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>

                            @endif
                             

                            </div>

                            </div>
                            <?php $count++; ?>
                             @endforeach      

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


                            <div class="form-group" >
                              
                              <div class="col-md-12">
                              <h3 class="box-title m-b-0">Approvals</h3>
                              </div>
                             
                             </div>


                            <div class="form-group">
                                 
                            <div class="col-md-4">
                            <ul>
                                <li>
                                    Select approval roles from below.
                                </li>
                             
                            </ul>
                            <input type="hidden" name="role_orders"  id="role_orders">
                            <select class="chosen-select" name="role_name[]" id="roles" multiple>
                            @if($approvel_roles->count() > 0  )
                            @foreach($approvel_roles as $list)
                            <option value="{{ $list->id }}">{{ $list->name }}</option> 
                            @endforeach
                            @endif
                            </select>

                            @if(Session::has('role_orders'))   
                            <span >
                            <strong class="error_messages" >{{ Session::get('role_orders') }}</strong>
                            </span>
                            @endif

                            </div>

                            </div>


                               
                            <div class="form-group">
                               
                                <div class="col-md-12">
                                       <button type="submit" class="btn btn-success waves-effect waves-light m-r-10">Submit</button>
                                </div>
                             
                            </div>

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

      </div>

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


@section('js')  

<script type="text/javascript">


$(document).ready(function() {

$(document).on('keyup', '.search', function() {

$item_id = $(this).closest('.parent_div').find('.us_valid :selected').val();

$qty = $(this).val();

$task  = '{{$purchase_request->task_id}}';

if ($task != 0) 
{
    $task_id =   $task;
}
else
{
    return false;
}

var div = $(this);

$.ajax({
type : 'get',
url : "{{route('purchase-requests.search')}}",
data:{'qty':$qty , 'item_id' :$item_id   , 'task_id' : $task_id  },
dataType: 'json',
success:function(data)
{
  if (data.response == 'limit_exceed')
   {
     div.closest('.parent_div').find('.limit_error').text('Limit Exceeded Max ('+data.max+')');
     div.closest('.parent_div').find('.limit_error').show();
   }
   else if (data.response == 'limit_not_exceed')
   {
     div.closest('.parent_div').find('.limit_error').hide();
   }
}
});

return false;
});

});



      function getItemLatestPrice(self)
    {
        var item_id =  $(self).find(':selected').val();
       
       if (item_id != 0) 
       {
         $(self).closest('.parent_div').find('.search').prop('disabled', false);
         $(self).closest('.parent_div').find('.search').val('');
       }

       if (item_id == 0) 
       {
         $(self).closest('.parent_div').find('.search').val('');
         $(self).closest('.parent_div').find('.search').prop('disabled', true);
       }

              $.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
        });
        $.ajax({
        url:"{{ route('purchase-requests.get-item-latest-price') }}",
        method:'POST',
        dataType:'json',
        data: {item_id:item_id },
        success:function(data)
        {
           if(data.response == 'yes')
           {
            
               $(self).closest('.parent_div').find('#item_qty').val(data.quantity)
               $(self).closest('.parent_div').find('.price').val(data.price)
           }
           else if(data.response == 'null')
           {
                $(self).closest('.parent_div').find('#item_qty').val(data.quantity)
                $(self).closest('.parent_div').find('.price').val("")
           }
           else
           {
            alert('Something Went wrong!')
            location.reload(true)
           }

        }
        })


      
        return false;
    }


    // In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
     $("#roles").chosen-select();
    $('.chosen-select').chosen-select();
    $('#role_orders').val(0);

});

$('#roles').val([{{$assignRoles}}]).change();


function adjustOrder()
{
       var data = $('#roles').chosen-select('data');
        
        // Push each item into an array
        var finalResult = [];
        for( item in $('#roles').chosen-select('data') ) {
            finalResult.push(data[item].id);
        };
        $('#role_orders').val(finalResult.join(','));

}

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

    var remaining = total_item ;

    if(remaining > 0)
  {
  $('#total_item').val(remaining - 1)
  $.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-3">   <select class="form-control chosen-select us_valid" id="chosen-select'+data.id+'" onchange="return getItemLatestPrice(this)"  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-4"><div class="row"><div class="col-md-6"><input type="number" maxlength="6" class="form-control search" placeholder ="Qty..." value="" id="item_qty" oninput="this.value = Math.abs(this.value)" name="quantity[]"><span style="color:red; display: none;" class="limit_error"></span></div><div class="col-md-6"><input type ="number" maxlength="6" class="form-control price" placeholder ="Price..." value="" name="price[]" oninput="this.value = Math.abs(this.value)"></div></div></div><div class="col-md-4"><textarea class="form-control" name="description[]" placeholder="ItemDescription / Specification" id="description"></textarea></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();


$task  = '{{$purchase_request->task_id}}';

           if ($task > 0)
    {
           
           $( ".us_valid" ).each(function() {

            if ( $( this ).val() == '0' )
            { 
               $(this).closest('.parent_div').find('.search').prop('disabled', true); 
            }

            });
    }
 if ($task == 0) 
    {
          $(".search").prop('disabled', false); 
    }



    }
    
   }
  })

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

return false;
}

function remove_item(self)
{
    if (confirm('Are you sure?'))
     {

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

</script>

@stop
