@extends('layouts.backend')
@section('extraCss')  
 <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet">
 <style>
table.TableAddDelete{
    width: 100%;
    border-collapse: collapse;
    margin-top:20px;
}
table.TableAddDelete th, table.TableAddDelete td{
    border: 1px solid #cdcdcd;
    padding: 7px;
}
</style>
@endsection

@section('mainContentArea')

<div class="card card-default">
    <div class="card-header">
        <h4>
            Edit Article Image      
            <a href="{{ route('article-image') }}" class="btn btn-info float-right btn-sm"> Back</a>      
        </h4>
    </div>

    @if (count($errors) > 0)
   <div class = "alert alert-danger">
      <ul>
         @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
         @endforeach
      </ul>
   </div>
   @endif
    <div class="card-body">
       
        <form   method="POST" enctype="multipart/form-data" action="{{ route('article-image.update') }}" >
        @csrf        
        
        <div class="row"> 
            <div class="col-md-12"><h5> Article Details</h5><hr/></div>
            <div class="col-md-6 form-group">
                <input type='hidden' name='editid' value='{{$articleimg->id}}'>
                <label for="article">Article</label>
                <input type='text' name="article" id="article" class="form-control" readonly value="{{$articleimg->code}}" > 
                    
            </div>

            <div class="col-md-6 form-group">
                <label for="color">Color</label>
                <input type='text' name="color" id="color" class="form-control" readonly value="{{$articleimg->color_name}}" > 
                
            </div>

           <!--  <div class="col-md-12"><h5> Images</h5><hr/></div>
        

            <div class="col-md-6 form-group">
                <label for="code"> Photo </label>
                <input type="file" name="photo" id="photo" class="form-control" onchange="previewPhoto(this)" multiple accept="image/*">
                
            </div>
            
            <div class="col-md-6 form-group" >
              <img src="{{ asset('uploads/articles/photos/full'.$articleimg->imgname) }}" alt="" title="" width = '100px' height='150px'>
            </div>


            <div class="col-md-6 form-group" id="preview_photo" style='display:none;'>
              <img id="preview_photo_img" src="" alt="Placeholder" width = '100px' height='150px'>
            </div> -->

            <div class="col-md-12"><h5>Images Details</h5><hr/></div> 
            <div class="col-md-12 form-group">
                <div class="table-responsive">
                  <table class="table table-bordered">
                    <thead>
                      <tr>                       
                        <th class="text-center">Image</th>
                       
                        <th class="text-center">Sort Order</th>                    
                        <th class="text-center">Action</th>
                      </tr>
                    </thead>
                    <tbody id="tbodyv">
                    @php $count = 0;@endphp
                      @if(count($images) > 0)
                       @foreach($images as $key => $value)

                        @php $count = $key +1 ; @endphp
                        <tr id="{{$count}}" >                             
                             
                              <td class="row-index text-center">               
                                    <img src="{{ asset('uploads/articles/photos/full'.$value->imgname) }}" alt="" title="" width = '100px' height='150px'>
                              </td>
                              <td class="row-index text-center">               
                                    <input type="number" name="sortorder[]"  min='0' value="{{!empty($value->sort_order) ? $value->sort_order : 0}}" class="form-control" placeholder="Enter Sort Order" required />
                                   <input type="hidden" name='imageids[]' value="{{$value->id}}">
                              </td>
                              <td class="text-center">
                                @if($articleimg->id != $value->id )
                                <button class="btn btn-danger remove"  type="button" id= "{{$value->id}}" onclick="deleteImage(this.id)">remove</button>
                                @endif
                                 <button class="btn btn-info" type="button" data-imageid="{{$value->id}}" data-code="{{$value->code}}" data-colorname="{{$value->color_name}}" data-editid = "{{$articleimg->id}}"
                                 data-toggle="modal" data-target="#ImageModal" id="gallery"  data-image = "{{  empty($value->imgname) || $value->imgname == 'NULL' ? 'https://via.placeholder.com/100x100.png?text=No Photo' : asset('uploads/articles/photos/full'.$value->imgname) }}" ><i class="fa fa-pencil-square-o"></i> </button>
                              </td>
                        </tr>
                       @endforeach 
                      @endif
                    </tbody>
                  </table>
                </div>
               
                
                <button class="btn btn-md btn-primary" 
                    id="addBtn" type="button">
                  Add Images 
                </button>
                
            </div>

           
            <div class="col-md-12 text-Center" style="margin:20px;">
                <button type="submit" class="btn btn-success" ><i class="fa fas fa-save"></i> Submit</button>
                
            </div>
          
        </div>

        
        
    </form>

    </div>
</div>
<div class="modal fade " id="ImageModal" tabindex="-1" role="dialog" aria-hidden="true" >
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5> Update Image </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form method="post" id="upload_form" enctype="multipart/form-data">
    {{ csrf_field() }}
      <div class="modal-body">
        <div class="row" style="margin-top:10px;">
          <div class="col-md-6 form-group">
            <img id='articlepop'  src="" alt="First slide" style="max-height:200px;">
            
          </div>
          <div class="col-md-6 form-group">
             <label for="code"> Photo </label>
                <input type="file" name="photo" id="photo" class="form-control" onchange="previewPhoto(this)" multiple accept="image/*" required>
                <input type="hidden" name='imageId' id='updateid' value=''>
                <input type="hidden" name='code' id='articleid' value=''>
                <input type="hidden" name='color_name' id='colorid' value=''>
                <input type="hidden" name='editids' id='editids' value=''>
           </div>
           <div class="col-md-6 form-group">
            <label for="code"> Sort Order </label>
            <input type="number" name="order" id='order' min='0' value="" class="form-control" placeholder="Enter Sort Order" required />
                                 
          </div>
         <div class="col-md-6 form-group">
            <img id="preview_photo" src="" alt="Placeholder" width = '100px' height='150px' style="display:none;">
          </div>
        </div>
        
      </div>
      <div class="modal-footer">        
        <button type="submit"  class="btn btn-primary" id='updateSubmit'>Save changes</button>

      </div>
       </form>
    </div>
  </div>
</div>
@endsection

@section('extraJs')
<script>
    var rowIdx = <?php echo $count; ?>;
  
// jQuery button click event to add a row.
$('#addBtn').on('click', function () {    
  
    // Adding a row inside the tbody.
    $('#tbodyv').append(`<tr id="R${++rowIdx}">
          
          <td class="row-index text-center">  
          <input type="file" name="images[${rowIdx}]">             
          </td>
          <td class="row-index text-center">    
               <input type="number" name="newsortorder[]"   id="ot${rowIdx}" class="form-control" placeholder="Enter Sort Order" required />

          </td>
          
           <td class="text-center">
            <button class="btn btn-danger remove" 
                type="button">Remove</button>
            </td>
           </tr>`);
});

$('#tbodyv').on('click', '.remove', function () {

        // Getting all the rows next to the row
        // containing the clicked button
        var child = $(this).closest('tr').nextAll();

        // Iterating across all the rows
        // obtained to change the index
        child.each(function () {

        // Getting <tr> id.
        var id = $(this).attr('id');        

        // Getting the <p> inside the .row-index class.
        var idx = $(this).children('.row-index').children('p');

        // Gets the row number from <tr> id.
        var dig = parseInt(id.substring(1));

        // Modifying row index.
        idx.html(`Row ${dig - 1}`);

        // Modifying row id.
        $(this).attr('id', `R${dig - 1}`);
        });      

        // Removing the current row.
        $(this).closest('tr').remove();

        // Decreasing total number of rows by 1.
        rowIdx--;
    });
$(function () {
  $('#ImageModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // Button that triggered the modal
    var newSrc = button.data('image'); // Extract info from data-* attributes
    var updateimg = button.data('imageid');
    var article = button.data('code');
    var color = button.data('colorname');
    var editid = button.data('editid');
   console.log(newSrc);
     $('#articlepop').attr('src', newSrc);
     $('#updateid').val(updateimg);
     $('#articleid').val(article);
     $('#colorid').val(color);
     $('#editids').val(editid);
  });
});

function previewPhoto(input){
       $("#preview_photo").css("display", "block");
        var file = $("input[type=file]").get(0).files[0];
 
        if(file){
            var reader = new FileReader();
 
            reader.onload = function(){
                $("#preview_photo").attr("src", reader.result);
            }
 
            reader.readAsDataURL(file);
        }
}

$('#upload_form').on('submit', function(event){       
   event.preventDefault();
    var imageid = $('#updateid').val();
      
    var _token   = $('meta[name="csrf-token"]').attr('content');   

      $.ajax({
        type: "POST",
        url: "{{ route('update-article-image') }}",
       
       data:new FormData(this),
       dataType:'JSON',
       contentType: false,
       cache: false,
       processData: false,
        dataType: "json",
        success: function(response) { //console.log(response); return false;
           $('#ImageModal').hide();
           //toastr.success(response.massage);
           var url = "{{url('article/images/edit')}}"+"/"+response.editid;
           console.log(url); 
            window.location.reload(url);
        },
        error: function(response) {
          console.log(response.responseJSON.errors);
        }
      });
  
});

function deleteImage(id)
{ 
     var _token   = $('meta[name="csrf-token"]').attr('content');   

      $.ajax({
        type: "get",
        url: "{{ route('delete-article-image') }}",
        data: {
          id: id,                
          _token: _token
        },
        dataType: "json",
        success: function(response) { 
            toastr.success(response.massage);
            window.location.reload();
           //console.log(response.massage);
           //toastr.success(response.massage);
        },
        error: function(response) {
          console.log(response.responseJSON.errors);
        }
    
  
      });
}
</script>
@endsection


