<script type="text/javascript">
    var selected_rows = [];
    $("#filter .btn_filter:last").html('<button type="button" id="btn_filter" class="ladda-button btn btn-primary w-100" data-style="expand-left">FILTER</button>');

    $(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': true,
            'stateSave': true,
            'language': {
                <?php if ($this->code_lang == 'id') : ?> 'url': '<?= base_url("assets/plugins/datatables/dataTables-language-id.json") ?>',
                    'sEmptyTable': 'Tidak ada data untuk ditampilkan',
                <?php else : ?>
                <?php endif; ?>
            },
            "processing": true,
            "serverSide": true,
            "order": [],
            "ajax": {
                "url": "<?= route('sales_activity.approval_activity.data', ['mulai' => date('Y-m-d'), 'selesai' => date('Y-m-d'), 'status' => 'all', 'karyawan' => 'all', 'group' => 'all']) ?>",
                "type": "GET",
                "data": function(d) {
                    delete d.columns;
                },
                "complete": function(data) {
                    reconfigure(data);
                    screenUp(200);
                    $("#row_selected").html(selected_rows.length);
                    if (data.responseJSON.data.length === 0) {
                        $("table.dataTable tbody tr").css("cursor", "default");
                    }
                    if (data.responseJSON.ttl_pengajuan > 0) {
                        $("#btn-verify-all").prop("disabled", false);
                        $("#btn-verify-all").removeClass("btn-light").addClass("btn-biru").removeAttr("style");
                    } else {
                        $("#btn-verify-all").prop("disabled", true);
                        $("#btn-verify-all").removeClass("btn-biru").addClass("btn-light").css("cursor", "not-allowed");
                    }
                    if (selected_rows.length == 0) {
                        $("#btn-verify-selected").prop("disabled", true);
                        $("#btn-verify-selected").removeClass("btn-warning").addClass("btn-light").css("cursor", "not-allowed");
                    }
                }
            },
            "aoColumnDefs": [{
                    "targets": "_all",
                    "className": "align-top"
                },
                {
                    "render": function(data, type, row) {
                        return "<span style='white-space: nowrap;'>" + data + "</span>";
                    },
                    "targets": 1
                }
            ],
            "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                $("td:eq(0), td:eq(1)", nRow).css({
                    'text-align': 'center',
                    'width': '30px'
                });
                $("td:eq(2),td:eq(-1)", nRow).css({
                    'text-align': 'center',
                    'width': '100px'
                });
                $("td:eq(5)", nRow).css({
                    'text-align': 'center',
                    'width': '50px'
                });
                if ($("td:eq(-1)", nRow).find("[data-status]").data("status") || $("td:eq(0)", nRow).hasClass("dataTables_empty")) {
                    $(nRow).css('cursor', 'default');
                } else {
                    if (selected_rows.indexOf($(nRow).find("[data-in]").data("in") + "_" + $(nRow).find("[data-id]").data("id")) > -1) {
                        $(nRow).addClass("selected");
                        $("td:eq(0)", nRow).find("input[type='checkbox']").prop('checked', true);
                    }
                }
            }
        });
        list_data.on('click', 'tbody tr', function(e) {
            let row = $(e.currentTarget);
            let id = row.find("[data-in]").data("in") + "_" + row.find("[data-id]").data("id");
            let action = '';
            const status = ["approve", "-"];

            if (!status.includes(row.find("[data-status]").data("status")) && !$(e.target).hasClass("btn-verify")) {
                if (!row.find("td:eq(0)").hasClass("dataTables_empty")) {
                    row.toggleClass('selected');
                    if (row.hasClass('selected')) {
                        set_selected_rows(id, 'add');
                        row.find("input[type='checkbox']").prop('checked', true);
                    } else {
                        set_selected_rows(id, 'remove');
                        row.find("input[type='checkbox']").prop('checked', false);
                    }
                }
            }
        });

        /**
         * FILTER
         */

        // periode
        tanggal();
        pickrange();

        // status
        const pengajuanCheckbox = document.getElementById('pengajuan');
        const disetujuiCheckbox = document.getElementById('disetujui');
        const ditolakCheckbox = document.getElementById('ditolak');

        pengajuanCheckbox.addEventListener('change', validateCheckboxes);
        disetujuiCheckbox.addEventListener('change', validateCheckboxes);
        ditolakCheckbox.addEventListener('change', validateCheckboxes);

        function validateCheckboxes() {
            if (!pengajuanCheckbox.checked && !disetujuiCheckbox.checked && !ditolakCheckbox.checked) {
                this.checked = true;
            }
        }

        // karyawan
        $("#karyawan").select2({
            placeholder: "Semua Sales",
            allowClear: true,
            ajax: {
                url: '<?= route("sales_activity.kanban.list_sales") ?>',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        search: params.term,
                        topic: "log_activity",
                        range: 1,
                        start: $("#tanggal_mulai").val(),
                        end: $("#tanggal_selesai").val()
                    };
                },
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        });

        // group
        $('#group').select2({
            placeholder: "Semua Group",
            allowClear: true,
            ajax: {
                url: '<?= route("sales_activity.kanban.list_group") ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        });

        $("#btn_filter").on("click", function() {
            var loading = Ladda.create(this);
            let mulai = $("#tanggal_mulai").val();
            let selesai = $("#tanggal_selesai").val();
            let status = "all";
            let karyawan = $("#karyawan").val() ? $("#karyawan").val() : "all";
            let group = $("#group").val() ? $("#group").val() : "all";

            if (!pengajuanCheckbox.checked || !disetujuiCheckbox.checked || !ditolakCheckbox.checked) {
                status = $("input[name='status[]']:checked").map(function() {
                    return this.value;
                }).get();
                status = status.join("_");
            }

            loading.start();
            selected_rows = [];
            list_data.ajax.url("<?= route('sales_activity.approval_activity.data', ['mulai' => '" + mulai + "', 'selesai' => '" + selesai + "', 'status' => '" + status + "', 'karyawan' => '" + karyawan + "', 'group' => '" + group + "']) ?>").load(function(response, status, xhr) {
                loading.stop();
            });
        });

        $("#btn-verify-all").on("click", function(e) {
            let mulai = $("#tanggal_mulai").val();
            let selesai = $("#tanggal_selesai").val();
            let karyawan = $("#karyawan").val() ? $("#karyawan").val() : "all";

            $.ajax({
                type: "GET",
                url: "<?= route('sales_activity.approval_activity.verification.all', ['mulai' => '" + mulai + "', 'selesai' => '" + selesai + "', 'id_karyawan' => '" + karyawan + "']) ?>",
                success: function(data) {
                    $("#modal_form .modal-dialog").removeClass("modal-lg");
                    $("#tampil_form").html(data);
                    $("#modal_form").modal("show");
                    $("#modal_form .title").text("<?= $this->lang->line('title_form_approve_pengajuan') ?>");
                }
            });
        });

        $("#btn-verify-selected").on("click", function(e) {
            $.ajax({
                type: "POST",
                data: {
                    selected_rows: selected_rows
                },
                url: "<?= route('sales_activity.approval_activity.verification.mass') ?>",
                success: function(data) {
                    req_token();
                    $("#modal_form .modal-dialog").removeClass("modal-lg");
                    $("#tampil_form").html(data);
                    $("#modal_form").modal("show");
                    $("#modal_form .title").text("<?= $this->lang->line('title_form_approve_pengajuan') ?>");
                }
            });
        });
    });

    function tanggal() {
        var d = new Date();
        d.setDate(d.getDate());
        $('.input-daterange input').each(function() {
            $(this).datepicker({
                orientation: "bottom",
                format: "dd-mm-yyyy",
                endDate: d,
                autoclose: true,
            });
        });
    }

    function preview_verify(e) {
        var tabel = $(e).data("in");
        var id = $(e).data("id");
        $("#modal_form .modal-dialog").removeClass("modal-lg");
        $("#tampil_form").load("<?= route('sales_activity.approval_activity.verification', ['tabel' => '"+ tabel +"', 'id' => '"+ id +"']) ?>", function() {
            $("#modal_form").modal("show");
            $("#modal_form .title").text("Verifikasi");
        });
    }

    function set_selected_rows(id, action) {
        if (action == 'add') {
            selected_rows.push(id);
        } else {
            selected_rows = selected_rows.filter(item => item !== id);
        }
        $("#row_selected").html(selected_rows.length);
        if (parseInt($("#row_selected").text()) > 0) {
            $("#btn-verify-selected").prop("disabled", false);
            $("#btn-verify-selected").addClass("btn-warning").removeClass("btn-light").removeAttr("style");
        } else {
            $("#btn-verify-selected").prop("disabled", true);
            $("#btn-verify-selected").removeClass("btn-warning").addClass("btn-light").css("cursor", "not-allowed");
        }
    }

    function reset_selected_rows() {
        selected_rows = [];
        $("#row_selected").html(selected_rows.length);
        $("#btn-verify-selected").prop("disabled", true);
        $("#btn-verify-selected").removeClass("btn-warning").addClass("btn-light").css("cursor", "not-allowed");
    }
</script>

<style>
    table.dataTable tbody tr:hover {
        cursor: pointer;

        :not(.selected)& {
            background-color: #fafbfc !important;
            transition: all 0.2s ease-out;
        }
    }

    table.dataTable tbody tr.selected {
        background-color: #1c77d42b !important;
    }
</style>

<div class="content-header-left mb-1">
    <label class="content-header-title" style="font-size: 16px"><?= $judul ?></label>
</div>
<hr>
<div id="filter">
    <div class="row">
        <div class="col-md-9 my-1">
            <div class="row">
                <div class="col-md-2">
                    <label><?= $this->lang->line('periode'); ?></label>
                </div>
                <div class="col-md-8">
                    <div class="input-group input-daterange">
                        <input type="text" class="form-control masktanggal" value="<?= $periode_mulai; ?>" id="tanggal_mulai" required>
                        <span class="align-self-center mx-1"><?= $this->lang->line('s/d'); ?></span>
                        <input type="text" class="form-control masktanggal" value="<?= $periode_selesai; ?>" id="tanggal_selesai" required>
                    </div>
                </div>
            </div>
            <div class="row mt-1">
                <div class="col-md-2">
                    <label>Status</label>
                </div>
                <div class="col-md-8">
                    <span class="pr-1">
                        <input id="pengajuan" type="checkbox" name="status[]" value="pengajuan" checked>
                        <label for="pengajuan"><?= $this->lang->line('pengajuan') ?></label>
                    </span>
                    <span class="pr-1">
                        <input id="disetujui" type="checkbox" name="status[]" value="approve" checked>
                        <label for="disetujui"><?= $this->lang->line('disetujui') ?></label>
                    </span>
                    <span class="pr-1">
                        <input id="ditolak" type="checkbox" name="status[]" value="tolak" checked>
                        <label for="ditolak"><?= $this->lang->line('ditolak') ?></label>
                    </span>
                </div>
            </div>
            <div class="row mt-1">
                <div class="col-md-2">
                    <label>Sales</label>
                </div>
                <div class="col-md-8">
                    <select id="karyawan" class="select2 form-control"></select>
                </div>
                <div class="col-md-2 btn_filter"></div>
            </div>
            <?php if ($this->level_user === '1' || $this->fungsi->cek_adm_satu_grup() == false) : ?>
                <div class="row mt-1">
                    <div class="col-md-2">
                        <label>Group</label>
                    </div>
                    <div class="col-md-8">
                        <select id="group" class="select2 form-control" style="width: 100%;"></select>
                    </div>
                    <div class="col-md-2 btn_filter"></div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<hr>

<div class="table-responsive">
    <div class="float-md-right">
        <button id="btn-verify-all" class="btn btn-light" style="cursor: not-allowed" disabled>Verify All Submission</button>
        <button id="btn-verify-selected" class="btn btn-light" style="cursor: not-allowed" disabled>Verify Selected Data <span id="row_selected" class="badge bg-white text-dark font-weight-bold" style="width: 45px;">0</span></button>
    </div>
    <table id="list_data" class="table table-bordered" style="width:100%">
        <thead>
            <tr>
                <th class="text-center align-middle"></th>
                <th class="text-center align-middle">NO</th>
                <th class="text-center align-middle">TANGGAL</th>
                <th class="text-center align-middle">SALES</th>
                <th class="text-center align-middle">AKTIVITAS</th>
                <th class="text-center align-middle">POIN</th>
                <th class="text-center align-middle">KETERANGAN</th>
                <th class="text-center align-middle">PELANGGAN</th>
                <th class="text-center align-middle">STATUS</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
