<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=package]").select2({
        dropdownParent: $("#package").parent(),
        width: '100%',
        ajax: {
          url: baseUrl+'package/get-all-package-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=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,
            };
          },
        },
      });

      $("#village").select2({
        dropdownParent: $("#village").parent(),
        width: '100%',
        ajax: {
          url: baseUrl+'area/village/get-all-village-name',
          type: 'post',
          dataType: 'json',
          data: function(params) {
            return {
              name: params.term,
              page: params.page,
              limit: 30,
              parentId: $("select[name=subdistrict]").val()
            };
          },
          processResults: function(data, params) {
            var more = (params.page * 30) < data.total;
            var option = [];
            console.log(data)
            if($("select[name=subdistrict]").val()==''||$("select[name=subdistrict]").val()==null){
              data.data = []
            }


            $.each(data.data, function(index, item) {
              option.push({
                id: item.id,
                text: item.name,
              });
            });
            return {
              results: option,
              more: more,
            };
          },
        },
      });


  });

  $("select[name=subdistrict]").on('change',function(e) {

    e.preventDefault()

    $("select[name='village']").select2('trigger','select', {
        data:{id: "", text: ""}
    });

  })



  $("#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() ?>customer/save'
      const data = {
        name: $("input[name='name']").val(),
        phone: $("input[name='phone']").val(),
        package: $("select[name='package']").val(),
        subdistrict: $("select[name='subdistrict']").val(),
        village: $("select[name='village']").val(),
        description: $("textarea[name='description']").val(),
      }
    
      
      $.ajax({
          url: url, 
          method: "POST", 
          data,
          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'
                  });
                
                  $("input[name='name']").val('')
                  $("input[name='phone']").val('')
                  $("select[name='package']").select2('trigger','select', {
                      data:{id: "", text: ""}
                  });
                  $("select[name='subdistrict']").select2('trigger','select', {
                      data:{id: "", text: ""}
                  });
                  $("select[name='village']").select2('trigger','select', {
                      data:{id: "", text: ""}
                  });
                  $("textarea[name='description']").val('')

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

                  $('#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','phone','description','subdistrict','village','package']
    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)
      })
    }

  }




</script>