<div class="card">
    <div class="card-body">
        <div class="row">
            <div class="col-md-6 d-flex align-items-center">
                <a href="#" class="btn_kembali_team"><img width="30px" style="margin-top: -5px;" src="<?= base_url('assets/images/icon/arrow-left-icon.png') ?>"></a>
                <h4 class="text-primary" style="margin-left: 15px;">KPI Karyawan</h4>
            </div>
            <div class="col-md-6 text-right">
                <div class="col" style="padding-right: 0px;"><?= $validasiPeriode ?></div>
            </div>
        </div>
        <hr>
        <div class="row">
            <div class="col-md-3">
                <div class="row">
                    <div class="col">
                        <span>Periode</span>
                        <h6 style="font-family: 'Poppins Bold';"><?= $data['periode'] ?></h6>
                    </div>
                    <div class="col">
                        <span>Nama</span>
                        <h6 style="font-family: 'Poppins Bold';"><?= $data['data_karyawan']->nama_lengkap ?></h6>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="row">
                    <div class="col">
                        <span>NIK</span>
                        <h6 style="font-family: 'Poppins Bold';"><?= $data['data_karyawan']->nik ?></h6>
                    </div>
                    <div class="col">
                        <span>Jabatan</span>
                        <h6 style="font-family: 'Poppins Bold';"><?= $data['data_karyawan']->nama_jabatan ?></h6>
                    </div>
                </div>
            </div>
            <div class="col-md-6 text-right">
                <div class="row">
                    <div class="col"></div>
                    <div id="div_tambah" class="col-8"></div>
                    <div id="div_publish" class="col"></div>
                </div>
            </div>
        </div>
        <input type="hidden" id="karyawan" name="karyawan" value="<?= $data['data_karyawan']->id_karyawan ?>">
        <input type="hidden" id="tahun" name="tahun" value="<?= $data['tahun'] ?>">
        <input type="hidden" id="bulan" name="bulan" value="<?= $data['bulan'] ?>">
        <table class="table table-striped table-bordered mt-3" width=100%>
            <thead style="font-family: Poppins SemiBold;">
                <tr>
                    <th class="align-middle" rowspan=2 width=150>Obyektif</th>
                    <th class="align-middle" rowspan=2>Performa Indikator</th>
                    <th rowspan=2 width=100 class="_center align-middle">Target</th>
                    <th rowspan=2 width=100 class="_center align-middle">Bobot</th>
                    <th class="align-middle" colspan=5>Skoring</th>
                    <th rowspan=2 width=100 class="_center align-middle">Aksi</th>
                </tr>
                <tr>
                    <th width=120 class="_center">1</th>
                    <th width=120 class="_center">2</th>
                    <th width=120 class="_center">3</th>
                    <th width=120 class="_center">4</th>
                    <th width=120 class="_center">5</th>
                </tr>
            </thead>
            <tbody></tbody>
            <tfoot>
                <tr height=50>
                    <th class="align-middle text-center" colspan=3 style="font-family: 'Poppins Bold';">Total</th>
                    <th class="align-middle" style="font-family: 'Poppins Bold';">0%</th>
                    <th colspan=6></th>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<!-- START TAMPIL MODAL -->
<div id="modal_form_lg" class="modal fade in" data-keyboard="false" data-backdrop="static" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div id="tampil_form_lg" class="modal-content"></div>
    </div>
</div>
<!-- END TAMPIL MODAL -->

<!-- modal hapus -->
<div id="modal_hapus" class="modal fade in">
    <div class="modal-dialog modal-md">
        <div id="tampil_hapus" class="modal-content">
            <input type="hidden" id="id_pi">
            <div class="card-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h3 class="title modal-title"></h3>
            </div>
            <div class="card-footer">
                <div class="row">
                    <div class="col-md-7 text-left">
                        <div id="message"></div>
                    </div>
                    <div class="col-md-5 text-right">
                        <button class="btn_hapus btn btn-danger ladda-button" id="btn_hapus" data-style="expand-left"><i class="fa fa-trash"></i> HAPUS</button>
                    </div>
                </div><!-- ./row -->
            </div>
        </div>
    </div>
</div>
<script>
    $(function() {
        list_data = $('table').DataTable({
            ordering : false,
            paging   : false,
            searching: false,
            scrollX  : true,
            info     : false,
            language : {
                url: '<?= base_url("assets/plugins/datatables/dataTables-language-id.json") ?>'
            },
            columnDefs: [
                { targets: '_center', className: 'text-center' }
            ],
            ajax: {
                url: '<?= route("kpi.team.detail.list.data") ?>',
                data: function(d) {
                    delete d.columns;
                    delete d.search;
    
                    d.karyawan = $('#karyawan').val();
                    d.tahun    = $('#tahun').val();
                    d.bulan    = $('#bulan').val();
                }
            },
            drawCallback: function(settings) {
                const data = this.api().ajax.json();
                if(data !== undefined) {
                    this.api().column(-1).visible(data.statusAksi);
                }
            },
            footerCallback: function(row, data) {
                var total = 0;
                data.forEach((item) => total = total + parseInt(item[3].replace("%", "")));
                this.api().column(3).footer().innerHTML = total+"%";
            }
        });
    
        button('publish');
        button('tambah');
    });

    function button(jenis)
    {
        const karyawan = $('#karyawan').val();
        const tahun    = $('#tahun').val();
        const bulan    = $('#bulan').val();
        $('#div_'+jenis).load('<?= route("kpi.team.detail.button", ['tahun' => "'+tahun+'", 'bulan' => "'+bulan+'", 'karyawan' => "'+karyawan+'", 'jenis' => "'+jenis+'"]) ?>');
    }

    function dropdownObyektives() 
    {
        $('#obyektives').select2({
            placeholder   : 'Pilih obyektif',
            allowClear    : true,
            dropdownParent: $('#modal_form_lg'),
            ajax          : {
                url     : '<?= route("dropdown.kpi.obyektives") ?>',
                dataType: 'json',
                processResults: function(data) {
                    return {
                        results: data
                    };
                }
            }
        });
    }

    function tambah() {
        $('#tampil_form_lg').load('<?= route("kpi.team.detail.form") ?>', function() {
            $("#modal_form_lg .title").text("Form Tambah Data");
            $(".btn_save").addClass("btn_save btn btn-biru");
            $(".btn_save").append('<i class="fa fa-save"></i> ');
            $(".btn_save").append('SIMPAN');
            $("#btn_new_input").hide();
            $('#modal_form_lg').modal('show');

            dropdownObyektives();
            $(".number").inputmask("numeric", {rightAlign: false});
        });
    }

    function errorStyle(content) {
        return "<span class='text-danger'><i class='fa fa-exclamation-triangle'></i> "+content+"</span>";
    }

    $(document).on("keydown", ":input:not(textarea)", function(event) {
        return event.key != "Enter";
    });

    // simpan or update
    $(document).on('click', '.btn_save', function() {
        $('#modal_form_lg #message').html('');

        $('form').validate({
            messages: {
                obyektives      : "Obyektif belum diisi",
                performIndicator: "Performa Indikator belum diisi",
                target          : "Target belum diisi",
                bobot           : "Bobot belum diisi"
            },
            errorPlacement: function(error, element) {
                if($('#modal_form_lg #message').html() == '') {
                    const id = element[0].attributes[1].nodeValue;
                    const errorMessage = errorStyle(error[0].firstChild.data);
                    $('#modal_form_lg #message').html(errorMessage);
                }
            },
            submitHandler: function(form, event) {
                event.preventDefault();

                const karyawan         = $('#karyawan').val();
                const tahun            = $('#tahun').val();
                const bulan            = $('#bulan').val();
                const idAtasan         = $('#id_atasan').val();
                const namaObyektives   = $('#obyektives').select2('data')[0].text;
                const noUrutObyektives = $('#obyektives').select2('data')[0].no_urut;
                const formTambahan     = "&karyawan="+karyawan+"&tahun="+tahun+"&bulan="+bulan+"&namaObyektives="+namaObyektives+"&noUrutObyektives="+noUrutObyektives;

                const loading = Ladda.create(document.querySelector('.btn_save'));
                loading.start();
                $.post('<?= route("kpi.team.detail.save") ?>', $('form').serialize()+formTambahan, function(result) {
                    loading.stop();
                    if(result.success && result.type == 'save') {
                        $('form input, form select, form textarea').prop('disabled', true);
                        $('.btn_save').hide();
                        $('#btn_new_input').show();
                    }
                    $('#modal_form_lg #message').html(result.message);
                }, 'json');
            }
        });
    });

    // tambah baru
    $(document).on('click', '#btn_new_input', function() {
        $('form input, form textarea').val('');
        $('form select').val(null).trigger('change');
        $('form input, form select, form textarea').prop('disabled', false);
        $('#btn_new_input').hide();
        $('#modal_form_lg #message').html('');
        $('.btn_save').show();
    });

    // edit
    $(document).on('click', '.btn_edit', function() {
        const id = $(this).attr('id');
        $('#tampil_form_lg').load('<?= route("kpi.team.detail.form") ?>/'+id, function() {
            $("#modal_form_lg .title").text("Form Update Data");
            $(".btn_save").addClass("btn_save btn btn-warning");
            $(".btn_save").append('<i class="fa fa-edit"></i> ');
            $(".btn_save").append('PERBARUI');
            $("#btn_new_input").hide();
            $('#modal_form_lg').modal('show');

            dropdownObyektives();
            $(".number").inputmask("numeric", {rightAlign: false});
        });
    });

    // delete
    $(document).on('click', '.btn_delete', function() {
        const id = $(this).attr('id');

        $('#id_pi').val(id);
        $('#modal_hapus .card-footer').show();
        $('#modal_hapus').modal('show');
        $("#modal_hapus .title").text("Apakah Anda ingin menghapus data ini?");
    });

    $(document).on('click', '.btn_hapus', function() {
        $('#modal_hapus #message').html('');

        const loading = Ladda.create(this);
        loading.start();
        $.post('<?= route("kpi.team.detail.delete") ?>', { id : $('#id_pi').val() }, function(result) {
            loading.stop();
            if(result.success) {
                $('#modal_hapus .title').html(result.message);
                $('#modal_hapus .title font').attr('color', 'white');
                $('#modal_hapus .card-footer').hide();
            } else {
                $('#modal_hapus #message').html(result.message);
            }
        }, 'json')
            .fail(function() {
                $("#modal_hapus .card-footer").hide();
                $("#modal_hapus .title").html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
            });
    });

    function publish() 
    {
        $('#tampil_form').load('<?= route("kpi.team.detail.form-publish") ?>', function() {
            $('#tampil_form #message').html('');
            $('#tampil_form .title').text('Apakah anda ingin mempublish KPI tersebut?');
            $('#modal_form').modal('show');
        });
    }

    // publish
    $(document).off('click', '.btn_publish');
    $(document).on('click', '.btn_publish', function() {
        const loading = Ladda.create(this);

        const data = {
            karyawan: $('#karyawan').val(),
            tahun   : $('#tahun').val(),
            bulan   : $('#bulan').val(),
        };

        const total = list_data.column(3).footer().innerHTML;
        if(total != '100%') {
            $('#modal_form #message').html('<span class="text-danger"><i class="fa fa-exclamation-triangle"></i> total KPI belum 100%</span>');
            return false;
        }

        loading.start();
        $.post('<?= route("kpi.team.detail.publish") ?>', data, function(result) {
            loading.stop();
            if(result.success) {
                $('#modal_form .title').html(result.message);
                $('#modal_form .title font').attr('color', 'white');
                $('#modal_form .card-footer, #modal_form .card-body').hide();

                button('publish');
                button('tambah');
            } else {
                $('#modal_form #message').html(result.message);
            }
        }, 'json')
            .fail(function() {
                $("#modal_form .card-footer").hide();
                $("#modal_form .title").html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
            });
    });

    function displayApv() {
        const tnc = document.getElementById('tnc');
        if(tnc.checked) {
            $('#apvOption').show();
        } else {
            $('#apvOption').hide();
        }
    }
</script>