<script type="text/javascript">
    $(function () {
        // reconfigure();
        $.fn.dataTableExt.sErrMode = 'none';
        list_data = $('#list_data').on('error.dt', function (e, settings, techNote, message) {
            if (confirm('Terjadi kesalahan saat memproses data, muat ulang halaman ?')) {
                window.location.reload();
            }
        }).DataTable({
            'searching': false,
            'searchDelay': 1000,
            'paging': true,
            'lengthChange': true,
            'ordering': false,
            'info': true,
            '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': ''
            },
            "processing": true,
            "serverSide": true,
            "order": [],
            "layout": {
                "topEnd": [
                    $("#data-actions")
                ]
            },
            "ajax": {
                "url": "<?= route("payroll.master.komponen.data", ["master" => "potongan"]) ?>",
                "type": "GET",
                "data": function (d) {
                    delete d.columns;
                },
                "complete": function (data) {
                    reconfigure(data);
                }
            },

            "aoColumnDefs": [
                {
                    "className": "text-left",
                    "targets": [2, 3]
                },
            ],
            "fnCreatedRow": function (row, data, dataIndex) {
                $(row).addClass('text-center');
            },

        });


        $('#list_data').sortable({
            items: "tr",
            cursor: "move",
            handle: "i.fa-sort",
            placeholder: "ui-state-highlight",
            update: function () {
                var pageInfo = list_data.page.info();
                var currentPage = pageInfo.page; // Zero-based index
                var pageLength = pageInfo.length;
                var startIndex = currentPage * pageLength;

                var order = [];
                $('#list_data tbody tr').each(function (index, element) {
                    order.push({
                        id_item: $(this).find("td:eq(0) i").data("key"),
                        no_urut: startIndex + index + 1
                    });
                });
                // console.log(order);
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "<?= route("payroll.master.komponen.order") ?>",
                    data: {
                        order: order,
                    },
                    success: function (response) {
                        if (response.status == "success") {
                            // console.log(response);
                        } else {
                            // console.log(response);
                        }
                    }
                });
            }
        });

        $(document).on('click', '.btn_tambah', function () {
            $('#tampil_form').load("<?= route("payroll.master.komponen.form.tambah", ["master" => "potongan"]) ?>", function () {
                $('#modal_form').modal('show');
                $(".title").text("Form Tambah Data Master Komponen");
                $(".btn_save").addClass("btn_save btn btn-primary");
                $(".btn_save").append('<i class="fa fa-save"></i> ');
                $(".btn_save").append('SIMPAN');
                $("#btn_new_input").hide();
            });
        });

        $(document).on('click', '.btn_edit', function () {
            $('#tampil_form').load("<?= route("payroll.master.komponen.form.edit", ["master" => "potongan"]) ?>" + "/" + $(this).attr('id'), function () {
                $('#modal_form').modal('show');
                $(".title").text("Form Edit Data Master Komponen");
                $(".btn_save").append('<i class="fa fa-edit (alias)"></i> ');
                $(".btn_save").append('PERBARUI');
                $(".btn_save").removeClass("btn_save").addClass("btn_update btn btn-warning");
                $("#btn_new_input").hide();
            });
        });

        $(document).on('click', '.btn_delete', function () {
            $('#tampil_form').load("<?= route("payroll.master.komponen.form.hapus", ["master" => "potongan"]) ?>" + "/" + $(this).attr('id'), function () {
                $('#modal_form').modal('show');
                $(".title").text("Apakah Anda ingin menghapus data ini?");
                $('#form_input input').prop("disabled", true);
                $(".btn_save").append('<i class="fa fa-trash"></i> ');
                $(".btn_save").append('HAPUS');
                $(".btn_save").removeClass("btn_save").addClass("btn_hapus btn btn-danger");
            });
        });

        $(document).on('click', '#btn_new_input', function () {
            $('#form_input input[type=text]').prop("disabled", false);
            $('#form_input input[type=radio]').prop("disabled", false);
            $("#form_input input[type=text]").val('');

            $('.btn_save').show();
            $('#btn_new_input').hide();
            $('#message').hide();
        });

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

            var valid = formValidation();
            if (!valid) {
                return false;
            }

            loading.start();

            var param = {};
            param.flag_jenis = $("#form_jenis_komponen input[type='radio']:checked").val();
            param.nm_komponen = $("#form_input #nm_komponen").val();
            param.flag_persentase = $("#form_persentase_gapok input[type='radio']:checked").val();
            param.persentase = $("#form_input #persentase").val();
            param.flag_bpjs = $("#form_bpjs input[type='radio']:checked").val();
            param.flag_pph21 = $("#form_pph21 input[type='radio']:checked").val();
            param.flag_pot_absensi = $("#form_pot_absensi input[type='radio']:checked").val();
            param.reorder = reorder();

            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.master.komponen.save', ['master' => 'potongan']) ?>",
                data: param,
                dataType: 'JSON',
                success: function (result) {
                    if (result.success == true) {
                        if (result.type == 'save') {
                            $("#form_input :input").prop("disabled", true);
                            $('.btn_save').hide();
                            $('#btn_new_input').show();
                        }

                    }
                    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>');
                }
            });
        });

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

            var valid = formValidation();
            if (!valid) {
                return false;
            }

            loading.start();

            var param = {};
            param.key = $("#form_input #key").val();
            param.jenis = $("#form_input #jenis").val();
            param.flag_jenis = $("#form_jenis_komponen input[type='radio']:checked").val();
            param.nm_komponen = $("#form_input #nm_komponen").val();
            param.flag_persentase = $("#form_persentase_gapok input[type='radio']:checked").val();
            param.persentase = $("#form_input #persentase").val();
            param.flag_bpjs = $("#form_bpjs input[type='radio']:checked").val();
            param.flag_pph21 = $("#form_pph21 input[type='radio']:checked").val();
            param.flag_pot_absensi = $("#form_pot_absensi input[type='radio']:checked").val();

            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.master.komponen.update', ['master' => 'potongan']) ?>",
                data: param,
                dataType: 'JSON',
                success: function (result) {
                    loading.stop();
                    $("#form_input #jenis").val(param.flag_jenis);
                    $('#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>');
                }
            });
        });

        // PROSES DELETE
        $(document).on('click', '.btn_hapus', function () {
            var loading = Ladda.create(this);
            loading.start();

            const bulan = $("#form_input #bulanTdkTetap").val();
            var param = {};
            param.key = $("#form_input #key").val();
            param.bulan = bulan;

            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.master.komponen.delete', ['master' => 'potongan', 'bulan' => '"+bulan+"']) ?>",
                data: param,
                dataType: 'JSON',
                success: function (result) {
                    $("#modal_form .card-body").hide();
                    $("#modal_form .card-footer").hide();
                    $("#modal_form .title").html(result.message.replace("009900", "FFFFFF"));
                    setTimeout(() => {
                        $("#modal_form").modal('hide');
                    }, 1000);
                },
                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 reorder() {
        var order = [];
        $('#list_data tbody tr').each(function (index, element) {
            order.push({
                id_item: $(this).find("td:eq(0) i").data("key"),
                no_urut: index + 1
            });
        });
        return order;
    }

    function formValidation() {
        if (($("#nm_komponen").val() == "")) {
            $('#message').show();
            $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Nama potongan belum diisi</font>");
            $("#nm_komponen").focus();
            return false;
        }

        if ($("#form_persentase_gapok input[type='radio']:checked").val() == "1") {
            if ($("#form_input #persentase").val() == "") {
                $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Persentase harus diisi</font>");
                $('#form_input #persentase').focus();
                return false;
            }
        }

        return true;
    }
</script>
<div class="content-header mt-4">
    <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="#">Payroll</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 class="card-body">
            <ul class="nav nav-tabs mb-2">
                <li class="nav-item">
                    <a class="nav-link" href="<?= route('payroll.master.komponen.pendapatan'); ?>">Master Pendapatan</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="#">Master Potongan</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="<?= route('payroll.master.komponen.kehadiran'); ?>">Master Kehadiran</a>
                </li>
            </ul>
            <div class="table-responsive">
                <div id="data-actions" class="float-md-right">
                    <button type="button" class="btn_tambah btn btn-biru">
                        <i class="fa fa-plus"></i> Tambah Data
                    </button>
                </div>
                <table id="list_data" class="table table-striped table-bordered" style="width:100%">
                    <thead>
                        <tr>
                            <th class="text-center align-middle" width="20"></th>
                            <th class="text-center align-middle" width="20">NO</th>
                            <th class="text-center align-middle">JENIS POTONGAN</th>
                            <th class="text-center align-middle">NAMA POTONGAN</th>
                            <th class="text-center align-middle">PRESENTASE<br>DARI GAPOK</th>
                            <th class="text-center align-middle">PRESENTASE</th>
                            <th class="text-center align-middle">DIIKUTSERTAKAN HITUNGAN<br>PPH21</th>
                            <th class="text-center align-middle" width="50">AKSI</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>