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

     $('#karyawan').select2({
        placeholder: 'Pilih Karyawan',
        allowClear: true,
        ajax: {
          url: '<?= route("dropdown.karyawan") ?>',
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
          return {
                  results: data
              };
          },
          cache: false
      },
      minLength: 3
    });

     $('#jenis').select2({
            placeholder: 'Pilih Jenis Izin',
            allowClear: true,
            ajax: {
              // type: 'POST',
              url: '<?= site_url("pengajuan/izin/get-jenis-form")  ?>',
              dataType: 'json',
              delay: 250,
              processResults: function (data) {
              return {
                      results: data
                  };
              },
              cache: false
          },
          minLength: 3
        });  
});     

$(document).on('click','#btn_baru', function(){
    var gambar = $('#form_input #file').dropify();
            gambar = gambar.data('dropify');
            gambar.resetPreview();
            gambar.clearElement();

    $('#form_input input[type=text]').prop("disabled",false);
    $("#form_input input[type=text]").val('');
    $('#form_input input[type=date]').prop("disabled",false);
    $("#form_input input[type=date]").val('');
    $('#form_input input[type=file]').prop("disabled",false);
    $("#form_input input[type=file]").val('');
    $("#keterangan").prop("disabled", false);
    $("#keterangan").val('');
    $("#btn_kembali").prop("disabled", false);
    $("#cabang, #departemen, #jenis, #karyawan").prop("disabled", false);
    $("#cabang").val('').trigger('change');
    $("#departemen").val('').trigger('change');
    $("#jenis").val('').trigger('change');
    $("#karyawan").val('').trigger('change');
    
    $('#btn_simpan').show();
    $('#btn_baru').hide();
    $('#message').hide();
});

$(document).on("click","#btn_simpan",function(e){
    e.preventDefault();
    $('#message').html("");
    var loading = Ladda.create(this);

    if($("#karyawan").val() ==null){
        $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Karyawan belum diiisi</font>");
        $('#karyawan').focus();
        return false;
    }else if($("#jenis").val() ==null){
        $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Jenis belum diiisi</font>");
        $('#jenis').focus();
        return false;
    }else if($("#tanggal_mulai").val() ==""){
        $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Tanggal Mulai belum diisi</font>");
        $('#tanggal_mulai').focus();
        return false;
    }else if($("#tanggal_selesai").val() ==""){
        $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Tanggal Selesai belum diisi</font>");
        $('#tanggal_selesai').focus();
        return false;
    }
    
    loading.start();

    var param = new FormData();
              param.append('tanggal_mulai',$("#tanggal_mulai").val());
              param.append('tanggal_selesai',$("#tanggal_selesai").val());
              param.append('jenis',$("#jenis").val());
              param.append('karyawan',$("#karyawan").val());
              param.append('keterangan',$("#keterangan").val());
              param.append('file',$('#file').prop('files')[0]);
              param.append('file_lama',$("#file_lama").val());
              param.append('id_izin',$("#id_izin").val());

    $.ajax({
        type: 'POST',
        url: "<?= site_url('pengajuan/izin/save') ?>",
        data: param,
        dataType:'JSON',
        contentType: false,
        processData: false,
        cache: false,
        success: function(result) {
            if(result.success == true){
                if(result.type == 'save'){
                  $("#form_input :input").prop("disabled", true);
                  $("#btn_kembali").prop("disabled", false);
                  $("#keterangan").prop("disabled", true);
                  $("#cabang, #departemen, #jenis, #karyawan").prop("disabled", true);
                  $('#btn_simpan').hide();
                  $('#btn_baru').show();
                  $("#btn_baru").prop("disabled", false);
                }
            }
            loading.stop();
            $('#message').show();
            $('#message').html(result.message);
        },
        error:function(){
            loading.stop();
            $('#message').show();
            $('#message').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
        }
    });
});
</script>
<div class="content-header">
    <div class="row align-items-center">
        <div class="content-header-left col-md-6 col-12 mb-md-0 mb-1">
            <h3 class="content-header-title"><?= $judul ?></h3>
            <div class="row breadcrumbs-top">
                <div class="breadcrumb-wrapper col-12">
                    <ol class="breadcrumb">
                        </li>
                        <li class="breadcrumb-item"><a href="#">Pengaturan</a>
                        </li>
                        <li class="breadcrumb-item active"><?= $judul ?>
                        </li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card card-rounded">
    <div class="card-content">
        <div id="form_input" class="card-body">
            <div class="row filter">
				<div class="col-md-6">

                    <?php 
                        if ($ref === 0) {
                            $disable = '';
                        }
                        else{
                            $disable ='disabled="disabled"';
                        } 

                        if ($ref == md5($data->id_izin) && $data->status == '4') {
                            $disable_jenis ='disabled="disabled"';
                        }else{
                            $disable_jenis = '';
                        }
                    ?>

                    <label>Karyawan</label>
                    <select class="form-control" name="karyawan" id="karyawan" class="select2 form-control" <?=$disable?> style="border-radius: 5px; width: 100%;">
                       <?php
                            $id_karyawan = $data->id_karyawan;
                            if ($id_karyawan != null) {
                                $selected_karyawan = $this->db->query("SELECT id_karyawan, nama_lengkap FROM data_karyawan WHERE id_karyawan = '".$id_karyawan."'");
                        ?>
                            <option value="<?=$id_karyawan?>" selected><?=((isset($selected_karyawan->row()->nama_lengkap))?$selected_karyawan->row()->nama_lengkap:'')?></option>
                        <?php
                            }
                        ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label>Jenis</label>
                    <select class="form-control" name="jenis" id="jenis" class="select2 form-control" <?=$disable_jenis?> style="border-radius: 5px; width: 100%;">
                        <?php
                            $id_jenis = $data->kode_izin;
                            if ($id_jenis != null) {
                                $selected_jenis = $this->db->query("SELECT id_jenis_izin, kode_izin, nama FROM master_jenis_izin WHERE kode_izin = '".$id_jenis."'");
                        ?>
                            <option value="<?=$id_jenis?>" selected><?=((isset($selected_jenis->row()->nama))?$selected_jenis->row()->nama:'')?></option>
                        <?php
                            }
                        ?>
                    </select>
                </div>
            </div><br>
            <div class="row filter">
                <div class="col-md-6">
                    <label>Tanggal Mulai</label>
                    <?php
                        if (isset($data)) {
                            $tgl_mulai = date('d-m-Y', strtotime($data->tgl_mulai_izin));
                        }else{
                            $tgl_mulai = "";
                        }
                    ?>
                    <input type="text" name="tanggal_mulai" id="tanggal_mulai" class="form-control datepicker" <?=$disable?> placeholder="dd-mm-yyyy" value="<?= $tgl_mulai ?>" autocomplete="off">
                </div>
                 <div class="col-md-6">
                    <label>Tanggal Selesai <span id="jumlah_pengajuan"></span></label>
                    <?php
                        if (isset($data)) {
                            $tgl_selesai = date('d-m-Y', strtotime($data->tgl_selesai_izin));
                        }else{
                            $tgl_selesai = "";
                        }
                    ?>
                    <input type="text" name="tanggal_selesai" id="tanggal_selesai" class="form-control datepicker" <?=$disable?> placeholder="dd-mm-yyyy" value="<?= $tgl_selesai ?>" autocomplete="off">
                </div>                 
            </div><br>
            <div class="row filter">
                 <div class="col-md-12">
                    <label>Keterangan</label>
                    <textarea id="keterangan" class="form-control"><?= ((isset($data))?$data->ket_izin:'') ?></textarea>
                </div>                 
            </div><br>
            <div class="row filter">
                 <div class="col-md-3">
                    <label>File Upload</label>
                     <?php 
                        if ($data->file == "") {
                            $file = "";
                        } else {
                            $file = $this->config->item('base_image').'image?_t=photo&_d='.$data->file;
                        } 
                    ?>
                    <input type="file" name="file" id="file" id="input-file-now-custom-1" class="dropify" data-default-file="<?= $file ?>"/>
                    <input type="hidden" name="file_lama" id="file_lama" value="<?= $data->file ?>">
                </div>                 
            </div><br>
            <div class="row">
                 <div class="col-md-7 text-left">
                    <div id="message"></div>
                </div>
                <div class="col-md-5 text-right">
                    <input type="hidden" name="id_izin" id="id_izin" value="<?= ((isset($data))?md5($data->id_izin):'') ?>">
                    <!-- <a onclick="" class="btn btn-secondary" style="color: white;">KEMBALI</a> -->
                    <button type="button" class="btn btn-secondary" onclick="window.history.go(-1); return false;" id="btn_kembali">KEMBALI</button>
                    <button type="button" class="btn btn-primary" id="btn_baru" style="display: none;">TAMBAH BARU</button>
                    <button type="button" class="btn btn-success ladda-button" name="tombol_submit" id="btn_simpan"><?= (isset($ref) and $ref == '0') ? 'SIMPAN' : 'UBAH' ?></button>
                </div>
            </div>
            <br><br>
        </div>
    </div>
</div>
<script>
    $(document).ready(function() {
        // Basic
        $('.dropify').dropify();

        // Translated
        $('.dropify-fr').dropify({
            messages: {
                default: 'Glissez-déposez un fichier ici ou cliquez',
                replace: 'Glissez-déposez un fichier ou cliquez pour remplacer',
                remove: 'Supprimer',
                error: 'Désolé, le fichier trop volumineux'
            }
        });

        // Used events
        var drEvent = $('#input-file-events').dropify();

        drEvent.on('dropify.beforeClear', function(event, element) {
            return confirm("Do you really want to delete \"" + element.file.name + "\" ?");
        });

        drEvent.on('dropify.afterClear', function(event, element) {
            alert('File deleted');
        });

        drEvent.on('dropify.errors', function(event, element) {
            console.log('Has Errors');
        });

        var drDestroy = $('#input-file-to-destroy').dropify();
        drDestroy = drDestroy.data('dropify')
        $('#toggleDropify').on('click', function(e) {
            e.preventDefault();
            if (drDestroy.isDropified()) {
                drDestroy.destroy();
            } else {
                drDestroy.init();
            }
        });
        
        <?php if(!isset($data)) { ?>
        count_leave();
		<?php } ?>
    });
    
    function count_leave() {
		//jika tanggal mulai dan selesai tidak kosong maka hitung jumlah 
		$('#tanggal_mulai, #tanggal_selesai, #karyawan').change(function() {
			var tanggal_mulai 	= $('#tanggal_mulai').val();
			var tanggal_selesai = $('#tanggal_selesai').val();
			var id_karyawan		= $('#karyawan').val();
			if(tanggal_mulai != '' && tanggal_selesai != '' && id_karyawan != null) {
				get_holidays(id_karyawan, tanggal_mulai, tanggal_selesai);
			}
		});
	}
	
	function date_id_to_date_const(date) {
		//konversi tanggal dd-mm-YYYY ke date object
		var array_date 	= date.split('-');
		var day			= array_date[0];
		var month		= array_date[1];
		var year		= array_date[2];
		return new Date(year, month, day);
	}
	
	function date_diff(id_karyawan, date_start, date_end) {
		//menampilkan selisih hari
		const date1 = date_id_to_date_const(date_start);
		const date2 = date_id_to_date_const(date_end);
		const diffTime = Math.abs(date2 - date1);
		const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
		var holidays = get_holidays(id_karyawan, date_start, date_end);
		return (diffDays+1)-holidays;
	}
	
	function get_holidays(id_karyawan, date_start, date_end) {
		//mendapatkan jumlah hari libur
		$.get("<?= site_url('pengajuan/izin/get_holidays'); ?>", 
			{id_karyawan : id_karyawan, date_start : date_start, date_end : date_end}, 
			function(result) {
				$('#jumlah_pengajuan').html('(total izin '+result+' hari)');
			}
		);
	}
</script>  







