<link href="<?= base_url(); ?>assets/libs/select2/select2.min.css" rel="stylesheet" type="text/css" />
<script src="<?= base_url() ?>assets/libs/select2/select2.min.js"></script>
<script src="<?= base_url(); ?>assets/libs/jquery.number/jquery.number.min.js"></script>

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

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

      $("select[name=type]").select2({
        dropdownParent: $("#type").parent(),
        width: '100%',
        placeholder: "Pilih Jenis Pengeluaran"
      });

  });


  $('#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'
        });
      }
    }
  })


  $("#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(``);

  });


  $("#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() ?>out/save'
      const data = {
        name: $("input[name='name']").val()
      }
    
      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) => {
                      
              $(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)
          }
      });
  })


  function showErrorMessage(message){

    const target = ['date','type','total','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="tanggal"]').val('')
    $('input[name="total"]').val('')
    $('textarea[name="description"]').val('')
    $("select[name='type']").select2('trigger','select', {
        data:{id: "", text: ""}
    });

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

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

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

  }


</script>