<script type="text/javascript">
    $(function() {
        // reconfigure();
        $.fn.dataTable.ext.errMode = 'throw';
        var list_data = $('#list_data').DataTable({
                    'searching'   : false,
                    'delay' : 1000,
                    'paging'      : false,
                    'lengthChange': true,
                    'ordering'    : false,
                    'info'        : false,
                    'scrollX'     : true,
                    'stateSave'   : true,
                    // 'scrollCollapse': true,
                    // 'fixedColumns': true,
                    'language'    :{
                                    'url'         : '<?=base_url("assets/plugins/datatables/dataTables-language-id.json")?>',
                                    'sEmptyTable' : 'Tidak ada data untuk ditampilkan',
                                    'searchPlaceholder': 'NIK/Nama Karyawan'
                                },
                    "processing"  : true,
                    "serverSide"  : true,
                    "order"       : [],

                    "ajax"        : {
                                        "url": "<?= route("payroll.pengaturan.potongan.absensi.data") ?>",
                                        "type": "POST",
                                        "complete" : function(data){
                                            reconfigure(data);
                                        }
                                    },

                    "aoColumnDefs": [
                                        { "aTargets": [0,1,2,3,4,5,6], "bSortable": false }
                                    ],
                    "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                            $('td:eq(0)', nRow).css({'text-align':'center','width':'10px'});
                            $('td:eq(1)', nRow).css({'text-align':'left','width':'100px'});
                            $('td:eq(2)', nRow).css({'text-align':'center','width':'100px'});
                            $('td:eq(3)', nRow).css({'text-align':'center','width':'100px'});
                            $('td:eq(4)', nRow).css({'text-align':'right','width':'100px'});
                            $('td:eq(5)', nRow).css({'text-align':'right','width':'150px'});
                            $('td:eq(6)', nRow).css({'text-align':'right','width':'100px'});
                            $('td:eq(7)', nRow).css({'text-align':'center','width':'100px'});
                    }

        });

        $(document).on('click','.btn_edit_nominal',function(){
            const nominal  = $(this).parent().closest(".nominal-edit");
            const inputVal = nominal.children()[0].value;
            const lastVal  = nominal.parent().closest(".nominal-form").children(".nominal-with-button")[0].children[0].innerText;
            const btnFor   = nominal.attr('data-btn');

            if (inputVal == lastVal) {
                nominal.attr("style", "display:none");
                nominal.parent().closest(".nominal-form").children(".nominal-with-button").show();
            }else{
                $('#tampil_form').load("<?= route("payroll.pengaturan.potongan.absensi.form.update") ?>",function(){
                    $('#modal_form').modal('show');
                    if (btnFor == "nominal") {
                        $(".title").html("Apakah Anda ingin mengubah nominal potongan menjadi <b>Rp "+inputVal+"</b> ?");
                        $("#nominal_potongan").val(inputVal);
                    }else if (btnFor == "menit") {
                        $(".title").html("Apakah Anda ingin mengubah minimal waktu potongan menjadi <b>"+inputVal+" menit</b> ?");
                        $("#menit").val(inputVal);
                    }else{
                        $(".title").html("Apakah Anda ingin mengubah persentase menjadi <b>"+inputVal+" %</b> ?");
                        $("#persen").val(inputVal);
                    }
                    $(".btn_save").addClass("btn_save btn btn-primary");
                    $(".btn_save").append('<i class="fa fa-save"></i> ');
                    $(".btn_save").append('SIMPAN');
                    $("#jenis").val(nominal.parent().closest(".nominal-form").children()[1].getAttribute("id"));
                    nominal.children()[0].value = lastVal;
                    nominal.attr("style", "display:none");
                    nominal.parent().closest(".nominal-form").children(".nominal-with-button").show();
                });
            }
        });

        $(document).on('click','.btn_edit',function(){
            $(this).hide();
            $(this).closest(".nominal-form").children(".nominal-edit")[0].removeAttribute("style");
            $(this).closest(".nominal-form").children(".nominal-edit")[0].children[0].focus();
        });

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

            loading.start();

            var param = {};
            param.jenis  = $("#jenis").val();
            param.persen = $("#persen").val();
            param.menit  = $("#menit").val();
            param.nominal_potongan = $("#nominal_potongan").val();

            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.pengaturan.potongan.absensi.save') ?>",
                data: param,
                dataType:'JSON',
                success: function(result) {
                    loading.stop();
                    if(result.success == true){
                        $("#modal_form .card-body").hide();
                        $("#modal_form .card-footer").hide();
                        $("#modal_form .title").html(result.message.replace("009900","FFFFFF"));
                        // Set a timeout to hide the element
                        setTimeout(function(){
                            $("#modal_form").modal('hide');
                        }, 2000);
                    }
                },
                error:function(){
                    loading.stop();
                    $("#modal_form .card-body").hide();
                    $("#modal_form .card-footer").hide();
                    $("#modal_form .title").html('<font color="#FFFFFF"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
                }
            });
        });

        // SWITCH ON / OFF
        $(document).on('change', ':checkbox', function(e){
            var id_p = $(this).attr('id');
            var for_flag = $(this).attr('data-flag');
            var status = $(this).attr('value');
            var ket = $(this).closest(".switch").children("span");

            if (status == "1") {
                status = "0";
                $(this).attr('value', '0');
                switch (for_flag) {
                    case "flag_aktif":
                        ket.html("Nonaktif");
                        break;

                    default:
                        ket.html("Tidak");
                        break;
                }
            }else{
                status = "1";
                $(this).attr('value', '1');
                switch (for_flag) {
                    case "flag_aktif":
                        ket.html("Aktif");
                        break;

                    default:
                        ket.html("Ya");
                        break;
                }
            }

            $('#tampil_form').load("<?= route("payroll.pengaturan.potongan.absensi.form.update") ?>",function(){
                $('#modal_form').modal('show');
                if (for_flag == "flag_persentase_gapok" && status == "1") {
                    $("#tampil_form #form_input").removeAttr("style");
                    $("#tampil_form #status_flag").val(status);
                    $(".title").html("Form persentase gapok");
                }else if (for_flag == "flag_persentase_gapok" && status == "0") {
                    $("#tampil_form #form_input").attr("style","display:none");
                    $("#tampil_form #status_flag").val(status);
                    $(".title").html("Apakah Anda ingin mengubah persentase gapok menjadi tidak aktif?");
                }else{
                    $(".title").html("Apakah Anda ingin mengubah "+for_flag.replaceAll("_", " ")+" menjadi "+ket.html()+"?");
                }
                $(".btn_save").addClass("btn_save_flag btn btn-primary");
                $(".btn_save_flag").append('<i class="fa fa-save"></i> ');
                $(".btn_save_flag").append('SIMPAN');

                // CLOSE
                $(document).on("click",".close",function(){
                    list_data.ajax.reload();
                });

                // PROSES UPDATE FLAG
                $(".btn_save_flag").on("click",function(e){
                    e.preventDefault();
                    $('#message').html("");
                    var loading = Ladda.create(this);

                    if (for_flag == "flag_persentase_gapok") {
                        if ($("#persentase").val() == "" && $("#tampil_form #status_flag").val() == "1") {
                            $('#message').show();
                            $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> persentase harus diisi</font>");
                            $("#persentase").focus();
                            return false;
                        }else{
                            var persen = $("#persentase").val();
                        }
                    }

                    loading.start();

                    var param = {};
                    if (for_flag == "flag_persentase_gapok") {
                        param.id_p = id_p;
                        param.for_flag = for_flag;
                        param.status = status;
                        param.persentase = persen;
                    }else{
                        param.id_p = id_p;
                        param.for_flag = for_flag;
                        param.status = status;
                    }

                    $.ajax({
                        type: 'POST',
                        url: "<?= route('payroll.pengaturan.potongan.absensi.update_flag') ?>",
                        data: param,
                        dataType:'JSON',
                        success: function(result){
                            loading.stop();
                            if(result.success == true){
                                $("#modal_form .card-body").hide();
                                $("#modal_form .card-footer").hide();
                                $("#modal_form .title").html(result.message.replace("009900","FFFFFF"));
                                // Set a timeout to hide the element
                                setTimeout(function(){
                                    $("#modal_form").modal('hide');
                                }, 2000);
                            }
                        },
                        error:function(){
                            loading.stop();
                            $("#modal_form .card-body").hide();
                            $("#modal_form .card-footer").hide();
                            $("#modal_form .title").html('<font color="#FFFFFF"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
                        }
                    });
                });
            });
        });

    });

    function formatangka(objek) {
        a = objek.value;
        b = a.replace(/[^\d]/g,"");
        c = "";
        panjang = b.length;
        j = 0;
        for (i = panjang; i > 0; i--) {
            j = j + 1;
            if (((j % 3) == 1) && (j != 1)) {
            c = b.substr(i-1,1) + "." + c;
            } else {
            c = b.substr(i-1,1) + c;
            }
        }
        objek.value = c;
    }

    function calculatePersentase(amount) {
        const n = amount.value;
        if ( n.match(/^[0-9][0-9]?(\.[0-9]{0,2})?$/) ) {
            amount.value = n;
        } else {
            amount.value = n.slice(0, -1);
        }
    }

    $(document).ready(function() {
        // Modal Radio Potongan PPH
        $("#pot_pph_net, #pot_pph_gross").change(function() {
            if ($(this).is(":checked")) {
                var jenis_pph = $(this).val();
                $("#modal_pot_pph #jenis_pph").val(jenis_pph);
                $("#modal_pot_pph .card-body").show();
                $("#modal_pot_pph .card-footer").show();
                $('#modal_pot_pph').modal('show');
                $(".title").text("Apakah Anda ingin mengubah jenis potongan pph menjadi " +jenis_pph.toUpperCase() +" ?");
                $(".btn_save_jenis_pph").removeClass("btn_save_jenis_pph").addClass("btn_save_jenis_pph btn btn-primary");
            }
        });

        // Jika modal pph di close kembali ke value awal
        $('#modal_pot_pph').on('hidden.bs.modal', function() {
            if (!berhasil_hapus) {
                var value_original = $("#value_pph_original").val();

                if (value_original === "net") {
                    $("#pot_pph_net").prop("checked", true);
                    $("#pot_pph_gross").prop("checked", false);
                } else if (value_original === "gross") {
                    $("#pot_pph_net").prop("checked", false);
                    $("#pot_pph_gross").prop("checked", true);
                }
            }

            berhasil_hapus = false;
        });

        // Action Save Jenis Potongan PPH
        var berhasil_hapus = false;
        $(document).on('click','.btn_save_jenis_pph',function(){
            var loading = Ladda.create(this);
            loading.start();
            jenis_pph = $("#modal_pot_pph #jenis_pph").val();
            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.pengaturan.potongan.absensi.update.pph') ?>",
                data: 'jenis_pph='+jenis_pph,
                dataType:'JSON',
                success: function(result){
                    berhasil_hapus = true;
                    $("#value_pph_original").val(jenis_pph);

                    loading.stop();
                    $("#modal_pot_pph .card-body").hide();
                    $("#modal_pot_pph .card-footer").hide();
                    $("#modal_pot_pph .title").html(result.message.message);
                },
                error:function(){
                    berhasil_hapus = false;
                    loading.stop();
                    $("#modal_pot_pph .card-body").hide();
                    $("#modal_pot_pph .card-footer").hide();
                    $("#modal_pot_pph .title").html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
                }
            });
        });
    });
</script>

<div class="card card-rounded mt-4">
    <div class="card-content">
        <div class="card-body">
            <h3 class="content-header-title mb-2">Potongan PPH</h3>

            <div class="row">
                <div class="col-2">Jenis Potongan PPH</div>
                <div class="col-6">
                    <label class="label text-center">
                        <input type="radio" class="disable-radio" id="pot_pph_net" name="pot_pph" value="net" <?= ((isset($get_pot_pph) && $get_pot_pph == "net")?"checked":"") ?>>
                        <span class="design"></span>
                        <span class="text">NETT</span>
                    </label>
                    <label class="label text-center ml-2">
                        <input type="radio" class="disable-radio" id="pot_pph_gross" name="pot_pph" value="gross" <?= ((isset($get_pot_pph) && $get_pot_pph == "gross")?"checked":"") ?>>
                        <span class="design"></span>
                        <span class="text">GROSS</span>
                    </label>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card card-rounded">
    <div class="card-content">
        <div class="card-body">
            <h3 class="content-header-title mb-2">Potongan Absensi</h3>

            <div class="table-responsive">
                <table id="list_data" class="table table-striped" style="width:100%">
                    <thead>
                        <tr>
                            <th rowspan="2" class="align-middle text-center">NO</th>
                            <th rowspan="2" class="align-middle text-left">JENIS</th>
                            <th rowspan="2" class="align-middle text-center">STATUS AKTIF</th>
                            <th colspan="2" class="align-middle text-center">PRESENTASE GAPOK</th>
                            <th rowspan="2" class="align-middle text-center">NOMINAL POTONGAN</th>
                            <th colspan="2" class="align-middle text-center">POTONGAN</th>
                        </tr>
                        <tr>
                            <th class="align-middle text-center">AKTIF</th>
                            <th class="align-middle text-center">PERSENTASE</th>

                            <th class="align-middle text-center">WAKTU/MENIT</th>
                            <th class="align-middle text-center">BERLAKU KELIPATAN</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- START TAMPIL MODAL -->
<div id="modal_form" class="modal fade in">
    <div class="modal-dialog modal-md">
        <div id="tampil_form" class="modal-content"></div>
    </div>
</div>
<!-- END TAMPIL MODAL -->

<!-- START TAMPIL MODAL -->
<div id="modal_pot_pph" class="modal fade in">
    <div class="modal-dialog modal-md">
        <div id="tampil_form_pph" class="modal-content">
            <input type="hidden" id="jenis_pph">
            <input type="hidden" id="value_pph_original" value="<?= $get_pot_pph ?>">
            <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_save_jenis_pph ladda-button" id="btn_save_jenis_pph" data-style="expand-left">UBAH</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- END TAMPIL MODAL -->
