
<script src="<?= base_url(); ?>assets/libs/jquery.number/jquery.number.min.js"></script>
<script src="<?= base_url() ?>assets/libs/select2/select2.min.js"></script>


<script type="text/javascript">
	
  $(document).ready(function() {

      $('input[name="price_buy"]').number(true, 0);
      $('input[name="price_sale"]').number(true, 0);

      $("select[name=category]").select2({
        dropdownParent: $("#category").parent(),
        width: '100%',
        ajax: {
          url: baseUrl+'category/get-all-category-name',
          type: 'post',
          dataType: 'json',
          data: function(params) {
            return {
              name: params.term,
              page: params.page,
              limit: 30,
            };
          },
          processResults: function(data, params) {
            var more = (params.page * 30) < data.total;
            var option = [];
            $.each(data.data, function(index, item) {
              option.push({
                id: item.id,
                text: item.name,
              });
            });
            return {
              results: option,
              more: more,
            };
          },
        },
      });

      $("select[name=unit]").select2({
        dropdownParent: $("#unit").parent(),
        width: '100%',
        ajax: {
          url: baseUrl+'unit/get-all-unit-name',
          type: 'post',
          dataType: 'json',
          data: function(params) {
            return {
              name: params.term,
              page: params.page,
              limit: 30,
            };
          },
          processResults: function(data, params) {
            var more = (params.page * 30) < data.total;
            var option = [];
            $.each(data.data, function(index, item) {
              option.push({
                id: item.id,
                text: item.name,
              });
            });
            return {
              results: option,
              more: more,
            };
          },
        },
      });

  });

  $('#btn_choose').on('click',function(e) {
    e.preventDefault()

    $('#fileInput').click()

  })


  $('#fileInput').on('change',function(){
    if (this.files.length > 0) {
      var extension = $('#fileInput').val().replace(/^.*\./, '');
      if (extension == 'jpg' || extension == 'JPG' || extension == 'png' || extension == 'PNG' || 
        extension == 'gif' || extension == 'GIF' || 
        extension == 'svg' || extension == 'SVG' || extension == 'jpeg' || extension == 'JPEG') {
        $.each(this.files, function(i, v) {
          var reader = new FileReader();
          reader.onload = function(e) {
            var img = new Image();
            img.src = e.target.result;

            img.onload = function() {
              var size = $('#fileInput')[0].files[0].size;
              var canvas2 = document.createElement("canvas");

              if (size >= 340000) {
                if (img.width >= 500) {
                  var new_width2 = img.width / 4;
                  img.height = (img.height * new_width2) / img.width;
                  img.width = new_width2;
                } else {
                  img.height = img.height;
                  img.width = img.width;
                }
              } else {
                img.height = img.height;
                img.width = img.width;
              }

              var ctx2 = canvas2.getContext("2d");
              ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
              canvas2.width = img.width;
              canvas2.height = img.height;
              ctx2.drawImage(img, 0, 0, canvas2.width, canvas2.height);

              if (size >= 340000) {
                var dataURL_preview = canvas2.toDataURL(`image/${extension}`, 0.3);
              } else {
                var dataURL_preview = canvas2.toDataURL(`image/${extension}`, 0.8);
              }

              $('.upload-content').css('display','none');

              $('#image_preview').removeClass('d-none');
              $('#image_preview').addClass('d-flex');
              $('#image_preview').html(`<div class="d-flex align-items-center position-relative"> 
                    <img src="${dataURL_preview}" alt="Gambar Produk" style="max-height: 100%; max-width: 100%; object-fit: contain;">

                    <button type="button" class="btn btn-sm position-absolute bg-danger text-white btn-delete-img translate-middle rounded-circle p-1" style="transform: translate(50%, -50%);">
                      <i class="bx bx-x"></i>
                    </button>

                    <input type="hidden" name="image" style="width: 0; height: 0; display: none;" value="${dataURL_preview}">

                  </div>`);
            }
          };

          reader.readAsDataURL(this);
        });
      } else {
        iziToast.show({
          title: 'Gagal',
          message: 'Format file tidak di izinkan',
          color: 'red',
          position: 'topCenter'
        });
      }
    }
  })


  $("#form_add").on('submit',function(e){
      e.preventDefault()

      $(this).find('button[type="submit"]').html(`<div class="d-flex justify-content-center align-items-center">
                <div class="lds-ring me-2"><div></div><div></div><div></div><div></div></div>
                <span>Menyimpan</span> 
              </div>`)
      $(this).find('button[type="submit"]').attr('disabled','disabled')

      const url = '<?= base_url() ?>good/save'
    
      const formData = new FormData();
      const formData1 = $('#form_add').serializeArray();
      formData1.forEach(function(item) {
          formData.append(item.name, item.value);
      });


      $.ajax({
          url: url, 
          method: "POST", 
          contentType: false, 
          processData: false, 
          data: formData,
          success: (respon) => {
              
              if(typeof respon == 'string'){
                respon = JSON.parse(respon)
              }

              $(this).find('button[type="submit"]').html("Simpan")
              $(this).find('button[type="submit"]').attr('disabled',false)
              if(respon.success){

                  showErrorMessage({})
                  
                  iziToast.show({
                    title: 'Berhasil',
                    message: respon.message,
                    color: 'green',
                    position: 'topRight'
                  });
                
                  resetForm()

                  $('#datatable').DataTable().ajax.reload(null, false);
              }else{
                
                  
                if(typeof respon.message == "object"){
                  showErrorMessage(respon.message);
                }else{
                  showErrorMessage({})
                  iziToast.show({
                    title: 'Gagal',
                    message: respon.message,
                    color: 'red',
                    position: 'topCenter'
                  });  
                  
                }
              }

          },
          error: (jqXHR, textStatus, errorThrown) => {
                  
              $(this).find('button[type="submit"]').html("Simpan")
              $(this).find('button[type="submit"]').attr('disabled',false)
          }
      });
  })


  $("#image_preview").delegate('.btn-delete-img', 'click', function(event) {

      $('.upload-content').css('display','block');

      $('#image_preview').removeClass('d-flex');
      $('#image_preview').addClass('d-none');
      $('#image_preview').html(``);

  });


  function showErrorMessage(message){

    const target = ['name','price_buy','price_sale','category','unit','discount','description']
    if(Object.keys(message).length>0){

      target.forEach(item => {

        if(item in message){
          $(`.error-message-${item}`).html(message[item])
          $(`.error-message-${item}`).fadeIn(255)
        }else{
          $(`.error-message-${item}`).html('')
          $(`.error-message-${item}`).fadeOut(255)
        }

      })
    }else{

      target.forEach(item => {

          $(`.error-message-${item}`).html('')
          $(`.error-message-${item}`).fadeOut(255)

      })

    }

  }



  function resetForm()
  {

    $('input[name="name"]').val('')
    $('input[name="longitude"]').val('')
    $('input[name="latitude"]').val('')
    $("select[name='area']").select2('trigger','select', {
        data:{id: "", text: ""}
    });

    $('input[name="name"]').focus()

  }


</script>