<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 type="text/javascript">
  
  $(document).ready(function() {
      $("select[name=subdistrict]").select2({
        dropdownParent: $("#subdistrict").parent(),
        width: '100%',
        ajax: {
          url: baseUrl+'area/subdistrict/get-all-subdistrict-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,
            };
          },
        },
      });

  });

  $("#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() ?>area/village/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 = ['name','subdistrict']
    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('')
    $("select[name='subdistrict']").select2('trigger','select', {
        data:{id: "", text: ""}
    });

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

  }


</script>