@extends('layouts.app')
@section('title', __('product.add_new_amazon_product'))

@section('content')

<!-- Content Header (Page header) -->
<section class="content-header">
  <div class="row">
    <div class="col-lg-6">
      <h3 style="margin: 0">@lang('product.add_new_amazon_product')</h3>
    </div>
    <div class="col-lg-6">
      <button class="btn btn-primary pull-right" onclick="popupFindInAmazon(event)"><i class="fa fa-microchip"></i> @lang('business.find_in_amazon')</button>
    </div>
  </div>
    <!-- <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li>
        <li class="active">Here</li>
    </ol> -->
</section>

<!-- Main content -->
<section class="content">
{!! Form::open(['url' => action([\App\Http\Controllers\AmazonController::class, 'StoreProduct']), 'method' => 'post', 
    'id' => 'product_add_form','class' => 'product_form ' , 'files' => true ]) !!}
    @component('components.widget', ['class' => 'box-primary'])      
    <div class="row">
        <input type="hidden" name="identifiers" id="identifiers">
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('title', __('product.title') . ':*') !!}
              {!! Form::text('title', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.title')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('store', __('product.store') . ':*') !!}
              {!! Form::select('store[]', $amazon_sellers, '', ['class' => 'form-control select2', 'required', 'multiple']) !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('asin', __('product.asin') . ':*') !!}
              {!! Form::text('asin', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.asin')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('product_group', __('product.product_group') . ':') !!}
              {!! Form::select('product_group', $amazon_product_group, '', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2', '']) !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('product_type', __('product.product_type') . ':') !!}
              {!! Form::select('product_type', $amazon_product_types, '', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2search', '']) !!}
          </div>
        </div>                     
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('price', __('product.price') . ':*') !!}
              {!! Form::text('price', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.price')]); !!}
          </div>
        </div>              
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('qty', __('product.qty') . ':*') !!}
              {!! Form::text('qty', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.qty')]); !!}
          </div>
        </div>              
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('sku', __('product.sku') . ':*') !!}
              {!! Form::text('sku', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.sku')]); !!}
          </div>
        </div>      
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('status', __('product.status') . ':*') !!}
              {!! Form::select('status', ['Active' => 'Active', 'Inactive' => 'Inactive'], 'Active', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2', 'required']) !!}
          </div>
        </div>        
        <div class="clearfix"></div>
        <div class="col-sm-9">
          <div class="form-group">
            {!! Form::label('product_description', __('lang_v1.product_description') . ':*') !!}
              {!! Form::textarea('product_description', !empty($duplicate_product->product_description) ? $duplicate_product->product_description : null, ['class' => 'form-control', 'required']); !!}
          </div>
        </div>
        <div class="col-sm-4">
          <div class="form-group">
            {!! Form::label('image', __('lang_v1.product_image') . ':*') !!}
            {!! Form::file('image', ['id' => 'upload_image', 'accept' => 'image/*', 
                'required' => 'required', 'class' => 'upload-element']); !!}
            <small><p class="help-block">@lang('purchase.max_file_size', ['size' => (config('constants.document_size_limit') / 1000000)]) <br> @lang('lang_v1.aspect_ratio_should_be_1_1')</p></small>
          </div>
        </div>              
        <div class="clearfix"></div>     
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('languages', __('product.languages') . ':') !!}
              {!! Form::text('languages', null, ['class' => 'form-control', '',
              'placeholder' => __('product.languages')]); !!}
          </div>
        </div>                              
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('format', __('product.format') . ':') !!}
              {!! Form::text('format', null, ['class' => 'form-control', '',
              'placeholder' => __('product.format')]); !!}
          </div>
        </div>                              
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('itemTypeKeyword', __('product.itemTypeKeyword') . ':') !!}
              {!! Form::select('itemTypeKeyword', $amazon_product_item_type, '', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2', '']) !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('binding', __('product.binding') . ':') !!}
              {!! Form::select('binding', $amazon_product_binding, '', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2', '']) !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('composer', __('product.composer') . ':') !!}
              {!! Form::text('composer', null, ['class' => 'form-control', '',
              'placeholder' => __('product.composer')]); !!}
          </div>
        </div> 
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('publication_date', __('product.publication_date') . ':') !!}
              {!! Form::text('publication_date', null, ['class' => 'form-control', '',
              'placeholder' => __('product.publication_date')]); !!}
          </div>
        </div> 
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('number_of_pages', __('product.numberOfPages') . ':') !!}
              {!! Form::text('number_of_pages', null, ['class' => 'form-control', '',
              'placeholder' => __('product.numberOfPages')]); !!}
          </div>
        </div> 
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('width', __('product.width') . ':') !!}
              {!! Form::text('width', null, ['class' => 'form-control', '',
              'placeholder' => __('product.width')]); !!}
          </div>
        </div>         
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('height', __('product.height') . ':') !!}
              {!! Form::text('height', null, ['class' => 'form-control', '',
              'placeholder' => __('product.height')]); !!}
          </div>
        </div> 
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('length', __('product.length') . ':') !!}
              {!! Form::text('length', null, ['class' => 'form-control', '',
              'placeholder' => __('product.length')]); !!}
          </div>
        </div> 
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('brand', __('product.brand') . ':') !!}
              {!! Form::text('brand', null, ['class' => 'form-control', '',
              'placeholder' => __('product.brand')]); !!}
          </div>
        </div>                      
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('manufacturer', __('product.manufacturer') . ':') !!}
              {!! Form::text('manufacturer', null, ['class' => 'form-control', '',
              'placeholder' => __('product.manufacturer')]); !!}
          </div>
        </div>                      
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('author', __('product.author') . ':') !!}
              {!! Form::text('author', null, ['class' => 'form-control', '',
              'placeholder' => __('product.author')]); !!}
          </div>
        </div>           
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('target_audience', __('product.targetAudience') . ':') !!}
              {!! Form::text('target_audience', null, ['class' => 'form-control', '',
              'placeholder' => __('product.targetAudience')]); !!}
          </div>
        </div>           
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('classifications', __('product.classifications') . ':*') !!}
              {!! Form::select('classifications[]', $classifications, null, ['class' => 'form-control select2search', 'required', 'multiple' => 'multiple', 'id' => 'classifications']) !!}
              <label id="classifications-error" class="error" for="collections" style="display: none;">This field is required.</label>
          </div>
        </div>    
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('condition', __('product.condition') . ':*') !!}
              {!! Form::select('condition', $itemCondition, '', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2', 'required']) !!}
          </div>
        </div>       
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('is_adult_product', __('product.isAdultProduct') . ':*') !!}
              {!! Form::select('is_adult_product', [true => 'Yes', false => 'No'], false, ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2', 'required']) !!}
          </div>
        </div>                      
    </div>
    @endcomponent    
    @component('components.widget', ['class' => 'box-primary'])
    <div class="row" id="subjects">
      <input type="hidden" name="row_count_subjects" id="row_count_subjects" value="0">
      <div class="col-lg-4">
        <div class="form-group">
          {!! Form::label('subjects', __('product.subjects') . ':') !!}
          <button type="button" class="btn btn-default bg-white btn-flat btn-modal" title="Add subject" onclick="addSubjects()"><i class="fa fa-plus-circle text-primary fa-lg"></i></button>
          <div class="input-group">
            {{-- {!! Form::text('subjects[]', null, ['class' => 'form-control', '',
            'placeholder' => __('product.subjects'), 'id' => 'subject1']); !!} --}}
            <span class="input-group-btn">
            </span>
          </div>
        </div>
      </div>
    </div>
    @endcomponent
    @component('components.widget', ['class' => 'box-primary'])
    <div class="row" id="bulletPoints">
      <input type="hidden" name="row_count_bulletPoints" id="row_count_bulletPoints" value="0">
      <div class="col-lg-4">
        <div class="form-group">
          {!! Form::label('bulletPoints', __('product.bulletPoints') . ':') !!}
          <button type="button" class="btn btn-default bg-white btn-flat btn-modal" title="Add Bullet Point" onclick="addbulletPoints()"><i class="fa fa-plus-circle text-primary fa-lg"></i></button>
          {{-- <div class="input-group">
            {!! Form::text('bulletPoints[]', null, ['class' => 'form-control', '',
            'placeholder' => __('product.subjects'), 'id' => 'bullet_point1']); !!}
            <span class="input-group-btn">
            </span>
          </div> --}}
        </div>
      </div>
    </div>
    @endcomponent
    <div class="row">
      <div class="col-sm-12">
      <input type="hidden" name="submit_type" id="submit_type">
      <div class="text-center">
      <div class="btn-group">              
        <button type="submit" value="submit" class="btn btn-primary submit_product_form">@lang('messages.save')</button>
      </div>
      
      </div>
    </div>
{!! Form::close() !!}
  
</section>
<!-- /.content -->

@endsection

@section('javascript')
  @php $asset_v = env('APP_VERSION'); @endphp
  <script type="text/javascript">
    const baseUrl = window.location.origin;
    let category_param_search = '';
    let category_found = true;
    
      $(document).ready(function(){
          __page_leave_confirmation('#product_add_form');
          $('#classifications').select2({
              placeholder: 'Find data...',
              ajax: {
                  url: '{{ route("ajax.search.classificationAmazon") }}', // sesuaikan dengan route kamu
                  dataType: 'json',
                  delay: 250,
                  data: function (params) {
                      return {
                          q: params.term // kata kunci pencarian
                      };
                  },
                  processResults: function (data) {
                      return {
                          results: data // array of {id, text}
                      };
                  },
                  cache: true
              }
          });             
          $('#product_type').select2({
              placeholder: 'Find data...',
              ajax: {
                  url: '{{ route("ajax.search.productTypeAmazon") }}', // sesuaikan dengan route kamu
                  dataType: 'json',
                  delay: 250,
                  data: function (params) {
                      return {
                          q: params.term // kata kunci pencarian
                      };
                  },
                  processResults: function (data) {
                      return {
                          results: data // array of {id, text}
                      };
                  },
                  cache: true
              }
          });             
      });      

      $(document).on('click', '.submit_product_form', function(e) {
        e.preventDefault();

        var is_valid_product_form = true;      
        var submit_type = $(this).val();                
        // var submit_type = $(this).attr('value');
        $('#submit_type').val(submit_type);
        if ($('form#product_add_form').valid()) {    
          const classifications = $('#classifications').val(); // Get selected values
          if (!classifications || classifications.length === 0) {
            // alert('Please select at least one collection.');
            $('#classifications-error').css('display', 'block');
            $('#classifications-error').text('This field is required.');            
          } else {          
            $('#classifications-error').css('display', 'none');
            $('#classifications-error').text();
            $('form#product_add_form').submit();
          }
        }        
        
      });      

      function scanFindInAmazon(event) {        
        if (event.key === 'Enter' && event.target.value.length > 3) {
          findInAmazon(event, event.target.value);
        }
      }

      function popupFindInAmazon(e) {
        e.preventDefault();
        $.ajax({
            url: baseUrl + '/amazon/popupFindInAmazon',
            dataType: 'html',
            success: function(result) {
                // console.log(result);
                $('.view_modal')
                    .html(result)
                    .modal('show');
                $('.view_modal').on('shown.bs.modal', function () {
                  $('#productISBN').trigger('focus');
                });
                
                setTimeout(function () {
                  $('#productISBN').trigger('focus');
                }, 300); // allow modal animation to complete
            },
        });
      }

      function findInAmazon(e, input) {
        e.preventDefault();
        let default_seller = 'A2NODI4BBRA1B1';
        let url = '/amazon/getProductDetailByISBN/' + input + '/' + default_seller + '?credit=-5';        
        $.ajax({
            method: 'GET',
            url: url,
            dataType: 'json',
            success: function(result) {
              if(result.error) {
                swal({
                    title: 'Credits',
                    text: result.error,
                    icon: 'error',
                    button: 'OK'
                });
              } else if(result.numberOfResults === 0) {
                swal({
                    title: 'Product Not Found',
                    text: 'Unfortunately, we were unable to locate the product on Amazon.',
                    icon: 'error',
                    button: 'OK'
                });
              } else {
                if(result.items.length > 0) {
                  let items = result.items[0];
                  console.log(items);
                  callKeepaApi(items.asin);
                  if(items.attributes.item_name) {
                    $('#title').val(items.attributes.item_name[0].value);
                  }
                    
                  $('#asin').val(items.asin);

                  $('#product_group option').each(function() {
                    if(items.salesRanks) {
                      if(items.salesRanks[0].displayGroupRanks) {
                        if ($(this).val().includes(items.salesRanks[0].displayGroupRanks[0].title)) {
                            $(this).prop('selected', true);
                        }
                      }
                    }
                  });

                  $('#product_group').trigger('change.select2');
                  if(items.productTypes) {
                    $('#product_type').val(items.productTypes[0].productType).trigger('change.select2');
                  }
                  if(items.attributes.list_price) {
                    $('#price').val(items.attributes.list_price[0].value);
                  }

                  if(items.identifiers) {
                    $('#identifiers').val(JSON.stringify(items.identifiers));
                  }

                  if(items.images) {
                    const imageUrl = items.images[0].images[0].link;
                    fetch(imageUrl)
                      .then(res => res.blob())
                      .then(blob => {
                          const filename = imageUrl.split('/').pop();
                          const file = new File([blob], filename, { type: blob.type });
                          
                          const dataTransfer = new DataTransfer();
                          dataTransfer.items.add(file);
                          $('#upload_image')[0].files = dataTransfer.files; // Setting files to the input
                          // ✅ Simulate "upload" via AJAX
                          let form = document.getElementById('product_add_form');
                          const formData = new FormData(form);
                          formData.append('image', file);
                    });
                  }

                  if(items.attributes.language) {
                    $('#languages').val(items.attributes.language[0].value);
                  }
                  if(items.attributes.item_type_keyword) {
                    $('#itemTypeKeyword').val(items.attributes.item_type_keyword[0].value).trigger('change.select2')
                  }
                  if(items.attributes.binding) {
                    $('#binding').val(items.attributes.binding[0].value).trigger('change.select2')
                  }
                  if(items.summaries) {
                    $('#publication_date').val(items.summaries[0].releaseDate);
                  }
                  if(items.attributes.pages) {
                    $('#number_of_pages').val(items.attributes.pages[0].value);
                  }
                  if(items.dimensions) {
                    $('#width').val(items.dimensions[0].item.width.value);
                  }
                  if(items.dimensions) {
                    $('#height').val(items.dimensions[0].item.height.value);
                  }
                  if(items.length) {
                    $('#length').val(items.dimensions[0].item.length.value);
                  }
                  if(items.summaries) {
                    $('#brand').val(items.summaries[0].brand);
                    $('#manufacturer').val(items.summaries[0].manufacturer);
                  }
                  if(items.attributes.author) {
                    $('#author').val(items.attributes.author[0].value);
                  }
                  if(items.attributes.target_audience) {
                    $('#target_audience').val(items.attributes.target_audience[0].value);
                  }

                  if(items.classifications[0]) {
                    var selectedValues = [];
                    $.each(items.classifications[0].classifications, function(k,v) {
                      selectedValues.push(v.displayName);
                      // if ($("#classifications option[value='" + v.displayName + "']").length === 0) {
                      //     $('#classifications').append(new Option(v.displayName, v.displayName, true, true));
                      // }
                      if ($("#classifications option").filter(function() {
                          return $(this).val() === v.displayName;
                      }).length === 0) {
                          $('#classifications').append(new Option(v.displayName, v.displayName, true, true));
                      }
                    })

                    $('#classifications').val(selectedValues).trigger('change');
                  }
                  
                  if(items.attributes.subject) {
                    if(items.attributes.subject.length > 0) {
                      $.each(items.attributes.subject, function(k,v) {                        
                          addSubjects();
                          $('#subject' + (k+1)).val(v.value);                        
                      })
                    }
                  }
                  
                  if(items.attributes.bullet_point) {
                    if(items.attributes.bullet_point.length > 0) {
                      $.each(items.attributes.bullet_point, function(k,v) {
                        if(k == 0) {
                          $('#bullet_point1').val(v.value);
                        } else {
                          addbulletPoints();
                          $('#bullet_point' + (k+1)).val(v.value);
                        }
                      })
                    }
                  }
                  
                  
                  swal({
                      title: 'Product Found',
                      text: '',
                      icon: 'success',
                      button: 'OK'
                  });
                  $('.view_modal').modal('hide');
                } else {
                  swal({
                    title: 'Product Not Found',
                    text: 'Unfortunately, we were unable to locate the product on Amazon.',
                    icon: 'error',
                    button: 'OK'
                  });
                }
              }
            },
            error: function(xhr, status, error) {
                swal({
                    title: 'Product Not Found',
                    text: 'Unfortunately, we were unable to locate the product on Amazon.',
                    icon: 'error',
                    button: 'OK'
                });
            }
        });
      }

      function callKeepaApi(asin) {
        $.ajax({
          method: 'GET',
          url: baseUrl + '/amazon/callApiKeepa/' + asin,
          dataType: 'json',
          success: function(result) {
            $('#product_description').val(result.description) 
          },
          error: function(xhr, status, error) {              
          }
        });
      }

      $('#category_id').on('select2:open', function() {
          const results = $('#category_id').select2('data'); // Get current Select2 results

          if (results.length === 0) {
              // If no results, show a message or handle empty results
              // $('#noResultsMessage').show();
              category_found = false;
            } else {
              // If there are results, hide the "no results" message
              category_found = true;
              $('#noResultsMessage').hide();
          }
      });

      function addSubjects() {
        let row_count_subjects = $('#row_count_subjects').val();
        let new_row = parseInt(row_count_subjects) + 1;

        $('#subjects').append(`
          <div class="col-lg-12" id="row_subjects_${new_row}">
            <div class="form-group">                         
              <div class="input-group">
                {!! Form::text('subjects[]', null, ['class' => 'form-control', '', 'id' => 'subject${new_row}']); !!}
                <span class="input-group-btn">
                    <button type="button" class="btn btn-default bg-white btn-flat btn-modal" title="Remove subject" onclick="removeSubject('#row_subjects_${new_row}')"><i class="fa fa-minus-circle text-danger fa-lg"></i></button>
                </span>
              </div>
            </div>
          </div>
        `); 

        $('#row_count_subjects').val(new_row)
      }

      function removeSubject(row) {
        $(row).remove();
      }

      function addbulletPoints() {
        let row_count_bulletPoints = $('#row_count_bulletPoints').val();
        let new_row = parseInt(row_count_bulletPoints) + 1;

        $('#bulletPoints').append(`
          <div class="col-lg-12" id="row_bulletPoints_${new_row}">
            <div class="form-group">                         
              <div class="input-group">
                {!! Form::text('bulletPoints[]', null, ['class' => 'form-control', '',
                'id' => 'bullet_point${new_row}']); !!}
                <span class="input-group-btn">
                    <button type="button" class="btn btn-default bg-white btn-flat btn-modal" title="Remove subject" onclick="removeSubject('#row_bulletPoints_${new_row}')"><i class="fa fa-minus-circle text-danger fa-lg"></i></button>
                </span>
              </div>
            </div>
          </div>
        `); 

        $('#row_count_bulletPoints').val(new_row)
      }

      function removeSubject(row) {
        $(row).remove();
      }
  </script>
@endsection