<div class="col card--ui" id="card--dashboard">

    <div style="z-index:999; position:absolute;left:0px, right:0px;bottom:0px; width:100%; height:100%;background-color:#0C6197; opacity:0.5; display:none; text-align:center" id="loadingDiv"><span style="margin: auto;width: 50%;color:white; font-size:40px;">Loading...</span></div>

        <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 entrate me-2"></i>
                <h2 class="primary">@if(!$add && !$update)Entrate @else Inserimento/modifica entrata @endif</h2>
            </div>

            @if(!$add && !$update)
                <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>
            @endif

        </header>


    @if(!$add && !$update)

        <!--
        <button id="open-filter" onclick="pcsh1()"></button>
        <button id="close-filter" onclick="pcsh2()"></button>
        -->

        <section id="subheader" class="d-flex align-items-center justify-content-between">
        </section>

        @if (session()->has('receipt'))
            <div class="alert alert-success" role="alert">
                {{ session()->get('receipt') }}
            </div>
        @endif

        <div class="showFilter" style="display:none">
            <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>Data di pagamento</b>
                        </div>
                        <div class="col-12 mb-2">
                            <input id="dateFrom" type="date" class="form-control filterFrom">
                        </div>
                        <div class="col-12">
                            <input id="dateTo" type="date" class="form-control filterTo" >
                        </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>Tipologia</b>
                        </div>
                        <div class="col-12">
                            <select name="filterCommercial" class="form-select filterCommercial">
                                <option value="">Entrambe
                                <option value="1">Commerciale
                                <option value="2">Non commerciale
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Utente</b>
                        </div>
                        <div class="col-12">
                            <select name="search_member_id" class="form-select filterMember">
                                <option value="">--Seleziona--
                                @foreach($members as $member)
                                    <option value="{{$member->id}}">{{$member->last_name}} {{$member->first_name}}
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Metodi di pagamento</b>
                        </div>
                        <div class="col-12">
                            <select name="search_payment_method_id" class="form-select filterPaymentMethod" multiple="multiple">
                                @foreach($payments as $payment)
                                    <option value="{{$payment->id}}">{{$payment->name}}
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Destinazioni</b>
                        </div>
                        <div class="col-12">
                            <select name="search_destination_id" class="form-select filterDestinations" multiple="multiple">
                                @foreach($banks as $bank)
                                    <option value="{{$bank["id"]}}">{!!$bank["name"]!!}
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Causali</b>
                        </div>
                        <div class="col-12">
                            <select name="search_causal_id" class="form-select filterCausals" multiple="multiple">
                                @foreach($causals as $causal)
                                    <option value="{{$causal["id"]}}">{!!$causal["name"]!!}
                                @endforeach
                            </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()">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_entrate tableHead" id="tablesaw-350" width="100%">
                <thead>
                    <tr>
                        <!--<th scope="col"></th>-->
                        <th style="text-align: right" scope="col">Data di pagamento</th>
                        <th scope="col">Importo</th>
                        <th scope="col">Cognome</th>
                        <th scope="col">Nome</th>
                        <th scope="col">Commerciale</th>
                        <th scope="col">Causale</th>
                        <th scope="col">Pagamento</th>
                        <th scope="col">Destinazione</th>

                        <th scope="col">Stato</th>
                        <th scope="col">...</th>
                    </tr>
                </thead>

                <tbody id="checkall-target">
                </tbody>
                <!--<tfoot>
                    <tr id="tfooter">
                        <td colspan="9"><span class="total"></span></td>
                    </tr>
                </tfoot>-->
            </table>

            <br><b class="totalDiv"></b>

        </section>

    @else

        @if($isDuplicate)
            <a style="margin-top:20px" class="btn--ui lightGrey" wire:click="cancel()" href="javascript:;"><i class="fa-solid fa-arrow-left"></i></a><br><br>
        @else
            <a style="margin-top:20px" class="btn--ui lightGrey" href="/{{$fromPage != '' ? ($fromPage) : 'in'}}"><i class="fa-solid fa-arrow-left"></i></a><br><br>
        @endif

        <a name="top"></a>
        @if (session()->has('error'))
            <div class="alert alert-danger" role="alert">
                {{ session()->get('error') }}
            </div>
        @endif
        
        @if($currentReceip?->status == 99)
            <div class="alert alert-warning" role="alert">
                Ricevuta annullata
            </div>
        @endif

        <section id="accountingEntry" class="d-flex">
            <div class="accountingEntry_data" wire:key='reload-{{$selectId}}'>
                <form class="form--accounting" >

                        <div class="row gx-2">

                            <div class="col-md-12">
                                <span class="title-form d-block w-100">Tipologia</span>
                                <div class="input-group mb-12">
                                    <div class="check--invoice d-flex align-items-center">
                                        <div class="form-check me-3">
                                            <input class="form-check-input" type="radio" value="1" wire:model="commercial" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                            <label class="form-check-label" for="flexCheckChecked"  {!!$this->dataId > 0 && !$isDuplicate ? '' : ' onclick="setCommercialType(1)"'!!}>&nbsp;Commerciale</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" value="0" wire:model="commercial" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                            <label class="form-check-label" for="flexCheck" {!!$this->dataId > 0 && !$isDuplicate ? '' : ' onclick="setCommercialType(0)"'!!}>&nbsp;Non Commerciale</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6 mt-3">
                                <span class="title-form d-block w-100">Data pagamento</span>
                                <div class="input-group mb-3">
                                    <input id="date" type="date" class="form-control"  wire:model="date">
                                </div>
                            </div>
                            <div class="col-md-6">&nbsp;</div>


                            <div class="col-md-6">
                                <span class="title-form d-block w-100">Utente</span>
                                <select name="member_id" class="form-select memberClass @error('member_id') is-invalid @enderror" aria-label="Seleziona una persona" wire:model="member_id" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}  >
                                    <option value="">--Seleziona--
                                    @foreach($members as $member)
                                        <option value="{{$member->id}}">{{$member->last_name}} {{$member->first_name}} ({{$member->fiscal_code}})
                                    @endforeach
                                </select>
                                @error('member_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                                <br><br>

                            </div>
                            <div class="col-md-6">
                                @if($this->dataId == 0 && !$isDuplicate)
                                    <span class="title-form d-block w-100">&nbsp;</span>
                                    <button type="button" class="btn--ui primary" data-bs-toggle="modal" data-bs-target="#userModal" style="width:50px">&nbsp;<i class="fa-solid fa-plus"></i></button>
                                @endif
                                @if(false && $this->member)
                                    <b>{{$this->member->first_name}} {{$this->member->last_name}}</b> {!! !$this->member->isAdult() ? '<span style="color:red;font-weight:bold">&nbsp;MINORENNE</span>' : '' !!}<br>
                                    <span class="title-form w-100">Codice fiscale</span> : {{$this->member->fiscal_code}}<br>
                                    <span class="title-form w-100">Email</span> : {{$this->member->email}}<br>
                                    <span class="title-form w-100">Borsellino virtuale</span>
                                    <b>{{number_format($virtual, 2, ".", "")}} &euro;</b><br>
                                    @if(sizeof($this->member->certificates) > 0)
                                        @php
                                        $cert = $this->member->certificates[0]
                                        @endphp
                                        @if($cert->expire_date < date("Y-m-d"))
                                            <span class="title-form w-100">Certificato medico </span><span class="badge tessera-badge suspended">scaduto</span>
                                        @endif
                                    @endif
                                    @php
                                    $status = $this->member->getStatus()["status"];
                                    $class = $status > 0 ? ($status == 2 ? 'active' : 'suspended') : 'due';
                                    $text = $status > 0 ? ($status == 2 ? 'Tesserato' : 'Sospeso') : 'Non tesserato';
                                    @endphp
                                    <span class="tablesaw-cell-content"><span class="badge tessera-badge {{$class}}">{{$text}}</span></span>
                                @endif
                            </div>
                        </div>

                        @if(false)
                            <br>
                            <div class="col-md-12">
                                <div class="input-group mb-12">
                                    <div class="check--invoice d-flex align-items-center">
                                        <div class="form-check me-3">
                                            <input class="form-check-input" id="financial_movement" type="checkbox" wire:model="financial_movement" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                            <label class="form-check-label" for="flexCheckChecked">&nbsp;&nbsp;&nbsp;Movimento finanziario</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endif

                        @if($commercial)

                            <br>
                            <div class="col-md-12">

                                <div class="input-group mb-12">
                                    <div class="check--invoice d-flex align-items-center">
                                        <div class="form-check me-3">
                                            <input class="form-check-input" id="corrispettivo_fiscale" type="checkbox" wire:model="corrispettivo_fiscale" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                            <label class="form-check-label" for="flexCheckChecked">&nbsp;&nbsp;&nbsp;Corrispettivo fiscale</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        @endif

                        @if($corrispettivo_fiscale)

                            @if ($this->dataId > 0)
                                <div class="row">
                                    <div class="col-md-6 mt-3">
                                        {{$this->getPaymentMethod($payment_method_id)}}
                                    </div>
                                    <div class="col-md-3 mt-3">
                                        {{$this->getBankName($destination_id)}}
                                    </div>
                                    <div class="col-md-3 mt-3">
                                        {{formatPrice($amount)}}
                                    </div>
                                </div>
                            @else
                                @foreach($payments as $payment)
                                    @if($payment->corrispettivo_fiscale)
                                        <div class="row">
                                            <div class="col-md-6 mt-3">
                                                {{$payment->name}}
                                            </div>
                                            <div class="col-md-3 mt-3">                                                
                                                <select id="corrispettivo_destination_{{$payment->id}}" name="corrispettivo_destination_{{$payment->id}}" wire:model="corrispettivo_destination.{{$payment->id}}" class="form-select" aria-label="Seleziona una destinazione" style="width:100%">
                                                    <option value="">--Seleziona--
                                                    @foreach($banks as $bank)
                                                        <option value="{{$bank->id}}">{{$bank->name}}
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="col-md-3 mt-3">
                                                <input type="text" class="form-control totalInput text-end" id="corrispettivo_{{$payment->id}}" wire:model="corrispettivo.{{$payment->id}}" onkeyup="onlyNumberAmount(this)" placeholder="€ 0,00">
                                            </div>
                                        </div>
                                    @endif
                                @endforeach

                                <div class="row">
                                    <div class="col-md-9 mt-3" style="font-size: 18px;font-weight: bold;">
                                        <b>Totale</b>
                                    </div>
                                    <div class="col-md-3 mt-3" style="text-align:right;font-size: 18px;font-weight: bold;">
                                        <b>{{$this->getTotalCorrispettivo()}}</b>
                                    </div>
                                </div>
                            @endif


                        @else

                            <div class="row gx-2 mt-3">
                                

                                <div class="col-md-6" >

                                    <span class="title-form d-block w-100">Metodo di pagamento</span>
                                    <select name="payment_method_id" class="form-select paymentClass @error('payment_method_id') is-invalid @enderror" aria-label="Seleziona un metodo di pagamento" wire:model="payment_method_id" style="width:100%"  {{$this->dataId > 0 && $deleted ? 'disabled' : ''}}>
                                        <option value="">--Seleziona--
                                        @foreach($payments as $payment)
                                            <option value="{{$payment->id}}">{{$payment->name}}
                                        @endforeach
                                    </select>
                                    @error('payment_method_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    
                                </div>
                            
                                <div class="col-md-6" >

                                    <span class="title-form d-block w-100">Destinazione</span>

                                    <select name="destination_id" class="form-select  @error('destination_id') is-invalid @enderror" aria-label="Seleziona una destinazione" wire:model="destination_id" style="width:100%"  {{$this->dataId > 0 && $deleted ? 'disabled' : ''}}>
                                        <option value="">--Seleziona--
                                        @foreach($banks as $bank)
                                            <option value="{{$bank->id}}">{{$bank->name}}
                                        @endforeach
                                    </select>
                                    @error('destination_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    
                                </div>
                            </div>

                            @foreach($rows as $idx => $row)

                                <div class="row gx-2 mt-3" >
                                    <span class="title-form d-block w-100">Causale</span>
                                    <div class="col-md-12">

                                        @if($this->dataId > 0 && !$isDuplicate)
                                            {{$this->getCausal($rows[$idx]['causal_id'])}}<br>
                                        @else
                                            <livewire:causals :type="$typeIN" :idx="$idx" :causal_id="$rows[$idx]['causal_id']" :wire:key="$idx"/>
                                        @endif

                                        @error('rows.'. $idx . '.causal_id')
                                            <span style="argin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
                                        @enderror

                                    </div>
                                </div>

                                <div class="row gx-2 mt-3">
                                    <span class="title-form d-block w-100">Dettaglio causale</span>
                                    <div class="col-md-6">
                                        <input class="form-control " id="causal_detail_{{$idx}}" type="text" placeholder="Dettaglio causale" wire:model="rows.{{$idx}}.note" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                    </div>
                                </div>

                                <div class="row gx-2 mt-3 align-items-center">
                                    <div class="col-md-6">
                                        <span class="total primary">Importo</span>
                                    </div>
                                    @if ($commercial)
                                        <div class="col-md-3">
                                            <select id="rows.{{$idx}}.vat_id" class="form-select"  wire:model="rows.{{$idx}}.vat_id" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                                <option value="0">
                                                @foreach($vats as $vat)
                                                    <option value="{{$vat->id}}">{{$vat->name}}
                                                @endforeach
                                            </select>
                                        </div>
                                    @else
                                        <div class="col-md-3"></div>
                                    @endif
                                    <div class="col-md-3">
                                        @if($add)
                                            <input type="text" class="form-control totalInput text-end @error('amount') is-invalid @enderror" id="rows.{{$idx}}.amount" wire:model="rows.{{$idx}}.amount" wire:keydown.enter="store(false)" onkeyup="onlyNumberAmount(this)" onchange="setChangedAmount()" placeholder="€ 0,00" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}  >
                                        @endif
                                        @if($update)
                                            <input type="text" class="form-control totalInput text-end @error('amount') is-invalid @enderror" id="rows.{{$idx}}.amount" placeholder="€ 0,00" wire:model="rows.{{$idx}}.amount"  onkeyup="onlyNumberAmount(this)" onchange="setChangedAmount()" wire:keydown.enter="update(false)" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                        @endif
                                        @error('rows.'. $idx . '.amount')
                                            <span style="argin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
                                        @enderror
                                    </div>

                                </div>

                                <div class="row gx-2 mt-3 align-items-center">
                                    <div class="col-md-4">
                                        <span class="total primary comp">Competenza</span>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="row">

                                            @if($multiP)
                                                <div class="row">
                                                    <h4>Seleziona inizio e fine multiperiodo</h4>
                                                    <div class="col-lg-6 col-xxl-3">
                                                        <span class="title-form d-block w-100">Dal mese</span>
                                                        <div class="input-group mb-3">
                                                            <select class="form-select form-select-lg me-1"  wire:model="multiMonthFrom" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                                                @foreach(getMonthList() as $mid => $mname)
                                                                    <option value="{{$mid}}">{{$mname}}</option>
                                                                @endforeach

                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-6 col-xxl-3">
                                                        <span class="title-form d-block w-100">Anno</span>
                                                        <div class="input-group mb-3">
                                                            <input type="number" class="form-control"  wire:model="multiYearFrom"  {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-6 col-xxl-3">
                                                        <span class="title-form d-block w-100">Dal mese</span>
                                                        <div class="input-group mb-3">
                                                            <select class="form-select form-select-lg me-1"  wire:model="multiMonthTo" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                                                @foreach(getMonthList() as $mid => $mname)
                                                                    <option value="{{$mid}}">{{$mname}}</option>
                                                                @endforeach
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-6 col-xxl-3">
                                                        <span class="title-form d-block w-100">Anno</span>
                                                        <div class="input-group mb-3">
                                                            <input type="number" class="form-control"  wire:model="multiYearTo"  {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                                        </div>
                                                    </div>
                                                    @if($this->dataId == 0 && !$isDuplicate)
                                                        <div class="col-lg-6">
                                                            <button type="button" class="btn--ui primary" wire:click.prevent="multiPeriodCreate({{$idx}})" style="margin-top:20px">
                                                                Crea multi periodo
                                                            </button>
                                                        </div>
                                                        <div class="col-lg-6">
                                                            <button type="button" class="btn--ui lightGrey" wire:click.prevent="multiPeriodCancel()" style="margin-top:20px">
                                                                Annulla multi periodo
                                                            </button>
                                                        </div>
                                                    @endif
                                                </div>


                                            @else
                                                @foreach($row["when"] as $xxx => $w)
                                                    <div class="col-md-4">
                                                        <span class="title-form d-block w-100">Mese</span>
                                                        <div class="input-group mb-3">
                                                            <select class="form-select form-select-lg me-1"  wire:model="rows.{{$idx}}.when.{{$xxx}}.month" onchange="setYear({{$idx}}, {{$xxx}})" {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                                                @foreach(getMonthList() as $mid => $mname)
                                                                    <option value="{{$mid}}">{{$mname}}</option>
                                                                @endforeach
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <span class="title-form d-block w-100">Anno</span>
                                                        <div class="input-group mb-3">
                                                            <input type="number" class="form-control"  wire:model="rows.{{$idx}}.when.{{$xxx}}.year"  {{$this->dataId > 0 && !$isDuplicate ? 'disabled' : ''}}>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                    <span class="title-form d-block w-100">Valore</span>
                                                        <span class="netprice_p total--wrapper_netprice"><b>{{$this->currencyToDouble($rows[$idx]["amount"]) > 0 ? formatPrice(($this->currencyToDouble($rows[$idx]["amount"]) + getVatValue($this->currencyToDouble($rows[$idx]["amount"]), $rows[$idx]["vat_id"])) / sizeof($rows[$idx]["when"])) : ""}}</b></span>
                                                    </div>
                                                    <div class="col-md-2"><br>
                                                        @if($this->dataId == 0)
                                                        <button type="button" class="btn--ui primary" wire:click.prevent="delPeriod({{$idx}}, {{$xxx}})" style="float:right">
                                                            -
                                                        </button>
                                                        @endif
                                                    </div>
                                                @endforeach
                                                @if($this->dataId == 0)
                                                <div class="d-flex justify-content-between mt-3">
                                                    <button type="button" class="btn--ui lightGrey order-2" wire:click.prevent="addPeriod({{$idx}})">
                                                        Aggiungi periodo
                                                    </button>

                                                    <button type="button" class="btn--ui_tertiary primary order-1" wire:click.prevent="multiPeriod()">
                                                        Imposta multi periodo
                                                    </button>
                                                </div>
                                                @endif
                                            @endif

                                        </div>
                                    </div>
                                </div>

                                <br><br>
                                @if($this->dataId == 0)
                                @if($idx > 0)
                                    <button type="button" class="btn--ui primary" wire:click.prevent="delRow({{$idx}})" style="float:right">
                                        Rimuovi causale
                                    </button>
                                    <br><br>
                                @endif
                                @endif
                                <hr size="1">

                            @endforeach

                            @if($this->dataId == 0)
                            <br>
                            <button type="button" class="btn--ui primary" wire:click.prevent="addRow()">
                                Aggiungi causale
                            </button>
                            @endif

                        @endif


                        <div class="accountingEntry--btn d-flex align-items-center justify-content-between mt-5">
                            @if($isDuplicate)
                                <button class="btn--ui lightGrey" wire:click="cancel()">annulla</button>
                            @else
                                <button class="btn--ui lightGrey" onclick="annulla()">annulla</button>
                            @endif
                            @if(!$deleted)
                                @if($canSave)
                                    @if($add)

                                        @if($commercial)

                                            @if($corrispettivo_fiscale)
                                                @if($corrispettivo_causal_id > 0)
                                                    <button class="btn--ui primary"  type="submit" wire:click.prevent="storeCorrispettivo()">inserisci corrispettivo fiscale</button>
                                                @else
                                                    Non hai configurato una causale per il corrispettivo fiscale
                                                @endif
                                            @else
                                                <button class="btn--ui primary"  type="submit" wire:click.prevent="store(false)" onclick='window.location.href = "#top";'>inserisci</button>
                                            @endif

                                        @else
                                            @if($this->member && !$commercial && !$this->member->isAdult() && $parent == '')
                                                <span style="color:red">Devi selezionare un genitore</span>
                                            @else

                                                    <button class="btn--ui primary sendInvoice d-flex ms-auto" wire:click.prevent="store(true)" onclick='window.location.href = "#top";'><i class="ico--ui sendingBtn"></i><span>inserisci {{!$commercial ? 'genera ricevuta' : ''}}</span></button>

                                            @endif

                                        @endif

                                    @endif
                                    @if($update && !$corrispettivo_fiscale)
                                        @if($this->member && !$commercial && !$this->member->isAdult() && $parent == '')
                                            <span style="color:red">Devi selezionare un genitore</span>
                                        @else

                                                <button class="btn--ui primary sendInvoice d-flex ms-auto" wire:click.prevent="update({{!$commercial}})"><i class="ico--ui sendingBtn"></i><span>inserisci {{!$commercial ? 'genera ricevuta' : ''}}</span></button>

                                        @endif
                                    @endif
                                @else
                                    <span style="color:red">Attenzione : non c'è credito sufficiente sul borsellino virtuale</span>
                                @endif
                            @endif

                        </div>
            </form>
            </div>
            @if(!$corrispettivo_fiscale)
            <div class="accountingEntry_resume card--ui" style="max-height:800px;width:35% !important;">
                <header style="height: 80px">
                    <div class="username d-flex align-items-start">
                        <i class="ico--ui accountingResume me-2"></i>
                        <div class="user--resume_name d-flex flex-column"><span class="primary">{{!$commercial ? 'Ricevuta' : 'Promemoria pagamento'}} {{$currentReceip ? $currentReceip->number . "/" . $currentReceip->year : ''}} {{$currentReceip != null ? ' del ' . date("d/m/Y", strtotime($currentReceip->created_at)) : ''}}</span></div></div>
                </header>

                <div class="resume--body d-flex justify-content-between flex-column">
                    <header>
                        @if($this->member)

                            <ul class="resume-item mb-4 p-0">

                                <li>
                                    <div style="background-color:#ffffff; padding:10px;">
                                        <b>{{$this->member->first_name}} {{$this->member->last_name}}</b> {!! !$this->member->isAdult() ? '<span style="color:red;font-weight:bold">&nbsp;MINORENNE</span>' : '' !!}<br>
                                        <span class="title-form w-100">Codice fiscale</span> : {{$this->member->fiscal_code}}<br>
                                        <span class="title-form w-100">Email</span> : {{$this->member->email}}<br>
                                        <span class="title-form w-100">Borsellino virtuale</span>
                                        <b>{{number_format($virtual, 2, ".", "")}} &euro;</b><br>
                                        @if(sizeof($this->member->certificates) > 0)
                                            @php
                                            $cert = $this->member->certificates[0]
                                            @endphp
                                            @if($cert->expire_date < date("Y-m-d"))
                                                <span class="title-form w-100">Certificato medico </span><span class="badge tessera-badge suspended">scaduto</span>
                                            @endif
                                        @endif
                                        @php
                                        $status = $this->member->getStatus()["status"];
                                        $class = $status > 0 ? ($status == 2 ? 'active' : 'suspended') : 'due';
                                        $text = $status > 0 ? ($status == 2 ? 'Tesserato' : 'Sospeso') : 'Non tesserato';
                                        @endphp
                                        <span class="tablesaw-cell-content"><span class="badge tessera-badge {{$class}}">{{$text}}</span></span>
                                    </div>
                                </li>

                                @if(!$this->member->isAdult())
                                    <li>
                                        <span class="evidence_name">
                                            <br>Seleziona un genitore
                                            <select class="form-control" wire:model="parent">
                                                <option value="">Seleziona un genitore
                                                @if($this->member->father_name != '')
                                                    <option value="{{$this->member->father_name}} (C.F. {{$this->member->father_fiscal_code}})">{{$this->member->father_name}} (C.F. {{$this->member->father_fiscal_code}})
                                                @endif
                                                @if($this->member->mother_name != '')
                                                    <option value="{{$this->member->mother_name}} (C.F. {{$this->member->mother_fiscal_code}})">{{$this->member->mother_name}} (C.F. {{$this->member->mother_fiscal_code}})
                                                @endif
                                            </select>
                                        </span>
                                    </li>
                                @endif
                            </ul>
                        @endif
                        <ul class="resume-item date p-0">
                            <li><strong>Data di Pagamento</strong></li>
                            <li>{{ date("d/m/Y", strtotime($date)) }}</li>
                        </ul>

                        @if(sizeof($rows) > 0)
                            <table width="100%">
                                <tr>
                                    <td><b>Causale</b></td>
                                    @if($commercial == 1)
                                        <td><b>Imponibile</b></td>
                                        <td><b>% Iva</b></td>
                                        <td><b>Iva</b></td>
                                    @endif
                                    <td style="float:right"><b>Totale</b></td>
                                </tr>
                                @foreach($rows as $row)
                                    <tr>
                                        <td>
                                            {{$this->getCausal($row["causal_id"])}}<br>
                                            {{$row["note"]}}
                                        </td>
                                        @php
                                        $vat_value = 0;
                                        @endphp
                                        @if($commercial == 1)
                                            <td>{{$row["amount"]}}</td>
                                            @php
                                            $vat_name = '';
                                            if ($row["vat_id"] > 0)
                                            {
                                                $v = \App\Models\Vat::findOrFail(intval($row["vat_id"]));
                                                $vat_name = $v->name;
                                                $vat_value = $this->currencyToDouble($row["amount"]) / 100 * $v->value;
                                            }
                                            @endphp
                                            <td>{{$vat_name}}</td>
                                            <td>{{$vat_value > 0 ? formatPrice($vat_value) : ''}}</td>
                                        @endif
                                        <td style="float:right">{{formatPrice($this->currencyToDouble($row["amount"]) + $vat_value)}}</td>
                                    </tr>
                                @endforeach
                            </table>

                        @endif

                    </header>

                    <footer>
                        <div class="total--wrapper">
                            <div class="total--wrapper_amount d-flex align-items-center justify-content-between w-100 mb-3">
                                <span class="amount_p"><strong>Importo</strong></span><span class="amount_data"><strong>{{$this->getPrice()}}</strong></span>
                            </div>
                            @if(false)
                                <div class="total--wrapper_amount d-flex align-items-center justify-content-between w-100 mb-3">
                                    <span class="amount_p"><strong>Iva</strong></span><span class="amount_data"><strong>{{$this->getVat()}}</strong></span>
                                </div>
                            @endif
                            @foreach($this->getVats() as $k => $v)
                                <div class="total--wrapper_amount d-flex align-items-center justify-content-between w-100 mb-3">
                                    <span class="amount_p"><strong>{{$k}}</strong></span><span class="amount_data"><strong>{{formatPrice($v)}}</strong></span>
                                </div>
                            @endforeach
                            <!--<div class="total--wrapper_tax d-flex align-items-center justify-content-between w-100 mb-2 pb-3">
                                <span class="taxt_p">Ritenuta d’acconto (20%):</span><span class="tax_data">€ 20,00</span>
                            </div>-->
                            <div class="total--wrapper_netprice d-flex align-items-center justify-content-between w-100">
                                <span class="netprice_p"><strong>Totale</strong></span><span class="netprice_data"><strong>{{$this->getTotal()}}</strong></span>
                            </div>
                        </div>

                        @if($update && !$isDuplicate && !$deleted)
                            @if($currentReceip)
                                @if($currentReceip->status == 99)
                                    {{-- <br><b style="float:right">Annullata</b> --}}
                                    @if($this->member && !$commercial && !$this->member->isAdult() && $parent == '')
                                        <span style="color:red">Devi selezionare un genitore</span>
                                    @else
                                        <button class="btn--ui primary sendInvoice mt-5 d-flex ms-auto" wire:click.prevent="rigenerate()"><i class="ico--ui sendingBtn"></i><span>rigenera ricevuta</span></button>
                                    @endif
                                @else
                                    <div class="mt-5 buttons--ricevuta d-flex align-items-center">
                                        <a target="_blank" class="btn--ui me-2 mb-2 mb-xxl-0" href="/receipt/{{$currentReceip->id}}"><i class="fa-regular fa-file-lines"></i><span>stampa ricevuta</span></a>
                                        <button class="btn--ui " wire:click.prevent="removeReceipt()"><i class="fa-regular fa-trash-can"></i><span>annulla ricevuta</span></button>
                                    </div>
                                @endif
                            @else
                                @if(!$corrispettivo_fiscale)
                                    @if($this->member && !$commercial && !$this->member->isAdult() && $parent == '')
                                        <span style="color:red">Devi selezionare un genitore</span>
                                    @else
                                        <button class="btn--ui primary sendInvoice mt-5 d-flex ms-auto" wire:click.prevent="update(true)"><i class="ico--ui sendingBtn"></i><span>salva {{!$commercial ? ' e genera ricevuta' : ''}}</span></button>
                                    @endif
                                @endif
                            @endif
                        @endif

                    </footer>
                </div>
            </div>
            @endif
        </section>

        <div  wire:ignore.self class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalLabel">Inserimento nuovo utente</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    @if($newMemberExists)
                    <div class="alert alert-warning" role="alert">
                        Un utente con lo stesso nome e cognome è già presente a database
                    </div>
                    @endif
                    <div class="row">
                        <div class="col-md-6">
                            <label for="newMemberFirstName" class="form-label">Nome</label>
                            <input class="form-control @error('newMemberFirstName') is-invalid @enderror" type="text" id="newMemberFirstName" placeholder="Nome" wire:model.lazy="newMemberFirstName">
                        </div>
                        <div class="col-md-6">
                            <label for="newMemberLastName" class="form-label">Cognome</label>
                            <input class="form-control @error('newMemberLastName') is-invalid @enderror" type="text" id="newMemberLastName" placeholder="Cognome" wire:model.lazy="newMemberLastName">
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-md-6">
                            <label for="newMemberEmail" class="form-label">Email</label>
                            <input class="form-control @error('newMemberEmail') is-invalid @enderror" type="text" id="newMemberEmail" placeholder="Email" wire:model="newMemberEmail">
                        </div>
                        <div class="col-md-6">
                            <label for="newMemberFiscalCode" class="form-label">Codice fiscale</label>
                            <input class="form-control @error('newMemberFiscalCode') is-invalid @enderror" type="text" id="newMemberFiscalCode" placeholder="Codice fiscale" maxlength="16" wire:model="newMemberFiscalCode">
                            @if($newMemberFiscalCodeExist)
                                <span style="color:red">Il codice fiscale inserito esiste</span>
                            @endif
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-md-6">
                            <input type="checkbox" id="newMemberToComplete" wire:model="newMemberToComplete">
                            <label for="newMemberToComplete" class="form-label">Tesserato</label>
                        </div>
                        <div class="col-md-6"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn--ui lightGrey" onclick="annulla()">annulla</a>
                    <button type="button" class="btn--ui btn-primary" wire:click.prevent="createMember()">Salva</button>
                </div>
                </div>
            </div>
        </div>

        <div wire:ignore.self class="modal fade success-modal" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModal" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header"></div>
                    <div class="modal-body pt-4 pb-4 text-center fw-bold">Ricevuta annullata con successo</div>
                </div>
            </div>
        </div>

    @endif
</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 {
        /* Important */
            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;
        }
        .page-link.active, .active > .page-link {
            background-color:#006099 !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;
        }
        /* .total.primary
        {
            font-size:38px !important;
        } */
        /* .total.primary.comp
        {
            font-size:32px !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')
    <script>

        function formatResult(node) {
            var output = node.text.split(/[,-]+/).pop();
            var $result = $('<span style="padding-left:' + (20 * (node.text.match(/-/g) || []).length) + 'px;">' + output + '</span>');
            return $result;
        };

        function matchStart(params, data) {
            params.term = params.term || '';
            if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
                return data;
            }
            return false;
        }
        @if($refreshAfter == 1)
            setTimeout(() => {
                // $('.causalClass').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
                $('.causalClass').select2({
                    matcher: function(params, data) {
                        return matchStart(params, data);
                    }
                });
                $('.memberClass').select2({
                    tags: false
                });
                $('.paymentClass').select2({
                    matcher: function(params, data) {
                        return matchStart(params, data);
                    }
                });
            }, 100);
            setTimeout(() => {
                var element = document.getElementById('causal_detail_0');
                element.dispatchEvent(new Event('input'));
            }, 1000);
        @endif
        window.livewire.on('refresh', () => {
            // $('.causalClass').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.memberClass').select2({
                tags: false
            });
            $('.paymentClass').select2({
                matcher: function(params, data) {
                    return matchStart(params, data);
                }
            });
        });

        $(document).ready(function(){

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

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

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

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

        });

        Livewire.on('load-select', () => {



            $('.causalClass').each(function(i, obj) {
                $(obj).select2({
                    //data: data,
                    /*formatSelection: function(item) {
                    return item.text
                    },*/
                    templateResult: formatResult
                });
                $(obj).on('change', function (e) {
                    var data = $(obj).select2("val");
                    var name = $(obj).select2().attr("name");
                    @this.set(name, data);
                });
            });

            $('.memberClass').select2({
                tags: false
            });
            $('.memberClass').on('change', function (e) {
                loadDiv();
                var data = $('.memberClass').select2("val");
                @this.set('member_id', data);
            });
            $('.paymentClass').select2({
                matcher: function(params, data) {
                    return matchStart(params, data);
                }
            });
            $('.paymentClass').on('change', function (e) {
                loadDiv();
                var data = $('.paymentClass').select2("val");
                @this.set('payment_method_id', data);
            });
            $('.filterCommercial').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterMember').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            /*$('.filterMember').on('change', function (e) {
                var data = $('.filterMember').select2("val");
                @this.set('filterMember', data);
                @this.search();
            });*/

            $('.filterPaymentMethod').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterPaymentMethod').on('change', function (e) {
                //var data = $('.filterPaymentMethod').select2("val");
                //@this.set('filterPaymentMethod', data);
            });
            $('.filterCausals').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterCausals').on('change', function (e) {
                //var data = $('.filterCausals').select2("val");
                //@this.set('filterCausals', data);
            });
            $('.filterDestinations').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterDestinations').on('change', function (e) {
                //var data = $('.filterDestinations').select2("val");
                //@this.set('filterDestinations', data);
            });



        });

        Livewire.on('hide-search', () => {
            //pcsh2();
        });

        $('.filterPaymentMethod').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterPaymentMethod').on('change', function (e) {
            //var data = $('.filterPaymentMethod').select2("val");
            //@this.set('filterPaymentMethod', data);
        });
        $('.filterCausals').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterCausals').on('change', function (e) {
            //var data = $('.filterCausals').select2("val");
            //@this.set('filterCausals', data);
        });
        $('.filterDestinations').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterDestinations').on('change', function (e) {
            //var data = $('.filterDestinations').select2("val");
            //@this.set('filterDestinations', data);
        });

        window.livewire.on('saved', () => {
            $('#userModal').modal('hide');
        });
        window.livewire.on('reloadMembers', () => {
            $('.memberClass').select2("destroy");
            $('.memberClass').select2({
                tags: false
            });
        });

        $('.filterCommercial').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterMember').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        /*$('.filterMember').on('change', function (e) {
            var data = $('.filterMember').select2("val");
            @this.set('filterMember', data);
            @this.search();
        });*/
        //$('.filterPaymentMethod').select2({"language": {"noResults": function(){return "Nessun risultato";}}});


        function onlyNumberAmount(input) {
            let v = input.value.replace(/\D+/g, '');
            if (v.length > 14) v = v.slice(0, 14);
            input.value = "€ " + v.replace(/(\d)(\d\d)$/, "$1,$2").replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:,|$))/g, '$1.');
        }

        function setChangedAmount() {
            loadDiv();
            @if(!$isDuplicate)
                @this.setAmount();
            @endif
        }

    </script>

    <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>
    <script>

        $(document).ready(function() {

            // Carico i dati dal local storage
            /*var filterCommercial = localStorage.getItem("filterCommercial");
            if (filterCommercial)
            {
                //$('input[name="filterCommercial"]').val(filterCommercial);
                $('input[name="filterCommercial"]').filter('[value="' + filterCommercial + '"]').attr('checked', true);
                setFilterCommercial(filterCommercial);
            }
            var filterMember = localStorage.getItem("filterMember");
            if (filterMember)
            {
                $('.filterMember').val(filterMember);
                $('.filterMember').trigger('change');
            }
            var filterPaymentMethod = localStorage.getItem("filterPaymentMethod");
            if (filterPaymentMethod)
            {
                $('.filterPaymentMethod').val(filterPaymentMethod);
                $('.filterPaymentMethod').trigger('change');
            }
            var filterCausals = localStorage.getItem("filterCausals");
            if (filterCausals)
            {
                $('.filterCausals').val(filterCausals);
                $('.filterCausals').trigger('change');
            }
            var filterDestinations = localStorage.getItem("filterDestinations");
            if (filterDestinations)
            {
                $('.filterDestinations').val(filterDestinations);
                $('.filterDestinations').trigger('change');
            }
            var filterFrom = localStorage.getItem("filterFrom");
            if (filterFrom)
            {
                $('.filterFrom').val(filterFrom);
            }
            var filterTo = localStorage.getItem("filterTo");
            if (filterTo)
            {
                $('.filterTo').val(filterTo);
            }
            */

            loadDataTable();

            setTimeout(() => {
                var h = $("#card--dashboard").height();
                // $('#loadingDiv').height(h);
            }, 500);

        } );

        @if(isset($_GET["showFilters"]))
            var filterCommercial = localStorage.getItem("filterCommercialRecordIn");
            if (filterCommercial && filterCommercial != "null" && filterCommercial != "undefined")
            {
                $('.filterCommercial').val(filterCommercial);
                $('.filterCommercial').trigger('change');
            }
            var filterMember = localStorage.getItem("filterMemberRecordIn");
            if (filterMember && filterMember != "null" && filterMember != "undefined")
            {
                $('.filterMember').val(filterMember);
                $('.filterMember').trigger('change');
            }
            var filterPaymentMethod = localStorage.getItem("filterPaymentMethodRecordIn");
            console.log(filterPaymentMethod);
            if (filterPaymentMethod && filterPaymentMethod != "null" && filterPaymentMethod != "undefined")
            {
                $('.filterPaymentMethod').val(filterPaymentMethod);
                $('.filterPaymentMethod').trigger('change');
            }
            var filterCausals = localStorage.getItem("filterCausalsRecordIn");
            if (filterCausals && filterCausals != "null" && filterCausals != "undefined")
            {
                $('.filterCausals').val(filterCausals);
                $('.filterCausals').trigger('change');
            }
            var filterDestinations = localStorage.getItem("filterDestinationsRecordIn");
            if (filterDestinations && filterDestinations != "null" && filterDestinations != "undefined")
            {
                $('.filterDestinations').val(filterDestinations);
                $('.filterDestinations').trigger('change');
            }
            var filterFrom = localStorage.getItem("filterFromRecordIn");
            if (filterFrom && filterFrom != "null" && filterFrom != "undefined")
            {
                $('.filterFrom').val(filterFrom);
            }
            var filterTo = localStorage.getItem("filterToRecordIn");
            if (filterTo && filterTo != "null" && filterTo != "undefined")
            {
                $('.filterTo').val(filterTo);
            }
        @endif

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

            $(document).on("select2:open",".filterCausals",function() {
            //$('.filterCausals').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);
            });
            $(document).on("select2:open",".filterDestinations",function() {
            //$('.filterDestinations').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 editData(id)
        {
            @this.edit(id);
        }

        function duplicateData(id)
        {
            @this.duplicate(id);
        }

        function deleteData(id)
        {
            if (confirm('Sei sicuro?'))
                @this.delete(id);
        }

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

        });

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

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

        function reset()
        {
            $(".todayButton").addClass("lightGrey");
            $(".yesterdayButton").addClass("lightGrey");
            $('.filterCommercial').val('').trigger('change');
            $('.filterMember').val('');
            $('.filterMember').trigger('change');
            $('.filterPaymentMethod').val('');
            $('.filterPaymentMethod').trigger('change');
            $('.filterCausals').val('');
            $('.filterCausals').trigger('change');
            $('.filterDestinations').val('');
            $('.filterDestinations').trigger('change');
            $('.filterFrom').val('');
            $('.filterTo').val('');
            //localStorage.clear();
            loadDataTable();
        }


        function loadDataTable(){

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

            // filterCommercial = $('input[name="filterCommercial"]:checked').val();
            var filterCommercial = $('.filterCommercial').val();
            var filterMember = $('.filterMember').val();
            var filterPaymentMethod = $('.filterPaymentMethod').val();
            var filterCausals = $('.filterCausals').val();
            var filterDestinations = $('.filterDestinations').val();
            var filterFrom = $('.filterFrom').val();
            var filterTo = $('.filterTo').val();

                // Salvo i filtri della ricerca
            localStorage.setItem("filterCommercialRecordIn", filterCommercial);
            localStorage.setItem("filterMemberRecordIn", filterMember);
            localStorage.setItem("filterPaymentMethodRecordIn", filterPaymentMethod);
            localStorage.setItem("filterCausalsRecordIn", filterCausals);
            localStorage.setItem("filterDestinationsRecordIn", filterDestinations);
            localStorage.setItem("filterFromRecordIn", filterFrom);
            localStorage.setItem("filterToRecordIn", filterTo);

            var totalString = "";

            $('#tablesaw-350').DataTable({
                //searching: false,
                /*fixedHeader: {
                    header: true,
                    footer: true
                },
                scrollCollapse: true,
                scrollX: true,
                scrollY: 800,*/
                serverSide: true,
                ajax: {
                    url : '/get_record_in?filterCommercial=' + filterCommercial + "&filterMember=" + filterMember + "&filterPaymentMethod=" + filterPaymentMethod + "&filterDestinations=" + filterDestinations + "&filterCausals=" + filterCausals + "&filterFrom=" + filterFrom + "&filterTo=" + filterTo,
                    dataSrc: function (json){
                        if(json.totals){
                            
                            $(".totalDiv").html('Totale&nbsp;:&nbsp;<b>' + json.totals + '</b>');
                        }
                        else
                        {
                            $(".totalDiv").html('');
                        }
                        @if(Auth::user()->level != 0)
                            $(".totalDiv").html('');
                        @endif
                        return json.data;
                    }
                },
                columns: [
                    //{ data: 'id' },
                    {
                        data: "date",
                        render: function (data, type){
                            if (data == "")
                                return " ";
                            if (type == "sort"){
                                return new Date(data).getTime();
                            }
                            // Split class and text
                            const j = data.split(" ");
                            const d = j[0].split("-");
                            var ret = d[2] + "/" + d[1] + "/" + d[0];
                            return ret;
                        },class:"numericCol"
                    },
                    { data: 'total', className: "numericCol" },
                    { data: 'last_name' },
                    { data: 'first_name' },
                    { data: 'commercial' },
                    { data: 'causals', "orderable": false, },
                    { data: 'payment', "orderable": false, },
                    { data: 'destination', "orderable": false, },
                    //{ data: 'payment_date', "orderable": false, },
                    { data: 'status', "orderable": false, },
                    {
                        data: "action",
                        render: function (data){
                            if (data == "")
                                return "";
                            const j = data.split("|");
                            //$(".totalDiv").html('Totale&nbsp;:&nbsp;<b>' + j[1] + '</b>');
                            //$(".total").html('Totale&nbsp;:&nbsp;<b>' + j[1] + '</b>');
                            //totalString = j[1];
                            var ret = '';
                            if (j[2] != 'x')
                            {
                                ret = '<button type="button" class="btn" onclick="editData(' + j[0] + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Modifica"><i class="fa-regular fa-pen-to-square"></i></button>&nbsp;';
                                ret += '<button type="button" class="btn" onclick="deleteData(' + j[0] + ')"  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>';
                                ret += '<button type="button" class="btn btn-outline-default btn-sm" onclick="duplicateData(' + j[0] + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Duplica"><i class="fa-regular fa-copy"></i></button>';
                            }
                            else
                            {
                                ret = '<button type="button" class="btn" onclick="editData(' + j[0] + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Visualizza"><i class="fa-regular fa-file"></i></button>&nbsp;';
                            }
                            return ret;
                        }
                    },
                ],
                rowCallback: function( row, data, index ) {

                    if (data["last_name"] == '') {
                        $(row).hide();
                        $(row).remove();
                    }
                },
                fixedHeader: false,
                order: [[0, 'desc']],
                thead: {
                'th': {'background-color': 'blue'}
                },
                layout: {
                    topStart : null,
                    topEnd : null,
                    top1A: {
                        buttons: [
                            {
                                extend: 'collection',
                                text: 'ESPORTA',
                                buttons: [
                                    {
                                    extend: 'excelHtml5',"action":newexportaction,
                                        title: 'Entrate',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'pdfHtml5',"action":newexportaction,
                                        title: 'Entrate',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'print',"action":newexportaction,
                                        text: 'Stampa',
                                        title: 'Entrate',
                                        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
                        }
                    }
                },
                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 href="#" 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);
                }
            });
            $('#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")
            });
        } );

        var isEdit = false;

        Livewire.on('showReceipt', (id) =>
        {
            window.open("{{env('APP_URL', '')}}/receipt/" + id, '_blank').focus();
        });

        Livewire.on('setEdit', (x) =>
        {
            isEdit = x;
        });

        Livewire.on('reload', (x) =>
        {
            location.reload();
        });

        function annulla()
        {
            window.onbeforeunload = null;
            document.location.href = '/in';
        }


        window.onbeforeunload = function(){
            if (isEdit)
                return 'Cambiando pagina le eventuali modifiche andranno perse';

        };

        function setCommercialType(t)
        {
            @this.set('commercial', t);
            Livewire.emit('refreshMembers');
        }

        function setYear(idx, xxx)
        {
            @this.setYear(idx, xxx);
        }

        function loadDiv()
        {
            $("select").prop('disabled',true);
            $("select[name='member_id']").prop('disabled',true);
            $("select[name='payment_method_id']").prop('disabled',true);
            setTimeout(() => {
                $("select").prop('disabled',false);
                $("select[name='payment_method_id']").prop('disabled',false);
                $("select[name='member_id']").prop('disabled',false);
            }, 1000);
        }

    </script>

@endpush

@push('scripts')
<script>
Livewire.on('success', () => {
    showSuccessAlert();
});

let success_alert_timeout;
function showSuccessAlert() {
    $('#successModal').modal("show");
    clearTimeout(success_alert_timeout);
    success_alert_timeout = setTimeout(() => {
        $('#successModal').modal("hide");
    }, 3000);
}
</script>
@endpush
