<div>
    <div class="col card--ui" id="card--dashboard">
        <header id="title--section" style="display:none !important"  class="d-flex align-items-center justify-content-between" style="display:none !important">
            <div class="title--section_name d-flex align-items-center justify-content-between">
                <i class="ico--ui title_section utenti me-2 "></i>
                <h2 class="primary">Archivio utenti</h2>
            </div>
        </header>

        <section id="subheader" class="d-flex align-items-center justify-content-between">
            @if(false)
            <form action="" class="search--form d-flex align-items-center">
                <div class="input-group mb-3">
                    <input type="text" class="form-control" placeholder="Cerca utente" aria-label="cerca utent" aria-describedby="button-addon2" wire:model="search">
                    @if($showReset)
                        <button class="btn--ui" type="button" id="button-addon2" onclick="reset()"><i class="ico--ui search"></i>Reset</button>
                    @else
                        <button class="btn--ui" type="button" id="button-addon2" wire:click="search()"><i class="ico--ui search"></i>Cerca</button>
                    @endif
                </div>
            </form>
            @endif
        </section>

        <div class="showFilter" style="display:none">
            <hr size="1">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Età</b>
                        </div>
                        <div class="col-12">
                            <div class="row mb-2">
                                <div class="col-3"><label class="form-check-label ms-2" >Da</label></div>
                                <div class="col-9"><input class="form-control " type="number" name="txtFromYear"></div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="row">
                                <div class="col-3"><label class="form-check-label ms-2" >A</label></div>
                                <div class="col-9"><input class="form-control " type="number"  name="txtToYear"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Tipologia di tesseramento</b>
                        </div>
                        <div class="col-12">
                            <select name="filterCards" class="form-select filterCards">
                                <option value="">Tutte
                                @foreach(getCards() as $card)
                                    <option value="{{$card->id}}">{{$card->name}}
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Stato tesseramento</b>
                        </div>
                        <div class="col-12">
                            <select name="filterStatus" class="form-select filterStatus" multiple="multiple">
                                <option value="2">Attivo
                                <option value="1">Sospeso
                                <option value="0">Non tesserato
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Gruppo di interesse</b>
                        </div>
                        <div class="col-12">
                            <select name="filterCategories" class="form-select filterCategories" multiple="multiple">
                                <option value="">Tutte</option>
                                @foreach($categories as $category)
                                    <option value="{{$category["id"]}}">
                                        {!! str_repeat('&bull; ', $category["indentation"] ?? 0) !!}{{$category["name"]}}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Anno di nascita</b>
                        </div>
                        <div class="col-12">
                            <div class="row mb-2">
                                <div class="col-3"><label class="form-check-label ms-2" >Da</label></div>
                                <div class="col-9"><input class="form-control " type="number" name="txtFromYearYear"></div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="row">
                                <div class="col-3"><label class="form-check-label ms-2" >A</label></div>
                                <div class="col-9"><input class="form-control " type="number"  name="txtToYearYear"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Scadenza certificato medico</b>
                        </div>
                        <div class="col-12">
                            <select name="filterScadenza" class="form-select filterScadenza" multiple="multiple">
                                <option value="1">Scaduti
                                <option value="2">In scadenza
                                <option value="3">Non consegnato
                                <option value="4">Validi
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Tipologia certificato medico</b>
                        </div>
                        <div class="col-12">
                            <select name="filterCertificateType" class="form-select filterCertificateType" multiple="multiple">
                                <option value="">Tutti
                                <option value="N">Non agonistico
                                <option value="A">Agonistico
                            </select>
                        </div>
                    </div>
                </div>

            </div>
            <div class="row g-3">
                <div class="col-md-12" style="text-align:right">
                    <button class="btn--ui lightGrey" onclick="reset()" onclick="destroyDataTable()">Reset</button>
                    <button class="btn--ui" onclick="loadDataTable()">FILTRA</button>
                </div>
            </div>
            <hr size="1">
        </div>
        <section id="anagrafiche--utenti">
            <div class="compare--chart_wrapper d-none"></div>
            <table class="table tablesaw tableHead tablesaw-stack table--lista_utenti tableHead" width="100%" id="tablesaw-350" width="100%">
                <thead>
                    <tr>
                        <th scope="col"><input type="checkbox" name="chkAll" class="chkAll"></th>
                        <th scope="col" style="text-align: center">Cognome</th>
                        <th scope="col">Nome</th>
                        <th scope="col">Telefono</th>
                        <th scope="col" style="text-align: center">Età</th>
                        <th scope="col" style="text-align: center">Anno</th>
                        <th scope="col">Tesseramento</th>
                        <th scope="col">Certificato</th>
                        <th scope="col">...</th>
                    </tr>
                </thead>
                <tbody id="checkall-target"></tbody>
            </table>
        </section>
    </div>
</div>
@push('scripts')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        table.tableHead thead
        {
            position: sticky;
            z-index: 100;
            top: 0;
        }
        .select2-container--default .select2-selection--single
        {
            background-color: #E9F0F5;
            border: 0.0625rem solid #DFE5EB;
            font-size: 0.75rem;
        }
        .select2-selection
        {
            height: 38px !important;
        }
        .select2-selection__rendered
        {
            padding-top:3px;
        }
        .select2
        {
            width:100% !important;
        }
        a.notSelected
        {
            display: flex;
            margin-right:10px;
            float:left;
            height: 2.5rem !important;
            width:50px;
            align-items: center;
            justify-content: center;
            color: var(--color-blu);
            background-color: #d3dce1 !important;
            padding: 0 1.25rem;
            font-size: 0.875rem;
            font-family: greycliff-cf, sans-serif;
            border-radius: 1.875rem !important;
            -webkit-border-radius: 1.875rem !important;
            -moz-border-radius: 1.875rem !important;
            -webkit-transition: all 0.3s ease-in-out;
            -moz-transition: all 0.3s ease-in-out;
            -o-transition: all 0.3s ease-in-out;
            transition: all 0.3s ease-in-out;
            border: none;
        }
        a.selected
        {
            display: flex;
            margin-right:10px;
            float:left;
            height: 2.5rem !important;
            width:50px;
            align-items: center;
            justify-content: center;
            color: #fff;
            background-color: var(--color-blu) !important;
            padding: 0 1.25rem;
            font-size: 0.875rem;
            font-family: greycliff-cf, sans-serif;
            border-radius: 1.875rem !important;
            -webkit-border-radius: 1.875rem !important;
            -moz-border-radius: 1.875rem !important;
            -webkit-transition: all 0.3s ease-in-out;
            -moz-transition: all 0.3s ease-in-out;
            -o-transition: all 0.3s ease-in-out;
            transition: all 0.3s ease-in-out;
            border: none;
        }
        div.day
        {
            margin-top:20px;
            color: var(--color-blu);
            background-color: #ffffff !important;
            padding: 20px;
            border-radius: 1.875rem !important;
            -webkit-border-radius: 1.875rem !important;
            -moz-border-radius: 1.875rem !important;
            -webkit-transition: all 0.3s ease-in-out;
            -moz-transition: all 0.3s ease-in-out;
            -o-transition: all 0.3s ease-in-out;
            transition: all 0.3s ease-in-out;
            border: 2px solid #d3dce1;
        }
        .btn--ui.lightGrey, .btn--ui.extraLightGrey
        {
            -webkit-border-radius: 0.5rem !important;
            background-color:#ffffff !important;
            border: 1px solid grey;
            color: black;
            font-weight:normal;
        }

        .persistent-invalid
        {
            border-color: #dc3545 !important;
            padding-right: calc(1.5em + 0.75rem) !important;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e") !important;
            background-repeat: no-repeat !important;
            background-position: right calc(0.375em + 0.1875rem) center !important;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem) !important;
        }
    </style>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
@endpush

@push('scripts')
    <link href="/css/datatables.css" rel="stylesheet" />
    <script src="/assets/js/datatables.js"></script>
    <script src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.dataTables.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
@endpush

@push('scripts')
    <script>
        function restoreMultipleData()
        {
            var ids = [];
            $(".chkIds").each(function () {
                if (this.checked) ids.push($(this).val());
            });

            if (ids.length) {
                if (confirm('Sei sicuro? Gli utenti verranno ripristinati.'))
                    @this.restoreMultiple(ids);
            }
        }

        function restoreData(id)
        {
            if (confirm('Sei sicuro? L\'utente verrà ripristinato.'))
                @this.restore(id);
        }

        function archiveMultipleData()
        {
            var ids = [];
            $(".chkIds").each(function () {
                if (this.checked) ids.push($(this).val());
            });

            if (ids.length) {
                if (confirm('Sei sicuro? Tutti i dati relativi a questi utenti verranno archiviati e non saranno più visibili.'))
                    @this.archiveMultiple(ids);
            }
        }

        function archiveData(id)
        {
            if (confirm('Sei sicuro? Tutti i dati relativi a questo utente verranno archiviati e non saranno più visibili.'))
                @this.archive(id);
        }

        var isFilter = false;
        $(document).ready(function() {
            $(document).on("click",".showHideFilter",function() {
                if (isFilter)
                {
                    isFilter = false;
                    $(".showFilter").hide();
                }
                else
                {
                    isFilter = true;
                    $(".showFilter").show();
                }
            });
        } );

        $(document).ready(function() {
            loadFilters();
            loadDataTable();
        } );

        function destroyDataTable()
        {
            $('#tablesaw-350').DataTable().destroy();
        }

        $('.filterCards').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterStatus').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterScadenza').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterCertificateType').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterCategories').select2({"language": {"noResults": function(){return "Nessun risultato";}}});

        function loadFilters() {
            let show = false;
            var filterStatus = localStorage.getItem("filterStatusMember");
            if (filterStatus != null && filterStatus != "null" && filterStatus != "undefined" && filterStatus)
            {
                $('.filterStatus').val(filterStatus).trigger('change');
                show = true;
            }
            var filterCards = localStorage.getItem("filterCardsMember");
            if (filterCards != null && filterCards != "null" && filterCards != "undefined" && filterCards)
            {
                $('.filterCards').val(filterCards).trigger('change');
                show = true;
            }
            var filterScadenza = localStorage.getItem("filterScadenzaMember");
            if (filterScadenza != null && filterScadenza != "null" && filterScadenza != "undefined" && filterScadenza)
            {
                $('.filterScadenza').val(filterScadenza).trigger('change');
                show = true;
            }
            var filterCertificateType = localStorage.getItem("filterCertificateTypeMember");
            if (filterCertificateType != null && filterCertificateType != "null" && filterCertificateType != "undefined" && filterCertificateType)
            {
                $('.filterCertificateType').val(filterCertificateType).trigger('change');
                show = true;
            }
            var filterCategories = localStorage.getItem("filterCategoriesMember");
            if (filterCategories != null && filterCategories != "null" && filterCategories != "undefined" && filterCategories)
            {
                $('.filterCategories').val(filterCategories).trigger('change');
                show = true;
            }
            var fromYear = localStorage.getItem("fromYearMember");
            if (fromYear != null && fromYear != "null" && fromYear != "undefined" && fromYear)
            {
                $('input[name="txtFromYear"]').val(fromYear);
                show = true;
            }
            var toYear = localStorage.getItem("toYearMember");
            if (toYear != null && toYear != "null" && toYear != "undefined" && toYear)
            {
                $('input[name="txtToYear"]').val(toYear);
                show = true;
            }
            var fromYearYear = localStorage.getItem("fromYearYearMember");
            if (fromYearYear != null && fromYearYear != "null" && fromYearYear != "undefined" && fromYearYear)
            {
                $('input[name="txtFromYearYear"]').val(fromYearYear);
                show = true;
            }

            var toYearYear = localStorage.getItem("toYearYearMember");
            if (toYearYear != null && toYearYear != "null" && toYearYear != "undefined" && toYearYear)
            {
                $('input[name="txtToYearYear"]').val(toYearYear);
                show = true;
            }

            if (show) {
                $('.showHideFilter').trigger('click');
            }
        }

        $(document).on("keypress", $('.filterCategories'), function (e) {

            setTimeout(() => {
                $(".select2-results__option").each(function(){
                    var txt = $(this).html();
                    var count = (txt.match(/-/g) || []).length;
                    $(this).addClass('paddingLeftSelect' + count);
                });
            }, 100);
        });

        $('.filterCategories').on('select2:open', function (e) {
            setTimeout(() => {
                $(".select2-results__option").each(function(){
                    var txt = $(this).html();
                    var count = (txt.match(/-/g) || []).length;
                    $(this).addClass('paddingLeftSelect' + count);
                });
            }, 100);
        });

        function reset()
        {
            $('.filterCards').val('').trigger('change');
            $('.filterStatus').val('').trigger('change');
            $('.filterScadenza').val('-1').trigger('change');
            $('.filterCertificateType').val('-1').trigger('change');
            $('.filterCategories').val('-1').trigger('change');


            $('input[name="txtFromYear"]').val('');
            $('input[name="txtToYear"]').val('');

            $('input[name="txtFromYearYear"]').val('');
            $('input[name="txtToYearYear"]').val('');
            loadDataTable();
        }

        function loadDataTable() {
            let date = new Date();
            let date_export = `${date.getFullYear()}${date.getMonth()}${date.getDate()}_`;

            const url = '/get_members?cards=' + $('.filterCards').val() + "&filterCategories=" + $('.filterCategories').val() + "&filterCertificateType=" + $('.filterCertificateType').val() + "&filterScadenza=" + $('.filterScadenza').val() + "&filterStatus=" + $('.filterStatus').val() + "&fromYear=" + $('input[name="txtFromYear"]').val() + "&toYear=" + $('input[name="txtToYear"]').val() + "&fromYearYear=" + $('input[name="txtFromYearYear"]').val() + "&toYearYear=" + $('input[name="txtToYearYear"]').val() + "&archived=1";

            localStorage.setItem("filterCardsMember", $('.filterCards').val());
            localStorage.setItem("filterCategoriesMember", $('.filterCategories').val());
            localStorage.setItem("filterCertificateTypeMember", $('.filterCertificateType').val());
            localStorage.setItem("filterScadenzaMember", $('.filterScadenza').val());
            localStorage.setItem("filterStatusMember", $('.filterStatus').val());
            localStorage.setItem("fromYearMember", $('input[name="txtFromYear"]').val());
            localStorage.setItem("toYearMember", $('input[name="txtToYear"]').val());
            localStorage.setItem("fromYearYearMember", $('input[name="txtFromYearYear"]').val());
            localStorage.setItem("toYearYearMember", $('input[name="txtToYearYear"]').val());

            if ($.fn.dataTable.isDataTable('#tablesaw-350')) {
                $('#tablesaw-350').DataTable().destroy();
            }

            const pageLength = 10;

            const dataTable = $('#tablesaw-350').DataTable({
                serverSide: true,
                processing: true,
                ajax: url,
                columns: [
                    {
                        data: "member_id",
                        orderable: false,
                        render: function (data){
                            var ret = '<input type="checkbox" name="chk'+data+'" value="'+data+'" class="chkIds" onchange="updateMultipleSelection()">';
                            return ret;
                        }
                    },
                    {
                        data: "last_name",
                        render: function (data){
                            const d = data.split("|");
                            var ret = d[0];
                            return ret;
                        }
                    },
                    {
                        data: "first_name",
                        render: function (data){
                            const d = data.split("|");
                            var ret = d[0];
                            return ret;
                        }
                    },
                    { data: "phone"},
                    { data: "age", "type": "num", className:"dt-type-numeric"},
                    { data: "year", className:"dt-type-numeric"},
                    {
                        data: "status",
                        render: function (data){
                            const d = data.split("|");
                            var ret = '<span class="tablesaw-cell-content"><span class="badge tessera-badge ' + d[0] + '">' + d[1] + '</span></span>';
                            return ret;
                        }
                    },
                    {
                        data: "certificate",
                        render: function (data){
                            var ret = '';
                            if (data != "") {
                                const d = data.split("|");
                                ret += '<span class="tablesaw-cell-content d-flex align-items-center">';
                                if (d[0] == "0") {
                                    ret += '<i class="ico--ui check suspended me-2"></i>';
                                    ret += 'Scaduto : ';
                                }
                                if (d[0] == "1") {
                                    ret += '<i class="ico--ui check due me-2"></i>';
                                    ret += 'In scadenza : ';
                                }
                                if (d[0] == "2") {
                                    ret += '<i class="ico--ui check active me-2"></i>';
                                    ret += 'Scadenza : ';
                                }
                                ret += d[1];
                                ret += '</span>';
                            }
                            if(data == ""){
                                ret += '<span class="tablesaw-cell-content d-flex align-items-center">';
                                ret += '<i class="ico--ui check absent me-2"></i>';
                                ret += 'Non consegnato';
                                ret += '</span>';
                            }
                            return ret;
                        }
                    },
                    {
                        data: "action",
                        render: function (data) {
                            var ret = '<button type="button" class="btn" onclick="restoreData(' + data + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Ripristina"><i class="fa-solid fa-rotate-left"></i></button>&nbsp;';
                            ret += '<button type="button" class="btn" onclick="archiveData(' + data + ')" data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Elimina"><i class="fa-regular fa-trash-can"></i></button>';
                            return ret;
                        }
                    },
                ],
                fixedHeader: false,
                thead: {
                    'th': {'background-color': 'blue'}
                },
                layout: {
                    topStart : null,
                    topEnd : null,
                    top1A: {
                        buttons: [
                            {
                                extend: 'collection',
                                text: 'ESPORTA',
                                buttons: [
                                    {
                                        extend: 'excelHtml5',
                                        text: '<i class="fa-solid fa-file-excel"></i>',
                                        action: newexportaction,
                                        title: 'Utenti archiviati',
                                        exportOptions: {
                                            columns: ":not(':last')",
                                            page: 'all'
                                        }
                                    },
                                    {
                                        extend: 'pdfHtml5',
                                        text: '<i class="fa-solid fa-file-pdf"></i>',
                                        action: newexportaction,
                                        title: 'Utenti archiviati',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        },
                                        customize: function(doc) {
                                            doc.styles.tableHeader.alignment = 'left';
                                        }
                                    },
                                    {
                                        extend: 'print',
                                        action: newexportaction,
                                        text: '<i class="fa-solid fa-print"></i>',
                                        title: 'Utenti archiviati',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    }
                                ],
                                dropup: true
                            },
                            {
                                text: '<i class="fa-solid fa-rotate-left"></i>',
                                attr: {
                                    id: 'btnRestore',
                                    style: 'display: none',
                                    onclick: 'restoreMultipleData()',
                                    class: 'btn archive-multiple-btn',
                                    "data-bs-toggle":"popover",
                                    "data-bs-trigger":"hover focus",
                                    "data-bs-placement":"bottom",
                                    "data-bs-content":"Ripristina",
                                }
                            },
                            {
                                text: '<i class="fa-regular fa-trash-can"></i>',
                                attr: {
                                    id: 'btnArchive',
                                    style: 'display: none',
                                    onclick: 'archiveMultipleData()',
                                    class: 'btn archive-multiple-btn',
                                    "data-bs-toggle":"popover",
                                    "data-bs-trigger":"hover focus",
                                    "data-bs-placement":"bottom",
                                    "data-bs-content":"Archivia",
                                }
                            },
                        ]
                    },
                    top1B : {
                        pageLength: {
                            menu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "Tutti"]]
                        }
                    },
                    top1C :'search',
                    bottomEnd: {
                        paging: {
                            boundaryNumbers: false
                        }
                    }
                },
                pagingType: 'first_last_numbers',
                language: {
                    "url": "/assets/js/Italian.json",
                    paginate: {
                        first: '<i class="fa-solid fa-angles-left"></i>',
                        last: '<i class="fa-solid fa-angles-right"></i>',
                    }
                },
                "fnInitComplete": function (oSettings, json) {
                    var html = '&nbsp;<a style="cursor:pointer" class="showHideFilter btn--ui"><i class="fa-solid fa-sliders"></i></a>';
                    html += '&nbsp;<a style="cursor:pointer" class="addData btn--ui"><i class="fa-solid fa-plus"></i></a>';
                    $(".dt-search").append(html);
                    
                    loadFilters();
                }
            });

            $('#tablesaw-350 thead tr th').addClass('col');
            $('#tablesaw-350 thead tr th').css("background-color", "#f6f8fa");
            $('#tablesaw-350').on('draw.dt', function() {
                $('[data-bs-toggle="popover"]').popover()
            });

            $(".chkAll").change(function () {
                var check = this.checked;
                var ok = false;
                $(".chkIds").each(function () {
                    $(this).prop("checked", check);
                    ok = true;
                });
                if (check && ok) {
                    $("#btnRestore").show();
                    $("#btnArchive").show();
                } else {
                    $("#btnRestore").hide();
                    $("#btnArchive").hide();
                }
            });
        }

        function updateMultipleSelection() {
            let checked = false;
            $(".chkIds").each(function () {
                if (this.checked) checked = true;
            });                

            if (checked) {
                $("#btnRestore").show();
                $("#btnArchive").show();
            } else {
                $("#btnRestore").hide();
                $("#btnArchive").hide();
                $(".chkAll").prop("checked", false);
            }
        }

        Livewire.on('reload', (x) =>
        {
            location.reload();
        });
    </script>
@endpush
