
<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() {
    const row = JSON.parse('<?= json_encode($row) ?>');
    
    // Fungsi untuk inisialisasi Select2 dengan Promise
    function initSelect2(selector, config, valueData) {
        return new Promise((resolve) => {
            const $select = $(selector).select2(config);
            
            // Untuk Select2 yang menggunakan AJAX, kita perlu menunggu sampai siap
            if (config.ajax) {
                // Buat option baru dan trigger select
                const newOption = new Option(valueData.text, valueData.id, true, true);
                $select.append(newOption).trigger('change');
                
                // Trigger custom event ketika siap
                $select.one('select2:select', function() {
                    resolve($select);
                });
                
                // Trigger select event
                $select.trigger('select2:select');
            } else {
                // Untuk Select2 non-AJAX, langsung resolve
                resolve($select);
            }
        }).then(($select) => {
            if (valueData) {
                // Set nilai setelah Select2 siap
                $select.val(valueData.id).trigger('change');
            }
            return $select;
        });
    }

    // 1. Inisialisasi Package Select2
    initSelect2("select[name=package_edit]", {
        dropdownParent: $("#package_edit").parent(),
        width: '100%',
        ajax: {
            url: baseUrl+'package/get-all-package-name',
            type: 'post',
            dataType: 'json',
            delay: 250,
            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,
                    pagination: {
                        more: more
                    }
                };
            },
            cache: true
        },
        minimumInputLength: 0,
        placeholder: 'Pilih Paket'
    }, {
        id: row.package_id, 
        text: row.packageName
    })
    .then(() => {
        // 2. Setelah Package selesai, inisialisasi Subdistrict
        return initSelect2("select[name=subdistrict_edit]", {
            dropdownParent: $("#subdistrict_edit").parent(),
            width: '100%',
            ajax: {
                url: baseUrl+'area/subdistrict/get-all-subdistrict-name',
                type: 'post',
                dataType: 'json',
                delay: 250,
                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,
                        pagination: {
                            more: more
                        }
                    };
                },
                cache: true
            },
            minimumInputLength: 0,
            placeholder: 'Pilih Kecamatan'
        }, {
            id: row.subdistrict_id, 
            text: row.subdistrictName
        });
    })
    .then(() => {
        // 3. Setelah Subdistrict selesai, inisialisasi Village
        return initSelect2("select[name=village_edit]", {
            dropdownParent: $("#village_edit").parent(),
            width: '100%',
            ajax: {
                url: baseUrl+'area/village/get-all-village-name',
                type: 'post',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        name: params.term,
                        page: params.page,
                        limit: 30,
                        parentId: $("#subdistrict_edit").val() // Gunakan subdistrict_id dari row
                    };
                },
                processResults: function(data, params) {
                    var more = (params.page * 30) < data.total;
                    var option = [];

                    if(row.subdistrict_id==''||row.subdistrict_id==null){
                      data.data = []
                    }

                    $.each(data.data, function(index, item) {
                        option.push({
                            id: item.id,
                            text: item.name,
                        });
                    });
                    return {
                        results: option,
                        pagination: {
                            more: more
                        }
                    };
                },
                cache: true
            },
            minimumInputLength: 0,
            placeholder: 'Pilih Desa/Kelurahan'
        }, {
            id: row.village_id, 
            text: row.villageName
        });
    })
    .catch(error => {
        console.error('Error initializing Select2:', error);
    });
});

    
  $("select[name=subdistrict_edit]").on('change',function(e) {
    
    e.preventDefault()
    // Kosongkan dulu select
    const select = $("select[name='village_edit']");
    select.empty();

    // Tambahkan opsi kosong
    select.append($('<option>', {
        value: '',
        text: 'Pilih Desa/Kelurahan'
    }));

    // Trigger change
    select.trigger('change');
  })



  $("#form_edit").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/update'
      const data = {
        id: $(this).find("input[name='hide_id']").val(),
        name: $(this).find("input[name='name']").val(),
        phone: $(this).find("input[name='phone']").val(),
        package: $(this).find("select[name='package_edit']").val(),
        subdistrict: $(this).find("select[name='subdistrict_edit']").val(),
        village: $(this).find("select[name='village_edit']").val(),
        description: $(this).find("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_edit']").select2('trigger','select', {
                      data:{id: "", text: ""}
                  });
                  $("select[name='subdistrict_edit']").select2('trigger','select', {
                      data:{id: "", text: ""}
                  });
                  $("select[name='village_edit']").select2('trigger','select', {
                      data:{id: "", text: ""}
                  });
                  $("textarea[name='description']").val('')

                  $("input[name='name']").focus()
                  $("#modal_edit").modal('hide')

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

