<script type="text/javascript">
    $(document).ready(function() {
        $('#karyawan').select2({
            placeholder: "<?= $this->lang->line('pilih_karyawan') ?>",
            allowClear: true,
            ajax: {
                url: '<?= route("dropdown.karyawan.list.izin") ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        });

        $('#jenis').select2({
            placeholder: "<?= $this->lang->line('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
        });

        <?php if (!isset($data)) : ?>
            $('#tanggal_mulai, #tanggal_selesai, #karyawan, #jenis').change(function() {
                count_leave();
            });
        <?php endif; ?>
    });

    $(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');
        // $("#file").addClass("dropify-clear");

        $('#btn_simpan').show();
        $('#btn_baru').hide();
        $('#message_izin').hide();
        var total_izin = '<?= $this->lang->line('total_izin'); ?> 0 <?= $this->lang->line('hari'); ?>';
        $('#jumlah_pengajuan').html(total_izin.toLowerCase());
    });

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

        var ekstensi = /(\.jpg|\.jpeg|\.png)$/i;

        if ($("#karyawan").val() == null) {
            $('#message_izin').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_pilih_karyawan') ?></font>");
            $('#karyawan').focus();
            return false;
        } else if (!$("#jenis").val()) {
            $('#message_izin').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_pilih_jenis_izin') ?></font>");
            $('#jenis').focus();
            return false;
        } else if ($("#tanggal_mulai").val() == "") {
            $('#message_izin').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_isi_tanggal_mulai') ?></font>");
            $('#tanggal_mulai').focus();
            return false;
        } else if ($("#tanggal_selesai").val() == "") {
            $('#message_izin').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_isi_tanggal_selesai') ?></font>");
            $('#tanggal_selesai').focus();
            return false;
        } else if ($("#file").val()) {
            if ($("#file").val() == "") {
                return true;
            } else if (!ekstensi.exec($("#file").val())) {
                $('#message_izin').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_validasi_file') ?></font>");
                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());
        param.append('hari', $("#hari").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_izin').show();
                $('#message_izin').html(result.message);
            },
            error: function() {
                loading.stop();
                $('#message_izin').show();
                $('#message_izin').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong><?= $this->lang->line('error') ?></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 class="breadcrumb-item"><a href="#"><?= $this->lang->line('menu_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">
            <?php
            if ($data->status != '1') {
                if ($ref === 0) {
                    $disable = '';
                } else {
                    $disable = 'disabled="disabled"';
                }
            }
            ?>
            <div class="row filter">
                <div class="col-md-6">
                    <label><?= $this->lang->line('karyawan') ?><span class="text-danger">*</span></label>
                    <select class="form-control" name="karyawan" id="karyawan" class="select2 form-control" <?= $disable ?> style="border-radius: 5px; width: 100%;">
                        <?php if ($data->id_karyawan != null) : ?>
                            <option value="<?= $data->id_karyawan ?>" selected><?= ($data->nama_lengkap ?: '') ?></option>
                        <?php endif; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label><?= $this->lang->line('jenis_izin') ?><span class="text-danger">*</span></label>
                    <select class="form-control" name="jenis" id="jenis" class="select2 form-control" <?= $disable ?> style="border-radius: 5px; width: 100%;">
                        <?php if ($data->kode_izin != null) : ?>
                            <option value="<?= $data->kode_izin ?>" selected><?= ($data->nama_izin ?: '') ?></option>
                        <?php endif; ?>
                    </select>
                </div>
            </div><br>
            <div class="row filter">
                <div class="col-md-6">
                    <label><?= $this->lang->line('tgl_mulai') ?><span class="text-danger">*</span></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" placeholder="dd-mm-yyyy" value="<?= $tgl_mulai ?>" autocomplete="off" <?= $disable ?>>
                </div>
                <div class="col-md-6">
                    <label><?= $this->lang->line('tgl_selesai') ?><span class="text-danger">*</span> <span style="font-size: 12px; background-color: #76a2cf;" class="badge" 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" placeholder="dd-mm-yyyy" value="<?= $tgl_selesai ?>" autocomplete="off" <?= $disable ?>>
                </div>
            </div><br>
            <div id="msg_absensi" class="alert alert-warning" role="alert" style="display: none">
                <span>
                    <?= $this->lang->line('error_absensi_exist'); ?>
                </span>
            </div>
            <div class="row filter">
                <div class="col-md-12">
                    <label><?= $this->lang->line('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_izin"></div>
                </div>
                <div class="col-md-5 text-right">
                    <input type="hidden" name="hari" id="hari" disabled>
                    <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"><?= $this->lang->line('button_form_kembali'); ?></button>
                    <button type="button" class="btn btn-primary" id="btn_baru" style="display: none;"><?= $this->lang->line('button_form_tambah_baru'); ?></button>
                    <button type="button" class="btn btn-success ladda-button" name="tombol_submit" id="btn_simpan" data-style="expand-left"><?= (isset($ref) and $ref == '0') ? $this->lang->line('button_form_simpan') : $this->lang->line('button_form_perbarui') ?></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();
            }
        });
    });

    function count_leave() {
        //jika tanggal mulai dan selesai tidak kosong maka hitung jumlah
        const tanggal_mulai = $('#tanggal_mulai').val();
        const tanggal_selesai = $('#tanggal_selesai').val();
        const id_karyawan = $('#karyawan').val();
        const kode = $('#jenis').val();
        if (tanggal_mulai != '' && tanggal_selesai != '' && id_karyawan != null && kode != null) {
            $.get("<?= route('pengajuan.izin.flag.cuti'); ?>", {
                kode: kode
            }).done(function(data) {
                if (data != 1) {
                    date_diff(id_karyawan, tanggal_mulai, tanggal_selesai);
                } else {
                    date_diff(null, tanggal_mulai, tanggal_selesai);
                }
            });
            // cek apakah sudah ada data absensi
            $.get("<?= route('pengajuan.izin.cek.absensi'); ?>", {
                id_karyawan: id_karyawan,
                date_start: tanggal_mulai,
                date_end: tanggal_selesai
            }).done(function(data) {
                if (data) {
                    $("#msg_absensi").slideDown(250);
                } else {
                    $("#msg_absensi").slideUp(250);
                }
            });
        }
    }

    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 = null, 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));
        if (id_karyawan) {
            get_holidays(id_karyawan, date_start, date_end);
        } else {
            var total_izin = '<?= $this->lang->line('total_izin'); ?> ' + (diffDays + 1) + ' <?= $this->lang->line('hari'); ?>';
            $('#jumlah_pengajuan').html(total_izin.toLowerCase());
            $("#hari").val((diffDays + 1));
        }
        return false;
    }

    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(data) {
            var total_izin = '<?= $this->lang->line('total_izin'); ?> ' + data + ' <?= $this->lang->line('hari'); ?>';
            $('#jumlah_pengajuan').html(total_izin.toLowerCase());
            $("#hari").val(data);
        });
    }
</script>
