<script src="/js/plugins/dataTables/datatables.min.js"></script>
<link href="/css/plugins/dataTables/fixedHeader.dataTables.min.css" rel="stylesheet">
<script src="/js/plugins/dataTables/dataTables.fixedColumns.min.js"></script>
<script src="/js/plugins/chosen/chosen.jquery.js"></script>
<script src="/js/plugins/chosen/chosen.ajaxaddition.jquery.js"></script>
    <script>

        $(document).ready(function() {
            $('#device_type').val($('.page-heading').find('h2').text());
            $.fn.serializeObject = function(){
                var obj = {};

                $.each( this.serializeArray(), function(i,o){
                    var n = o.name, v = o.value;

                    obj[n] = obj[n] === undefined ? v
                        : $.isArray( obj[n] ) ? obj[n].concat( v )
                        : [ obj[n], v ];
                });

                return obj;
            };

            $('.searchable').select2();

            var table = $('.footable').DataTable({
                fixedHeader:true,
                "scrollX": true,
                fixedColumns: true,
                fixedColumns: {
                    left: 2
                },
                "processing": true,
                "serverSide": true,
                lengthMenu: [
                    [10, 25, 50, 100],
                    [10, 25, 50, 100]
                ],
                iDisplayLength: 50,
                "columnDefs": [
                    { "orderable": false, "targets": 1 },
                    { "width": "5%", "orderable": false, "targets": 'azioni' }
                ],
                "ajax":{
                    "url": "{{ route('windows-compliance-report-data') }}",
                    "dataType": "json",
                    "type": "POST",
                    "data": function( result ) {
                        result.form = $('#filter-form').serializeObject();
                    }
                },
                "columns": [
                    { "data": "id" },
                    { "data": "serial_no" },
                    { "data": "asset_serial_no" },
                    { "data": "asset_type" },
                    { "data": "hardware_standard" },
                    { "data": "hardware_teqtivity" },
                    { "data": "technical_spec" },
                    { "data": "asset_status" },
                    { "data": "user_location" },
                    { "data": "intune_user" },
                    { "data": "os_platform" },
                    { "data": "os_version" },
                    { "data": "latest_version" },
                    { "data": "check_in_date" },
                ],
                "fnDrawCallback": function (oSettings) {
                    if (table.page.info().recordsTotal == 0) {
                        $("#export-csv").hide();
                    } else {
                        $("#export-csv").show();
                    }
                },
            });

            //Data table column toggle
            $(document).on('click', 'span.col-toggle', function (e) {
                e.preventDefault();

                $(this).toggleClass('col-hidden');
                // Get the column API object
                var column = table.column($(this).attr('data-column'));

                // Toggle the visibility
                column.visible(!column.visible());
            });

            $('#filter-form').submit(function (e) {
                e.preventDefault();
                table.draw();
            });

            $('.input-group.date').on('show', function(e) {
                $("th.clear").attr('colspan', 8)
            }).datepicker({
                todayBtn: "linked",
                clearBtn: true,
                keyboardNavigation: false,
                forceParse: false,
                calendarWeeks: true,
                autoclose: true,
            }).on('change',function(e){
                $('#filter-form').submit();
            });

            $(".windows-compliance-filter").on('change', function(){
                $('#filter-form').submit();
            });

            $(".filter-field").each(function() {
                var name = $(this).attr('key');
                var url = (name == 'asset_tag') || (name == 'hardware') ? '/get-filter-fields' : '/discovery-tools/intune/get-filter-fields-intune';
                $( this ).select2({
                    tokenizer: function (input, s2, callback) {
                        var term = input.term;
                        if (term.indexOf(',') < 0)
                            return input; // Exit if no tokens

                        var parts = term.split(",");
                        for (var i = 0; i < parts.length; i++) {
                            var part = parts[i].trim();
                            if (part.length > 2) {
                                $.ajax({
                                    url: s2.options.ajax.url,
                                    dataType: s2.options.ajax.dataType,
                                    data: s2.options.ajax.data({ term: part }),
                                    async: false, // If async then unable to return unmatched tokens
                                    success: function (data) {
                                        var pr = s2.options.ajax.processResults(data, { term: part });
                                        if(pr.results[0].value != 0) {
                                            callback(pr.results[0]);
                                            parts.splice(i--, 1);
                                        }
                                    }
                                });
                            }
                        }
                        return { term: parts.join(',') }; // Rejoin unmatched tokens
                    },
                    minimumInputLength: 1,
                    multiple: true,
                    ajax: {
                        url: url,
                        dataType: "json",
                        data: function (params){
                          var query = {
                            search: params.term,
                            type: name
                          }

                          // Query parameters will be ?search=[term]&type=public
                          return query;
                        },
                        processResults: function (data) {
                          // Tranforms the top-level key of the response object from 'items' to 'results'
                          return {
                            results: data
                          };
                        },

                    }
                });
            });

            $(".filter-field-user").each(function() {
                $( this ).select2({
                    tokenizer: function (input, s2, callback) {
                        var term = input.term;
                        if (term.indexOf(',') < 0)
                            return input; // Exit if no tokens

                        var parts = term.split(",");
                        for (var i = 0; i < parts.length; i++) {
                            var part = parts[i].trim();
                            if (part.length > 2) {
                                $.ajax({
                                    url: s2.options.ajax.url,
                                    dataType: s2.options.ajax.dataType,
                                    data: s2.options.ajax.data({ term: part }),
                                    async: false, // If async then unable to return unmatched tokens
                                    success: function (data) {
                                        var pr = s2.options.ajax.processResults(data, { term: part });
                                        callback(pr.results[0]);
                                        parts.splice(i--, 1);
                                    }
                                });
                            }
                        }
                        return { term: parts.join(',') }; // Rejoin unmatched tokens
                    },
                    minimumInputLength: 1,
                    multiple: true,
                    ajax: {
                        url: '/get-filter-fields-all-user',
                        dataType: "json",
                        data: function (params){
                          var query = {
                            search: params.term
                          }

                          // Query parameters will be ?search=[term]&type=public
                          return query;
                        },
                        processResults: function (data) {
                          // Tranforms the top-level key of the response object from 'items' to 'results'
                          return {
                            results: data
                          };
                        },

                    }
                });
            });

            $(".filter-field-location").each(function () {
                var name = $(this).attr('key');
                $(this).select2({
                    minimumInputLength: 1,
                    multiple: true,
                    ajax: {
                        url: '/get-filter-fields-location',
                        dataType: "json",
                        data: function (params) {
                            var query = {
                                search: params.term,
                                type: name
                            }

                            // Query parameters will be ?search=[term]&type=public
                            return query;
                        },
                        processResults: function (data) {
                            // Tranforms the top-level key of the response object from 'items' to 'results'
                            return {
                                results: data
                            };
                        },

                    }
                });
            });

        $('#export-csv').on('click', function(e) {
            e.preventDefault();
            $('.ajax-loader').show();
            $.ajax({
                type: "POST",
                url: "{{route('windows-compliance-report-export')}}",
                data: $('#filter-form').serializeObject(),
                dataType: 'text',
                success: function(result) {
                    var blob = new Blob([result]);
                    if (window.navigator.msSaveOrOpenBlob)
                        window.navigator.msSaveBlob(blob, "windows-oscompliance-report.csv");
                    else
                    {
                        var a = window.document.createElement("a");
                        a.href = window.URL.createObjectURL(blob, {type: "text/plain"});
                        a.download = "windows-oscompliance-report.csv";
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    }
                    $('.ajax-loader').hide();
                }
            })
        });
    })
    </script>