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

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


  
  function loadData() {
    $('#datatable').DataTable({
      "pageLength": 10,
      "serverSide": true,
      "processing": true,
      "scrollX": true,
      "order": [
        [0, "desc"]
      ],
      "columnDefs": [
        {
          targets: [0,1,2,3,4],
          className: "text-center"
        },
        {
          orderable: false,
          targets: [3,4]
        }
      ],
      "ajax": {
        url: base_url + 'history/get-all-data',
        type: 'POST',
        data: {
          // category_id : $("#category_id_filter").val()
        },
      },
      "columns": [{
          data: "no"
        },
        {
          data: "start_date"
        },
        {
          data: "end_date"
        },
        {
          data: "status"
        },
        {
          data: "total"
        },
      ],
      "destroy": true
    }); // End of DataTable
  }


  $("#btn_add").on('click',function(){
    $('#modal_content').html(modal_loading_animation);
    $('#modal_add').modal('show');
    $('#modal_content').load(base_url + 'sac/add');
  })



  $('#datatable').delegate('.datatable-edit', 'click', function() {
    var url = $(this).attr('data-link');
    $('#modal_content').html(modal_loading_animation);
    $('#modal_add').modal('show');
    $('#modal_content').load(url);
  });

  $('#datatable').delegate('.datatable-detail', 'click', function() {
    var url = $(this).attr('data-link');
    $('#modal_content').html(modal_loading_animation);
    $('#modal_add').modal('show');
    $('#modal_content').load(url);
  });


  $("#btn_upload").on('click',function(e){
    e.stopPropagation()

    $("#modal_upload").modal('show')
    $("#upload_container").html(`<div class="alert upload-triger alert-secondary mb-0" role="alert" style="cursor: pointer;">
            <div class="w-100 d-flex justify-content-center align-items-center flex-column">
              <i class="dripicons-cloud-upload" style="font-size: 28px;"></i>
              <span>Click to upload the excel</span>
            </div>
        </div>`)
        $('input[name="upload-triger"]').val('')
  })


  $("#upload_container").delegate('.upload-triger','click',function(){
    $('input[name="upload-triger"]').click()
  })

  $('input[name="upload-triger"]').on('change',function(){

    var file = this.files[0]; 
      if (file) {
          var fileName = file.name;
          var fileExtension = fileName.split('.').pop().toLowerCase(); 

          var allowedExtensions = ['xlsx', 'xlsm', 'xlsb', 'xltx', 'xls'];

          if (allowedExtensions.includes(fileExtension)) {
              
        $("#upload_container").html(`<div class="alert upload-triger alert-success mb-0 px-2" role="alert" style="cursor: pointer;">
                    <div class="w-100 d-flex justify-content-between align-items-center ">
                      <div>
                        <i class="fas fa-file-excel me-1" style="font-size: 16px;"></i>
                        <span style="font-size: 14px;">${fileName}</span>
                      </div>
                      <div>
                        <button class="btn btn-xs btn-danger btn-delete-xcl">
                          <i style="font-size: 12px;" class="fas fa-trash-alt"></i>
                        </button>
                      </div>
                    </div>
                </div>`)
              
          } else {
              iziToast.show({
          title: 'Gagal',
          message: 'Format file tidak di izinkan',
          color: 'red',
          position: 'topCenter'
        });
          }
      }
  })


  $("#upload_container").delegate('.btn-delete-xcl','click',function(e){
    e.stopPropagation();
    $("#upload_container").html(`<div class="alert upload-triger alert-secondary mb-0" role="alert" style="cursor: pointer;">
            <div class="w-100 d-flex justify-content-center align-items-center flex-column">
              <i class="dripicons-cloud-upload" style="font-size: 28px;"></i>
              <span>Click to upload the excel</span>
            </div>
        </div>`)

  })

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

    var file = $('input[name="upload-triger"]')[0].files[0];
    var formData = new FormData();
        formData.append('file_excel', file);

        $(this).find('button[type="submit"]').html("Menyimpan...")
        $(this).find('button[type="submit"]').attr('disabled','disabled')

        $.ajax({
            url: '<?= base_url() ?>sac/upload_excel',
            type: 'POST',
            data:  formData,
            contentType: false,
            processData: false,
            cache: false,
            dataType: 'json',
            success: (response) => {

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

                if(response.code==200){
                  if(response.success){

                    iziToast.show({
              title: 'Berhasil',
              message: response.message,
              color: 'green', // blue, red, green, yellow
              position: 'topRight'
            });
                    $("#modal_upload").modal('hide')
                    $('#datatable').DataTable().ajax.reload(null, false);

                  }else{
                    iziToast.show({
              title: 'Gagal',
              message: response.message,
              color: 'red', // blue, red, green, yellow
              position: 'topRight'
            });
                  }
                }else{
                  iziToast.show({
            title: 'Terjadi Kesalahan',
            message: 'Silahkan coba lagi.',
            color: 'red', // blue, red, green, yellow
            position: 'topRight'
          });
                }
            },
            error: () => {

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

              iziToast.show({
          title: 'Terjadi Kesalahan',
          message: 'Silahkan coba lagi.',
          color: 'red', // blue, red, green, yellow
          position: 'topRight'
        });
            }
        });


  })



</script>