<script>
    if (location.href == "<?= route('payroll.master.lembur.karyawan') ?>") window.location.replace("<?= route('payroll.master.lembur.home') ?>");
    $(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': false,
            'info': true,
            'scrollX': false,
            'stateSave': true,
            'language': {
                'url': '<?= base_url("assets/plugins/datatables/dataTables-language-id.json") ?>',
                'sEmptyTable': 'Tidak ada data untuk ditampilkan'
            },
            "processing": true,
            "serverSide": true,
            "order": [],

            "ajax": {
                "url": "<?= route("payroll.master.lembur.data", ["tab" => "lembur_karyawan", "params" => "1.1.1.1.all.all.all"]) ?>",
                "type": "GET",
                "data": function(d) {
                    delete d.columns;
                },
                "complete": function(data) {
                    reconfigure(data);
                    $('[data-toggle="tooltip"]').tooltip();
                }
            },
            "initComplete": function() {
                $("#excel").show();
            },
            "aoColumnDefs": [{
                "className": "text-left",
                "aTargets": [1, 2]
            }, {
                "className": "text-center",
                "targets": "_all"
            }],

            "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                $("td:eq(3), td:eq(4), td:eq(5), td:eq(6)", nRow).css("width", "150px");
                $("td:eq(-1)", nRow).css("width", "20px");
            }
        });

        $(document).on('click', '#lembur_karyawan .btn_edit', function() {
            var row = this.closest('tr');
            for (let index = 3; index < 7; index++) {
                row.children[index].querySelector('select').className = "form-control";
                row.children[index].querySelector('span').className = "hidden";
            }
            this.closest('td').querySelector('#save').className = "";
            this.closest('td').querySelector('#edit').className = "hidden";
        });

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

            const row = this.closest('tr');
            const selects = row.querySelectorAll('select');

            var params = {};
            params.id = $(this).attr('id');
            let lembur_p = [];
            for (let index = 0; index < selects.length; index++) {
                lembur_p.push(selects[index].value);
            }
            params.lembur_p = lembur_p;

            $.ajax({
                type: 'POST',
                url: "<?= route('payroll.master.lembur.karyawan.save') ?>",
                data: params,
                dataType: 'JSON',
                beforeSend: function() {
                    loading_start(row, selects);
                },
                success: function(result) {
                    loading_stop(row, selects);
                    if (result.success == true) {
                        list_data.ajax.reload();
                    } else {
                        showMsg(result.message, false);
                    }
                },
                error: function() {
                    loading_stop(row, selects);
                    showMsg('error', false);
                }
            });
        });

        $(document).on('click', '#lembur_karyawan .btn_batal', function() {
            var row = this.closest('tr');
            for (let index = 3; index < 7; index++) {
                let selectElement = row.children[index].querySelector('select');
                selectElement.className = "hidden";
                selectElement.value = selectElement.getAttribute("data-old");
                row.children[index].querySelector('span').className = "";
            }
            this.closest('td').querySelector('#save').className = "hidden";
            this.closest('td').querySelector('#edit').className = "";
        });

        $(document).on('click', '#lembur_karyawan .btn_delete', function() {
            const id = $(this).attr('id');
            $("#modal_form .modal-dialog").removeClass("modal-lg");
            $("#modal_form .modal-dialog").addClass("modal-md");
            $("#tampil_form").load("<?= route('payroll.master.lembur.karyawan.form.delete', ['id' => '"+id+"']) ?>", function() {
                $("#modal_form").modal("show");
                $(".title").text("Hapus Data Master Lembur Karyawan");
                $("#btn_submit").html("<i class='fa fa-trash (alias)'></i> HAPUS");
                $("#btn_submit").addClass("btn_destroy btn btn-danger");

                $('.btn_destroy').on('click', function(e) {
                    e.preventDefault();
                    var loading = Ladda.create(this);
                    loading.start();

                    var param = {};
                    param.id = $("#encrypt_id").val();

                    $.ajax({
                        type: 'POST',
                        url: "<?= route('payroll.master.lembur.karyawan.delete') ?>",
                        data: param,
                        dataType: 'JSON',
                        success: function(result) {
                            loading.stop();
                            if (result.success == true) {
                                showMsg(result.message);
                                list_data.ajax.reload();
                            } else {
                                showMsg(result.message, false);
                            }
                        },
                        error: function() {
                            loading.stop();
                            showMsg('error', false);
                        }
                    });
                });
            });
        });

        // FILTER
        onchange_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 #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
        });

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

            const id_karyawan = $("#filter #id_karyawan").val() ? $("#filter #id_karyawan").val() : "all";
            const params = "all.all.all.all." + id_karyawan + ".all.all";

            $("#excel").attr("data-params", params);

            list_data.ajax.url("<?= route('payroll.master.lembur.data', ['tab' => 'lembur_karyawan', 'params' => '"+params+"']) ?>").load(function() {
                loading.stop();
            });
        });

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

            const working_day = $("#working_day:checked").val() ? "1" : "0";
            const day_off = $("#day_off:checked").val() ? "1" : "0";
            const national_holiday = $("#national_holiday:checked").val() ? "1" : "0";
            const special_holiday = $("#special_holiday:checked").val() ? "1" : "0";
            const id_cabang = $("#filter #cabang").val() ? $("#filter #cabang").val() : "all";
            const id_departemen = $("#filter #departemen").val() ? $("#filter #departemen").val() : "all";
            const params = working_day + "." + day_off + "." + national_holiday + "." + special_holiday + ".all." + id_cabang + "." + id_departemen;

            $("#excel").attr("data-params", params);

            list_data.ajax.url("<?= route('payroll.master.lembur.data', ['tab' => 'lembur_karyawan', 'params' => '"+params+"']) ?>").load(function() {
                loading.stop();
            });
        });

        $("#excel").click(function() {
            const params = $(this).data("params");
            const urlExcel = "<?= route('payroll.master.lembur.karyawan.download', ['params' => '"+params+"']) ?>";
            downloadFile(urlExcel, this);
        });
    });

    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", ["cabang" => "'+id_cabang+'"]) ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            }
        });
    }

    function loading_start(row, selects) {
        var loading = row.querySelector('.custom-loader');

        row.querySelector('#save').className = "hidden";
        loading.className = "custom-loader";
        selects.forEach(element => {
            element.disabled = true;
        });
    }

    function loading_stop(row, selects) {
        var loading = row.querySelector('.custom-loader');

        row.querySelector('#edit').className = "";
        loading.className = "custom-loader hidden";
        selects.forEach(element => {
            element.disabled = false;
        });
    }
</script>
<style>
    .custom-loader {
        width: 25px;
        height: 25px;
        border-radius: 50%;
        border: 4px solid;
        border-color: #E4E4ED;
        border-right-color: #1c77d4;
        animation: s2 1s infinite linear;
    }

    @keyframes s2 {
        to {
            transform: rotate(1turn)
        }
    }
</style>
<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>
    <div class="content-header-right text-right col-md-6 col-12 mb-md-0 mb-1">
        <a href="<?= route('payroll.master.lembur.karyawan.import') ?>" class="btn btn-success text-white">
            <i class="fa fa-upload"></i> Import Data Lembur
        </a>
    </div>
</div>
<hr>
<div id="filter">
    <div class="row">
        <div class="col-md-9">
            <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-success col-md-12" data-style="expand-left">CARI</button>
                </div>
            </div>

            <div class="row mt-2">
                <div class="col-md-2 py-1">
                    <label>STATUS LEMBUR</label>
                </div>
                <div class="col-md-10">
                    <span class="pr-1">
                        <input id="working_day" type="checkbox" name="working_day" value="1" checked>
                        <label class="text" for="working_day">Hari Kerja</label>
                    </span>
                    <span class="pr-1">
                        <input id="day_off" type="checkbox" name="day_off" value="1" checked>
                        <label class="text" for="day_off">Libur</label>
                    </span>
                    <span class="pr-1">
                        <input id="national_holiday" type="checkbox" name="national_holiday" value="1" checked>
                        <label class="text" for="national_holiday">Libur Nasional</label>
                    </span>
                    <span class="pr-1">
                        <input id="special_holiday" type="checkbox" name="special_holiday" value="1" checked>
                        <label class="text" for="special_holiday">Libur Khusus</label>
                    </span>
                </div>
            </div>

            <div class="row mt-1">
                <div class="col-md-2">
                    <label>CABANG</label>
                </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>
<hr>
<div class="table-responsive">
    <div class="float-right">
        <button id="excel" data-params="1.1.1.1.all.all.all" class="btn btn-biru text-white ladda-button" style="display:none" data-style="expand-left"><i class="fa fa-download"></i> Download</button>
    </div>
    <table id="list_data" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th rowspan="2" class="text-center align-middle" width="20">NO</th>
                <th rowspan="2" class="text-center align-middle">NAMA</th>
                <th rowspan="2" class="text-center align-middle">CABANG<br>DEPARTEMEN</th>
                <th colspan="4" class="text-center align-middle">LEMBUR</th>
                <th rowspan="2" class="text-center align-middle">AKSI</th>
            </tr>
            <tr>
                <th class="text-center align-middle">HARI KERJA <i class="fa fa-question-circle" data-toggle="tooltip" data-placement="top" title="Reguler / Shift"></i></th>
                <th class="text-center align-middle">LIBUR <i class="fa fa-question-circle" data-toggle="tooltip" data-placement="top" title="Libur Reguler / Shift off"></i></th>
                <th class="text-center align-middle">LIBUR NASIONAL <i class="fa fa-question-circle" data-toggle="tooltip" data-placement="top" title="Contoh: Libur Hari Pancasila, Kemerdekaan"></i></th>
                <th class="text-center align-middle">LIBUR KHUSUS <i class="fa fa-question-circle" data-toggle="tooltip" data-placement="top" title="Contoh: Libur Hari Raya Idul Fitri"></i></th>
            </tr>
        </thead>
        <tbody id="lembur_karyawan">
        </tbody>
    </table>
</div>
