@extends('layouts.app')
@section('title', __('product.add_new_shopify_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_shopify_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\ShopifyController::class, 'StoreProduct']), 'method' => 'post', 
    'id' => 'product_add_form','class' => 'product_form ' , 'files' => true ]) !!}
    @component('components.widget', ['class' => 'box-primary'])
    <div class="row">
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('name', __('product.product_name') . ':*') !!}
              {!! Form::text('name', !empty($duplicate_product->name) ? $duplicate_product->name : null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.product_name')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('category_id', __('product.category') . ':') !!}
              {!! Form::select('category_id', $productTaxonomyNodes, '', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2search', '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>
    @endcomponent
    @component('components.widget', ['class' => 'box-primary'])
    <p><strong>Product Organization :</strong></p>
    <div class="row">
      <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('product_type', __('product.product_type') . ':') !!}
              {!! Form::text('product_type', '', ['class' => 'form-control', '',
              'placeholder' => __('product.product_type')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('vendor', __('product.location_or_vendor') . ':') !!}
              {!! Form::select('vendor[]', ['CheapBookDepot' => 'Cheap Book Depot', 'UsedBookDepot' => 'Used Book Depot'], '', ['class' => 'form-control select2', 'required', 'multiple']) !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('collections', __('product.collections') . ':') !!}
              {!! Form::select('collections[]', $collections, null, ['class' => 'form-control select2search', 'required', 'multiple' => 'multiple', 'id' => 'collections']) !!}
              <label id="collections-error" class="error" for="collections" style="display: none">This field is required.</label>
          </div>
        </div>
    </div>
    @endcomponent
    @component('components.widget', ['class' => 'box-primary'])
    <p><strong>Pricing :</strong></p>
    <div class="row">
      <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>
    @endcomponent
    @component('components.widget', ['class' => 'box-primary'])
    <p><strong>Inventory :</strong></p>
    <div class="row">
      <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('barcode', __('product.barcode') . ':*') !!}
              {!! Form::text('barcode', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.barcode')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('qty', __('product.qty_on_hand') . ':*') !!}
              {!! Form::text('qty', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.qty_on_hand')]); !!}
          </div>
        </div>
    </div>
    @endcomponent
    @component('components.widget', ['class' => 'box-primary'])
    <p><strong>Shipping :</strong></p>
    <div class="row">
      <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('weight_lb', __('product.weight_lb') . ':') !!}
              {!! Form::text('weight_lb', null, ['class' => 'form-control', '',
              'placeholder' => __('product.weight_lb')]); !!}
          </div>
        </div>
    </div>
    @endcomponent
    @component('components.widget', ['class' => 'box-primary'])
    <p><strong>Product Metafields :</strong></p>
    <div class="row">
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_edition', __('product.edition') . ':*') !!}
              {!! Form::text('metafield_edition', null, ['class' => 'form-control', '',
              'placeholder' => __('product.edition')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_material_type', __('product.material_type') . ':*') !!}
              {!! Form::text('metafield_material_type', null, ['class' => 'form-control', '',
              'placeholder' => __('product.material_type')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_format', __('product.format') . ':*') !!}
              {!! Form::text('metafield_format', null, ['class' => 'form-control', '',
              'placeholder' => __('product.format')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">          
          {!! Form::label('metafield_condition', __('product.condition') . ':') !!}
              {!! Form::select('metafield_condition', $itemCondition, '', ['placeholder' => __('messages.please_select'), 'class' => 'form-control select2', 'required']) !!}            
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_publisher', __('product.publisher') . ':*') !!}
              {!! Form::text('metafield_publisher', null, ['class' => 'form-control', '',
              'placeholder' => __('product.publisher')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_publication_date', __('product.publication_date') . ':*') !!}
              {!! Form::text('metafield_publication_date', null, ['class' => 'form-control', '',
              'placeholder' => __('product.publication_date')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_languange', __('product.languange') . ':*') !!}
              {!! Form::text('metafield_languange', null, ['class' => 'form-control', '',
              'placeholder' => __('product.languange')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_print_length', __('product.print_length') . ':*') !!}
              {!! Form::text('metafield_print_length', null, ['class' => 'form-control', '',
              'placeholder' => __('product.print_length')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_isbn13', __('product.isbn13') . ':*') !!}
              {!! Form::text('metafield_isbn13', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.isbn13')]); !!}
          </div>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            {!! Form::label('metafield_isbn10', __('product.isbn10') . ':*') !!}
              {!! Form::text('metafield_isbn10', null, ['class' => 'form-control', 'required',
              'placeholder' => __('product.isbn10')]); !!}
          </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');
          $('#category_id').select2({
              placeholder: 'Find data...',
              ajax: {
                  url: '{{ route("ajax.search.categoryshopify") }}', // 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
              }
          });
          $('#collections').select2({
              placeholder: 'Find data...',
              ajax: {
                  url: '{{ route("ajax.search.collectionshopify") }}', // sesuaikan dengan route kamu
                  dataType: 'json',
                  delay: 250,
                  data: function (params) {

                      return {
                          q: category_param_search || 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 collections = $('#collections').val(); // Get selected values
          console.log("collections");
          console.log(collections);
          if (!collections || collections.length === 0) {
            // alert('Please select at least one collection.');
            $('#collections-error').css('display', 'block');
            $('#collections-error').text('This field is required.');            
          } else {          
            $('#collections-error').css('display', 'none');
            $('#collections-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];
                  callKeepaApi(items.asin);
                  $('#name').val(items.attributes.item_name[0].value);
                  $('#product_type').val(items.productTypes[0].productType);
                  $('#price').val(items.attributes.list_price[0].value);
                  $('#barcode').val(items.asin);
                  $('#weight_lb').val(items.dimensions[0].item.weight.value);                  
                  $('#metafield_material_type').val(items.attributes.binding[0].value);
                  $('#metafield_publisher').val(items.attributes.author[0].value);
                  $('#metafield_publication_date').val(items.summaries[0].releaseDate);
                  $('#metafield_languange').val(items.attributes.language[0].value);
                  $('#metafield_print_length').val(items.attributes.pages[0].value);
                  $('#metafield_isbn13').val(input);
                  $('#metafield_isbn10').val(items.asin);      
                  // category_param_search = items.salesRanks[0].classificationRanks[0].title;
                  // console.log("category_found");                  
                  // console.log(category_param_search);                  
                  // $('#category_id').trigger('change');
                  // setTimeout(() => {
                  //   console.log("category_found");                  
                  //   console.log(category_found);                  
                  //   $('#category_id').val(category_param_search);
                  //   if(!category_found) {
                  //     category_param_search = items.classifications[0].classifications[0].displayName;
                  //     $('#category_id').val(category_param_search).trigger('change');
                  //   }
                  // }, 500);
                  
                  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);
                  });
                  
                  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();
          }
      });
  </script>
@endsection