<script type="text/javascript">
    $(function () {
        loadFormPph21();
        // 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);

            if ($("#menit").val() <= 0 && $("#menit").val() != '') {
                showMsg("<i class='fa fa-exclamation-triangle'></i> Waktu/menit harus diisi dan harus lebih dari 0", false);
                return false;
            }

            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) {
                        showMsg(result.message);
                    }
                },
                error: function () {
                    loading.stop();
                    showMsg('error', false);
                }
            });
        });

        // 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) {
                                showMsg(result.message);
                            }
                        },
                        error: function () {
                            loading.stop();
                            showMsg('error', false);
                        }
                    });
                });
            });
        });

        // PPH21
        $(document).on("click", "#btn-simpan", function (e) {
            e.preventDefault();
            const loading = Ladda.create(this);
            loading.start();

            let params = {};
            params.for_data = $(this).attr("for-data");
            params.aktif = $("input[name=aktif]:checked").val();
            params.jenis_pot_pph = $("input[name=pot_pph]:checked").val();
            params.nama_pemotong = $("#nama_pemotong").val();
            params.jenis_pemotong = $("#jenis_pemotong").val();
            params.nomor_pemotong = $("#nomor_pemotong").val();
            params.id_tku = $("#id_tku").val();

            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.pengaturan.form.pph.save') ?>",
                data: params,
                dataType: 'JSON',
                success: function (result) {
                    loading.stop();
                    // set default style
                    $("input, select").removeClass("border-danger");
                    $('div[id*="msg_error_"]').slideUp(100);
                    if (result.success == true) {
                        showMsg(result.message);
                        loadFormPph21();
                    } else {
                        $("input#" + result.message[0]).focus();
                        $("#" + result.message[0]).addClass("border-danger");
                        $("#msg_error_" + result.message[0] + " label").html(result.message[1]);
                        $("#msg_error_" + result.message[0]).slideDown(100);
                    }
                },
                error: function () {
                    loading.stop();
                    showMsg('error', false);
                }
            });
        });

        $(document).on("click", "#btn-edit", function () {
            // show & hide button
            $(this).hide();
            $("#btn-batal").show();
            $("#btn-simpan").show();
            // unset disable input
            $(".form-pph21 input, .form-pph21 select").prop("disabled", false);
        });

        $(document).on("click", "#btn-batal", function () {
            $("#btn-batal").prop("disabled", true);
            $("#btn-simpan").prop("disabled", true);
            // set default data
            loadFormPph21();
        });
    });

    function formatangka(objek, delimiter = ".") {
        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) + delimiter + 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);
        }
    }

    function loadFormPph21() {
        const id = "<?= $pengaturan_pph21->id_company ?: '' ?>";
        $(".form-pph21").load("<?= route('payroll.pengaturan.form.pph', ['id_company' => '"+id+"']) ?>");
    }
</script>

<!-- pph21 -->
<div class="card card-rounded mt-4">
    <div class="card-content form-pph21">
        <div class="card-body">
            <h3 class="content-header-title mb-2">Potongan PPH</h3>
            <div class="row">
                <div class="col-md-2">
                    <label>Aktif <span class="text-danger">*</span></label>
                </div>
                <div class="col-md-6 loading-skeleton">
                    <div class="form-group">
                        <label class="label text-center">
                            <input disabled type="radio" class="form-control" id="aktif_ya" name="aktif_ya" value="1">
                            <span class="text">Ya</span>
                        </label>
                        <label class="label text-center ml-2">
                            <input disabled type="radio" class="form-control" id="aktif_tidak" name="aktif_tidak"
                                value="0">
                            <span class="text">Tidak</span>
                        </label>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <label>Jenis Potongan PPH <span class="text-danger">*</span></label>
                </div>
                <div class="col-md-6 loading-skeleton">
                    <div class="form-group">
                        <label class="label text-center">
                            <input disabled type="radio" class="form-control" id="pot_pph_net" name="pot_pph"
                                value="net">
                            <span class="text">NETT</span>
                        </label>
                        <label class="label text-center ml-2">
                            <input disabled type="radio" class="form-control" id="pot_pph_gross" name="pot_pph"
                                value="gross">
                            <span class="text">GROSS</span>
                        </label>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <label for="nama_pemotong">Nama Pemotong <span class="text-danger">*</span></label>
                </div>
                <div class="col-md-6 loading-skeleton">
                    <div class="form-group">
                        <input disabled type="text" name="nama_pemotong" id="nama_pemotong" class="form-control">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <label for="jenis_pemotong">Jenis Pemotong <span class="text-danger">*</span></label>
                </div>
                <div class="col-md-6 loading-skeleton">
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-4">
                                <select disabled name="jenis_pemotong" id="jenis_pemotong"
                                    class="form-control"></select>
                            </div>
                            <div class="col-md-8">
                                <input disabled type="text" name="nomor_pemotong" onkeyup="formatangka(this, '');"
                                    id="nomor_pemotong" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <label for="id_tku">ID Tempat Kegiatan Usaha (TKU) <span class="text-danger">*</span></label>
                </div>
                <div class="col-md-6 loading-skeleton">
                    <div class="form-group">
                        <input disabled type="text" name="id_tku" id="id_tku" class="form-control">
                    </div>
                </div>
                <!-- button -->
                <div class="col-md-4 loading-skeleton">
                    <div class="form-group">
                        <button disabled class="btn btn-secondary w-120" style="display:none"><i class="fa fa-close">
                            </i> BATAL</button>
                        <button disabled class="btn btn-primary w-120 ladda-button" <?= (isset($pengaturan_pph21)) ? 'style="display:none"' : '' ?> data-style="expand-left"
                            for-data="<?= (isset($pengaturan_pph21)) ? 'update' : 'store' ?>"><i class="fa fa-save ">
                            </i> SIMPAN</button>
                        <button disabled class="btn btn-warning w-120" <?= (!isset($pengaturan_pph21)) ? 'style="display:none"' : '' ?>><i class="fa fa-edit (alias) "> </i> EDIT</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- pengaturan potongan absensi -->
<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_pot_pph" class="modal fade in">
    <div class="modal-dialog modal-md">
        <div id="tampil_form_pph" class="modal-content">
            <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>
    </div>
</div>
<!-- END TAMPIL MODAL -->