<!-- BAGIN DATATABLE -->
<script type="text/javascript">
    $(document).ready(function() {
        $.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': true,
            'info': true,
            'scrollX': true,
            'fixedColumns': {
                leftColumns: 2
            },
            // '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": [],

            "ajax": {
                "url": "<?= route('payroll.data.komponen.datatable', ['id_karyawan' => 'all', 'id_cabang' => 'all', 'id_departemen' => 'all']) ?>",
                "type": "GET",
                "data": function(d) {
                    delete d.columns;
                },
                "complete": function(data) {
                    reconfigure(data);
                }
            },

            "aoColumnDefs": [{
                    "aTargets": "_all",
                    "bSortable": false
                },
                {
                    "className": "text-center",
                    "targets": [0]
                },
                {
                    "className": "text-left",
                    "targets": [1, 2, 3, 4]
                },
                {
                    "className": "text-right",
                    "targets": "_all"
                },
            ],
            "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                if (aData[5] == "-") {
                    $('td:eq(5)', nRow).css({
                        'background-color': '#FF7588',
                        'color': 'White'
                    });
                    $('td:eq(5)', nRow).attr('class', 'text-center');
                    $('td:eq(5)', nRow).html('<span>Gapok belum diatur</span>');
                }
            },
        });
    });
</script>
<!-- END DATATABLE -->

<!-- BEGIN FORM INPUT -->
<script type="text/javascript">
    $(function() {
        $('#modal-nominal').on('show.bs.modal', function(event) {
            $('#message').hide();

            let button = $(event.relatedTarget);
            let rowData = list_data.row(button.closest("tr")).data();
            let item = button.data('item');
            let komponen = button.data('komponen');
            let btn = button.data('btn');
            let nm_komponen = button.data('nm_komponen');
            let nominal = button.data('nominal');
            let persen = button.data('persen');
            let modal = $(this);

            modal.find('.card-body').show();
            modal.find('#nominal_pendapatan').prop("disabled", true)
            if (btn == "hapus") {
                modal.find(".modal-title").text(capitalize(btn) + ' nominal ' + komponen + "?");
                modal.find('.card-body').hide();
                modal.find('#nominal_pendapatan').val(0);
                modal.find(".btn_save").html('<i class="fa fa-trash"></i> HAPUS');
                modal.find(".btn_save").removeClass("btn-primary").addClass("btn_save ladda-button btn btn-danger");
            } else {
                modal.find(".modal-title").text(capitalize(btn) + ' nominal ' + komponen);
                modal.find('.card-body label').text(nm_komponen);
                modal.find('#nominal_pendapatan').val(nominal);
                modal.find(".btn_save").html('<i class="fa fa-save"></i> SIMPAN');
                modal.find(".btn_save").removeClass("btn-danger").addClass("btn_save ladda-button btn btn-primary");
                if (btn == "ubah") {
                    modal.find('#nominal_pendapatan').prop("disabled", false);
                } else {
                    modal.find('#nominal_pendapatan').val(Math.round(rowData[5].replaceAll(".", "") * (persen / 100)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."));
                }
            }
            modal.find('#item').val(item);
            modal.find('#komponen').val(komponen);
            modal.find('#nominal_pendapatan').focus();

            $("#nominal_pendapatan").keydown(function(event) {
                if (event.which == 13) {
                    event.preventDefault();
                    $('.btn_save').click();
                }
            });
        })

        $(document).on('click', '.btn_save', function(e) {
            e.preventDefault();

            var loading = Ladda.create(this);
            loading.start();

            var param = {};
            param.item = $("#item").val();
            param.komponen = $("#komponen").val();
            param.nominal = ($("#nominal_pendapatan").val() != "") ? $("#nominal_pendapatan").val() : 0;

            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.data.komponen.update') ?>",
                data: param,
                dataType: 'JSON',
                success: function(result) {
                    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>');
                }
            });
        });
    });

    function capitalize(str) {
        strVal = '';
        str = str.split(' ');
        for (var chr = 0; chr < str.length; chr++) {
            strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
        }
        return strVal
    }

    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;
    }
</script>
<!-- END FORM INPUT -->

<!-- BEGIN FILTER DATA -->
<script type="text/javascript">
    $(document).ready(function() {
        dropdown_cabang();

        $('#filter #id_karyawan').select2({
            placeholder: 'Semua Karyawan',
            allowClear: true,
            ajax: {
                url: '<?= route("dropdown.karyawan.encrypt") ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        });

        $('#filter #btn_cari').click(function() {
            let loading = Ladda.create(this);
            loading.start();

            let id_karyawan = ($("#filter #id_karyawan").val()) ? $("#filter #id_karyawan").val() : "all";
            let id_cabang = "all";
            let id_departemen = "all";

            list_data.ajax.url("<?= route('payroll.data.komponen.datatable', ['id_karyawan' => '"+id_karyawan+"', 'id_cabang' => '"+id_cabang+"', 'id_departemen' => '"+id_departemen+"']) ?>").load();
            loading.stop();
        });

        $('#filter #btn_filter').click(function() {
            let loading = Ladda.create(this);
            loading.start();

            let id_karyawan = "all";
            let id_cabang = (!$("#filter #cabang").val()) ? "all" : $("#filter #cabang").val();
            let id_departemen = (!$("#filter #departemen").val()) ? "all" : $("#filter #departemen").val();

            list_data.ajax.url("<?= route('payroll.data.komponen.datatable', ['id_karyawan' => '"+id_karyawan+"', 'id_cabang' => '"+id_cabang+"', 'id_departemen' => '"+id_departemen+"']) ?>").load();
            loading.stop();
        });
    });

    function dropdown_cabang() {
        $('#filter #cabang').select2({
            placeholder: 'Semua Cabang',
            allowClear: true,
            ajax: {
                url: '<?= route("dropdown.cabang") ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        });
    }

    function onchange_dropdown_cabang() {
        $("#filter #departemen").val('').trigger('change');
        dropdown_departemen();
    }

    function dropdown_departemen() {

        var id_cabang = ($("#filter #cabang").val() == null) ? "all" : $("#filter #cabang").val();

        $("#filter #departemen").select2({
            placeholder: "Semua Departemen",
            allowClear: true,
            ajax: {
                url: '<?= route("dropdown.departemen.by.cabang") ?>/' + id_cabang,
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            }
        });
    }
</script>
<!-- END FILTER DATA -->

<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 class="content-header-right col-md-6 col-12">
            <div class="float-md-right">
                <a href="<?= route('payroll.data.komponen.import.home') ?>" class="btn-import btn btn-success">
                    <i class="fa fa-upload"></i> Import Data Komponen
                </a>
            </div>
        </div>
    </div>
    <hr>
    <div id="filter">
        <div class="row">
            <div class="col-md-8">
                <div class="row mt-1">
                    <div class="col-md-2">
                        <label>NAMA KARYAWAN</label>
                    </div>
                    <div class="col-md-8">
                        <select id="id_karyawan" class="form-control"></select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" id="btn_cari" class="ladda-button btn btn-primary col-md-12" data-style="expand-left">CARI</button>
                    </div>
                </div>

                <div class="row mt-1">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>CABANG</label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select id="cabang" class="form-control" onchange="onchange_dropdown_cabang()">
                            <option></option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label>DEPARTEMEN</label>
                    </div>
                    <div class="col-md-3">
                        <select class="form-control" id="departemen"></select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" id="btn_filter" class="ladda-button btn btn-primary col-md-12" data-style="expand-left">FILTER</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card card-rounded">
    <div class="card-content">
        <div class="card-body">
            <div class="table-responsive">
                <table id="list_data" class="table table-striped table-bordered" style="width:100%">
                    <thead>
                        <tr class="bg-tr">
                            <?php
                            $numrow = 1;
                            if (count($master['pendapatan']) > 0 || count($master['potongan']) > 0) {
                                $numrow = 2;
                            }
                            ?>
                            <th rowspan="<?= $numrow ?>" class="align-middle text-center" width="30">NO</th>
                            <th rowspan="<?= $numrow ?>" class="align-middle text-center">NAMA KARYAWAN</th>
                            <th rowspan="<?= $numrow ?>" class="align-middle text-center">CABANG</th>
                            <th rowspan="<?= $numrow ?>" class="align-middle text-center">DEPARTEMEN</th>
                            <th rowspan="<?= $numrow ?>" class="align-middle text-center">JABATAN</th>
                            <th rowspan="<?= $numrow ?>" class="align-middle text-center">GAPOK</th>
                            <?php
                            if (count($master['pendapatan']) > 0) {
                                echo '<th colspan="' . (count($master['pendapatan']) + 1) . '" class="align-middle text-center">PENDAPATAN</th>';
                            }
                            if (count($master['potongan']) > 0) {
                                echo '<th colspan="' . (count($master['potongan']) + 1) . '" class="align-middle text-center">POTONGAN</th>';
                            }
                            ?>
                            <th rowspan="<?= $numrow ?>" class="align-middle text-center">GAJI DITERIMA</th>
                        </tr>
                        <?php
                        if (count($master['pendapatan']) > 0 || count($master['potongan']) > 0) {
                            echo '<tr>';
                            if (count($master['pendapatan']) > 0) {
                                foreach ($master['pendapatan'] as $komponen) {
                                    echo '<th class="align-middle text-center">' . strtoupper($komponen['nm_komponen']) . (($komponen['flag_persentase_gapok'] == '1') ? ' (' . str_replace('.00', '', $komponen['gapok_persen']) . '%)' : '') . '</th>';
                                }
                                echo '<th class="align-middle text-center">TOTAL PENDAPATAN</th>';
                            }
                            if (count($master['potongan']) > 0) {
                                foreach ($master['potongan'] as $komponen) {
                                    echo '<th class="align-middle text-center">' . strtoupper($komponen['nm_komponen']) . (($komponen['flag_persentase_gapok'] == '1') ? ' (' . str_replace('.00', '', $komponen['gapok_persen']) . '%)' : '') . '</th>';
                                }
                                echo '<th class="align-middle text-center">TOTAL POTONGAN</th>';
                            }
                            echo '</tr>';
                        }
                        ?>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- START TAMPIL MODAL -->
<div class="modal fade" id="modal-nominal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-md" role="document">
        <div 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 class="card-body">
                <input id="item" type="hidden" disabled>
                <input id="komponen" type="hidden" disabled>
                <div class="form-group">
                    <label>Nominal</label>
                    <input type="text" id="nominal_pendapatan" class="form-control" onkeyup="formatangka(this);">
                </div>
            </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 ladda-button btn btn-primary" data-style="expand-left"><i class="fa fa-save"></i> SIMPAN</button>
                    </div>
                </div><!-- ./row -->
            </div>
        </div>
    </div>
</div>
<!-- END TAMPIL MODAL -->
