<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">
        <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">Ricevute</h2>
        </div>

        <!--
        <div class="title--section_addButton"  wire:click="add()" style="cursor: pointer;">
            <div class="btn--ui entrata d-flex justify-items-between">
                <a href="#" wire:click="add()" style="color:white">Aggiungi</a>
            </div>
        </div>
        -->

    </header>
    
    <div class="alert alert-success" id="email-alert-success" role="alert" style="display: none">
        Email inviata con successo
    </div>

    <div class="showFilter" style="display:none"  wire:ignore.self>
        <hr size="1">
        <div class="row g-3">
            <div class="col-md-2">
                <div class="row">
                    <div class="col-md-12" style="margin-bottom:10px;">
                        <b>Periodo</b>
                    </div>
                    <div class="col-12 mb-2">
                        <input id="dateFrom" type="date" class="form-control filterFrom" name="txtFrom">
                    </div>
                    <div class="col-12">
                        <input id="dateTo" type="date" class="form-control filterTo" name="txtTo">
                    </div>
                    <div class="col-6 mt-2">
                        <button class="btn--ui lightGrey todayButton" style="width:100%" onclick="setToday('{{date("Y-m-d")}}')">OGGI</button>
                    </div>
                    <div class="col-6 mt-2">
                        <button class="btn--ui lightGrey yesterdayButton" style="width:100%" onclick="setYesterday('{{date("Y-m-d",strtotime("-1 days"))}}')">IERI</button>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="row">
                    <div class="col-md-12" style="margin-bottom:10px;">
                        <b>Stato</b>
                    </div>
                    <div class="col-12">
                        <select class="form-select filterStatus">
                            <option value="">--Seleziona--
                            <option value="1">Attiva
                            <option value="99">Annullata
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="row">
                    <div class="col-md-12" style="margin-bottom:10px;">
                        <b>Utente</b>
                    </div>
                    <div class="col-12">
                        <select class="form-select filterMember" wire:model="filteredMemberId">
                            <option value="">--Seleziona Utente--</option>
                            @foreach($members as $member)
                                <option value="{{ $member->id }}">{{ $member->last_name }} {{ $member->first_name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="row g-3">
            <div class="col-md-12" style="text-align:right">
                <button class="btn--ui_outline light" onclick="reset()">RESET</button>
                <button class="btn--ui" onclick="loadDataTable()">FILTRA</button>
            </div>
        </div>
        <hr size="1">
    </div>

    <section id="resume-table">
        <div class="compare--chart_wrapper d-none"></div>

        <table class="table tablesaw tableHead tablesaw-stack table--lista_ricevute" id="tablesaw-350" width="100%">
            <thead>
                <tr>
                    <th scope="col">Anno</th>
                    <th scope="col">N°</th>
                    <th scope="col">Cognome</th>
                    <th scope="col">Nome</th>
                    <th scope="col">Stato</th>
                    <th scope="col">Data</th>
                    <th scope="col">Importo</th>
                    <th scope="col">...</th>
                </tr>
            </thead>
            <tbody id="checkall-target">
                @if(false)
                    @foreach($records as $record)
                        <tr>
                            <td>{{$record->year}}</td>
                            <td>{{$record->number}}</td>
                            <td>{{$record->type == 'IN' ? ($record->member->last_name) : 'Uscita'}}</td>
                            <td>{{$record->type == 'IN' ? ($record->member->first_name) : ''}}</td>
                            <td>
                                <span class="tablesaw-cell-content">
                                    <span class="badge tessera-badge {{$record->status == 1 ? 'active' : 'suspended'}}">{{$record->status == 1 ? 'Attivo' : 'Annullata'}}</span>
                                </span>
                            </td>
                            <td>{{date("d/m/Y", strtotime($record->date))}}</td>
                            <td>{{formatPrice($record->rows->sum('amount'))}}</td>
                            <td>
                                <button type="button" class="btn u"
                                    onclick="document.location.href='/in?id={{$record->record_id}}'" data-bs-toggle="popover"
                                    data-bs-trigger="hover focus" data-bs-placement="bottom"
                                    data-bs-content="Visualizza ricevuta"><i class="fa-regular fa-eye"></i></button>
                                <a target="_blank" class="btn  u" href="/receipt/{{$record->id}}" data-bs-toggle="popover"
                                    data-bs-trigger="hover focus" data-bs-placement="bottom"
                                    data-bs-content="Stampa ricevuta"><i class="fa-regular fa-file-lines"></i></a>
                                <a target="_blank" class="btn u" onclick="sendMail({{$record->id}})"><i
                                        class="fa-regular fa-envelope" data-bs-toggle="popover" data-bs-trigger="hover focus"
                                        data-bs-placement="bottom" data-bs-content="Invia email"></i></a>
                            </td>
                        </tr>
                    @endforeach
                @endif
            </tbody>
        </table>
        <br>
    </section>

</div>


@push('scripts')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .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;
        }
    </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="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>


    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .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;
        }
        .select2-selection--multiple{
            overflow: hidden !important;
            height: auto !important;
        }
        .select2-container {
            box-sizing: border-box;
            display: inline-block;
            margin: 0;
            position: relative;
            vertical-align: middle;
        }
        .select2-container .select2-selection--single {
            box-sizing: border-box;
            cursor: pointer;
            display: block;
            height: 38px;
            user-select: none;
            -webkit-user-select: none;
        }
        .select2-container .select2-selection--single .select2-selection__rendered {
            display: block;
            padding-left: 8px;
            padding-right: 20px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .select2-selection__choice__display{
            color:#000000 !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>
    <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>

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

        $('.filterStatus').select2({ "language": { "noResults": function () { return "Nessun risultato"; } } });
        $('.filterMember').select2({
            "language": { "noResults": function () { return "Nessun risultato"; } }
        });


        Livewire.on('load-data-table', () => {
            $('.filterStatus').select2({ "language": { "noResults": function () { return "Nessun risultato"; } } });
            $('.filterMember').select2({ "language": { "noResults": function () { return "Nessun risultato"; } } });

            loadDataTable();
        });

        Livewire.on('load-data-table', () => {
            setTimeout(function() {loadDataTable()}, 100);
        });

        Livewire.on('destroy-data-table', () => {
            $('#tablesaw-350').DataTable().destroy();
        });

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

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

        function sendMail(id)
        {
            // $.get("/receipt/mail/" + id, function(data, status){
            //     alert('Mail inviata');
            // });
            $.get("/receipt/mail/" + id, function (data, status) {
                let alert = document.getElementById("email-alert-success");
                if (alert) {
                    alert.style.display = "";
                    setTimeout(() => {
                        alert.style.display = "none";
                    }, 3000)
                } else {
                    alert("Email inviata con successo");
                }
            });
        }

        @if(isset($_GET["showFilters"]))
            setTimeout(function() {
                var filterStatus = localStorage.getItem("filterStatusReceipt");
                if (filterStatus && filterStatus !== "null" && filterStatus !== "undefined") {
                    $('.filterStatus').val(filterStatus).trigger('change');
                }

                var filterFrom = localStorage.getItem("filterFromReceipt");
                if (filterFrom && filterFrom !== "null" && filterFrom !== "undefined") {
                    $('input[name="txtFrom"]').val(filterFrom);
                }

                var filterTo = localStorage.getItem("filterToReceipt");
                if (filterTo && filterTo !== "null" && filterTo !== "undefined") {
                    $('input[name="txtTo"]').val(filterTo);
                }

                var filterMember = localStorage.getItem("filterMemberReceipt");
                if (filterMember && filterMember !== "null" && filterMember !== "undefined") {
                    $('.filterMember').val(filterMember).trigger('change');
                }

                isFilter = true;
                loadDataTable();
            }, 100);
        @else
            loadDataTable();
        @endif

        function reset()
        {
            $(".todayButton").addClass("lightGrey");
            $(".yesterdayButton").addClass("lightGrey");
            $('.filterStatus').val(null).trigger("change");
            $('.filterMember').val(null).trigger("change");
            $('.filterFrom').val('');
            $('.filterTo').val('');
            destroyDataTable();
            loadDataTable();
        }

        function loadDataTable(){

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

            var filterStatus = $('.filterStatus').val();
            localStorage.setItem("filterStatusReceipt", filterStatus);

            var filterFrom = $('.filterFrom').val();
            localStorage.setItem("filterFromReceipt", filterFrom);

            var filterTo = $('.filterTo').val();
            localStorage.setItem("filterToReeipt", filterTo);


            var filterMember = $('.filterMember').val();
            localStorage.setItem("filterMemberReceipt", filterMember);


            $('#tablesaw-350').DataTable({
                serverSide: true,
                ajax: {
                    url: '/get_receipts?filterStatus=' + filterStatus + '&filterFrom=' + filterFrom + '&filterTo=' + filterTo + '&filterMember=' + filterMember,
                    dataSrc: function (json) {
                        if(json.totals){
                            totals = json.totals;
                        }
                        return json.data;
                    }
                },
                thead: {
                'th': {'background-color': 'blue'}
                },
                columns: [
                    {
                        data: 'year', className: "numericCol"
                    },
                    {
                        data: 'number', className: "numericCol"
                    },
                    {
                        data: 'last_name'
                    },
                    {
                        data: 'first_name'
                    },
                    {
                        data: "status",
                        render: function (data){
                            // Split class and text
                            var ret = '<span class="tablesaw-cell-content"><span class="badge tessera-badge ' + (data == 1 ? 'active' : 'suspended') + '">' + (data == 1 ? 'Attiva' : 'Annullata') + '</span></span>';
                            return ret;
                        }
                    },
                    {
                        data: 'date', className: "numericCol"
                    },
                    {
                        data: 'totals'
                    },
                    {
                        data: "action",
                        render: function (data){
                            var ids = data.split("|");
                            // Split class and text
                            var ret = '<button type="button" class="btn u" onclick="document.location.href=' + "'" + '/in?id=' + ids[1] + "&from=receipts'" + '" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Visualizza ricevuta"><i class="fa-regular fa-eye"></i></button>';
                            ret += '<a target="_blank" class="btn  u" href="/receipt/' + ids[0] + '" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Stampa ricevuta"><i class="fa-regular fa-file-lines"></i></a>';
                            ret += '<a target="_blank" class="btn u" onclick="sendMail(' + ids[0] + ')"><i class="fa-regular fa-envelope" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Invia email"></i></a>';
                            return ret;
                        }
                    }
                ],
                layout: {
                    topStart : null,
                    topEnd : null,
                    top1A: {
                        buttons: [
                            {
                                extend: 'collection',
                                text: 'ESPORTA',
                                buttons: [
                                    {
                                    extend: 'excelHtml5',"action":newexportaction,
                                        title: 'Ricevute',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'pdfHtml5',"action":newexportaction,
                                        title: 'Ricevute',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'print',"action":newexportaction,
                                        text: 'Stampa',
                                        title: 'Ricevute',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    }
                                ],
                                dropup: true
                            }
                        ]
                    },
                    top1B : {
                        pageLength: {
                            menu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "Tutti"]]
                        }
                    },
                    top1C :'search',
                    bottomEnd: {
                        paging: {
                            boundaryNumbers: false
                        }
                    }
                },
                order: [[0, 'desc'], [1, 'asc']],
                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) {
                    if ($(".dt-search .showHideFilter").length === 0) {
                        var html = '&nbsp;<a href="#" class="showHideFilter btn--ui"><i class="fa-solid fa-sliders"></i></a>';
                        console.log(html);
                        $(".dt-search").append(html);
                    }
                },
            });
            $('#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()
            });

            $(document).ready(function() {
                $(document).on("click",".addData",function() {
                    $(".title--section_addButton").trigger("click")
                });
            } );

        }

    </script>
@endpush

