@php
    $last_date = explode(" ", $this->calendar->from)[0];
@endphp

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

    <a class="btn--ui lightGrey" href="/calendar?last_date={{$last_date}}"><i class="fa-solid fa-arrow-left"></i></a><br><br>

    <div class="compare--chart_wrapper d-none"></div>

    <div class="row">
        <div class="col-sm-12">
            <div class="row">
                <div class="col-auto">
                    <h3 class="text-primary">{{$calendar->course ? $calendar->course->name : $calendar->name}}</h3>
                </div>
                <div class="col"></div>
                <div class="col-auto text-end">
                    <h4>{!!$this->getDateX()!!}<br>ora inizio {{date("H:i", strtotime($calendar->from))}}</h4>
                </div>
            </div>
        </div>

        {{-- @if($manual)

        <div class="col-md-6">
            <label for="court_id" class="form-label">Motivazione</label>
            <select class="form-select form-select-lg me-1 " id="motivation_manual_id">
                <option value="">
                    @foreach($motivations_add as $m)
                <option value="{{$m->id}}" {{$motivation_manual_id==$m->id ? 'selected' : ''}}>{{$m->name}}</option>
                @endforeach
            </select>
        </div>

        @else
        <div class="col-md-6">
            <label for="court_id" class="form-label">Campo</label>
            <select class="form-select form-select-lg me-1 " wire:model="court_id">
                <option value="">
                    @foreach($courts as $c)
                <option value="{{$c["id"]}}">{{$c["name"]}}</option>
                @endforeach
            </select>
        </div>
        <div class="col">
            <label for="instructor_id" class="form-label">Istruttore</label>
            <select class="form-select form-select-lg me-1 " wire:model="instructor_id">
                <option value="">
                    @foreach($instructors as $i)
                <option value="{{$i["id"]}}">{{$i["name"]}}</option>
                @endforeach
            </select>
        </div>
        <div class="col-auto mt-2">
            <br>
            <button type="button" class="btn--ui primary" data-bs-toggle="modal" data-bs-target="#instructorModal" style="width:50px">&nbsp;<i class="fa-solid fa-plus"></i></button>
        </div>

        <div class="col-md-12 mt-3">
            <textarea class="form-control" id="note" placeholder="Note" wire:model="note"></textarea>
        </div>
        @endif --}}

    </div>

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

        <div class="row">
            <div class="col-md-8 col-sm-6"></div>
            <div class="col-md-4 col-sm-6 mb-3">
                <input type="text" class="form-control" placeholder="Cerca utente" wire:model="filter">
            </div>
        </div>
    </div>

    <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
        <thead>
            <tr>
                <th scope="col" class="annulla-lezione" style="display: none;">Annullamento</th>
                <th scope="col">#</th>
                <th scope="col">Cognome</th>
                <th scope="col">Nome</th>
                <th scope="col">Certificato</th>
                <th scope="col">Campo</th>
                <th scope="col">Istruttore</th>
                <th scope="col">Presenza</th>
                <th scope="col">Motivazione</th>
                <th scope="col">Note</th>
            </tr>
        </thead>
        <tbody id="checkall-target">
            @php
                $totalPresences = 0;
            @endphp
            @foreach($records as $idx => $record)
            <tr>
                <td class="annulla-lezione" style="display: none;">
                    @if ($record["status"] != 99)
                    <input name="annulla_lezione" class="member chkM" type="checkbox" value="{{$record["id"]}}">
                    @endif
                </td>
                <td>{{$idx + 1}}</td>
                <td>{{$record["last_name"]}}</td>
                <td>{{$record["first_name"]}}</td>
                <td>
                    <span class="tablesaw-cell-content d-flex align-items-center">
                        @php
                        list($status, $date) = explode("|", $record["certificate"]);
                        @endphp
                        @if($status == 0)
                        <i class="ico--ui check suspended me-2"></i>Scaduto
                        @endif
                        @if($status == 1)
                        <i class="ico--ui check due me-2"></i>In scadenza
                        @endif
                        @if($status == 2)
                        <i class="ico--ui check active me-2"></i> Scadenza
                        @endif
                        @if(is_null($status) || $status == '')
                        <i class="ico--ui check due me-2"></i> Sospeso
                        @endif
                        {{$date}}
                    </span>
                </td>
                <td>{{$record["court"]}}</td>
                <td>{{$record["instructor"]}}{{$record["additional_instructor"] ? ", ".$record["additional_instructor"] : ""}}</td>
                <td>
                    @if ($record["status"] != 99)
                        @if ($record["presence"])
                            @if ($record["my_presence"])
                            @if($manual)
                                    <a onclick="removeSingle({{$record['id']}})"><i class="fas fa-trash"></i></a>
                                @else
                                    <input name="presence" class="member chkM" type="checkbox" value="{{$record["id"]}}" {{$record["presence"] ? 'checked' : '' }}>
                                    @php
                                    if ($record['presence']) {
                                        $totalPresences ++;
                                    }
                                    @endphp
                                @endif
                            @else
                                <span style="color:#0C6197;font-size:25px;">&#10003;</span>
                                @php
                                    $totalPresences++;
                                @endphp
                            @endif
                        @else
                            <input name="presence" class="member chkM" type="checkbox" value="{{$record["id"]}}" {{$record["presence"] ? 'checked' : '' }}>
                            @php
                            if ($record['presence']) {
                                $totalPresences ++;
                            }
                            @endphp
                        @endif
                    @else
                        Annullata &nbsp;&nbsp;-&nbsp;&nbsp; <a href="#" wire:click="revert({{$record["id"]}})" style="text-decoration: underline;color: #0c6197;"><small><i class="fa-solid fa-arrow-left-rotate"></i></small> Ripristina</a>
                    @endif
                </td>
                <td>
                    {{$record["motivation"]}}
                </td>
                <td>{{$record["notes"]}}</td>
            </tr>
            @endforeach

            <tr>
                <td colspan="6"><span class="fw-bold text-uppercase">Totale presenti</span></td>
                <td><span class="fw-bold">{{$totalPresences}}</span></td>
                <td colspan="2"></td>
            </tr>
        </tbody>
    </table>


    @if($calendar->status == 0)
    <div class="row">
        <div class="col">
            <button type="button" class="btn--ui primary btSave btAdd" data-bs-toggle="modal" data-bs-target="#userModal" onclick="addUser()">Aggiungi utente</button>
        </div>
    </div>
    @endif
    <br>
    <br>
    <div class="row">
        @if($calendar->status == 0)
        <div class="col">
            {{-- @if(!$manual) --}}
            <div class="col-lg-4 col-md-7 col-sm-12 showDelete" style="display:none">
                <label for="newMotivation" class="form-label">Motivazione</label>
                <select class="form-select form-select-lg me-1 " id="motivation_id">
                    <option value="">
                        @foreach($motivations as $m)
                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                    @endforeach
                </select>
            </div>
            <button type="button" class="btn--ui lightGrey btSave" onclick="showHideDelete()">Annulla lezione per selezionati</button>
            {{-- <button type="button" class="btn--ui btSave" onclick="saveAndStay()">Salva presenze</button> --}}

            {{-- @endif --}}
        </div>
        {{-- @if(!$manual) --}}
        <div class="col-auto mt-2 text-end">
            <a href="/calendar?last_date={{$last_date}}" class="btn--ui lightGrey btSave">Chiudi</a>
            {{-- <button type="button" class="btn--ui btSave" onclick="saveAndQuit()">Salva e chiudi</button> --}}
            @if(!$manual)
            <button type="button" class="btn--ui btSave" onclick="saveAndStay()">Salva presenze</button>
            @endif
            @if($manual)
            <button type="button" class="btn--ui btSave" onclick="saveManualCalendar()">Salva presenze</button>
            @endif
        </div>
        <div class="col-xs-12 mt-2">
            <div class="showDelete" style="float:left;display:none;">
                <button type="button" class="btn--ui lightGrey btSaveDelete" onclick="hideShowDelete()">Indietro</button>
                <button type="button" class="btn--ui btSaveDelete" onclick="cancel()">Conferma</button>
            </div>
        </div>
        {{-- @endif --}}
        @endif
    </div>

    <div class="row mt-3">
        @if($calendar->status == 0)
        {{-- @if(!$manual) --}}
        <div class="col-md-6">
        </div>
        {{-- @endif --}}
        @else
        LEZIONE ANNULLATA ({{$calendar->motivation ? $calendar->motivation->name : ''}})
        @endif
    </div>

    <div wire:ignore.self class="modal modal-lg 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 text-primary" id="userModalLabel">Aggiungi persone al corso</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <h3 class="text-primary"><input type="radio" name="chkType" value="1" checked onchange="change(1)"> Utente già registrato</h3>
                    @if ($insertUser == 'exist')
                    <div class="existUser">
                        <div class="row mt-2 ">
                            <div class="col-md-6" wire:ignore>
                                {{-- <label for="member_id" class="form-label">Aggiungere una o più persone</label> --}}
                                <label for="member_id" class="form-label">Selezionare l'utente</label>
                                <select name="member_id" id="member_id" class="form-select memberClass" aria-label="Seleziona una persona" {{-- multiple --}}>
                                    <option value="">--Seleziona--</option>
                                    @foreach($members as $member)
                                    <option value="{{$member->id}}">{{$member->last_name}} {{$member->first_name}} ({{$member->fiscal_code}})</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="newMotivation" class="form-label">Motivazione</label>
                                <select class="form-select form-select-lg me-1 @error('newMemberMotivationId') is-invalid @enderror" id="newMemberMotivationId">
                                    <option value=""></option>
                                    @foreach($motivations_add as $m)
                                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-12 mt-4">
                                <h6 class="mb-0">Seleziona il corso a cui l’utente è associato e per il quale va registrata la presenza</h6>
                            </div>
                            <div class="col-md-6">
                                <label for="motivation_course_name" class="form-label">Corso</label>
                                <select class="form-select form-select-lg me-1 @error('motivation_course_id') is-invalid @enderror" id="motivation_course_name" wire:model="motivation_course_name">
                                    <option value=""></option>
                                    @foreach($course_names as $m)
                                        <option value="{{$m}}">{{$m}}</option>
                                    @endforeach
                                </select>
                                @error('motivation_course_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            @if ($motivation_course_name)
                                <div class="col-md-6">
                                    <label for="motivation_course_level" class="form-label">Livello</label>
                                    <select class="form-select form-select-lg me-1 @error('motivation_course_level') is-invalid @enderror" id="motivation_course_level" wire:model="motivation_course_level">
                                        <option value="">
                                            @foreach($course_levels as $m)
                                            <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                            @endforeach
                                        </select>
                                </div>
                                @if ($motivation_course_level)
                                    <div class="col-md-6">
                                        <label for="motivation_course_type" class="form-label">Tipologia</label>
                                        <select class="form-select form-select-lg me-1 @error('motivation_course_type') is-invalid @enderror" id="motivation_course_type" wire:model="motivation_course_type">
                                            <option value="">
                                            @foreach($course_types as $m)
                                                <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    @if ($motivation_course_type)
                                        <div class="col-md-6">
                                            <label for="motivation_course_frequency" class="form-label">Frequenza</label>
                                            <select class="form-select form-select-lg me-1 @error('motivation_course_frequency') is-invalid @enderror" id="motivation_course_frequency" wire:model="motivation_course_frequency">
                                                <option value="">
                                                @foreach($course_frequencies as $m)
                                                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    @endif
                                @endif
                            @endif
                        </div>
                    </div>
                    @endif
                    <br>
                    <hr>
                    <br>
                    <h3 class="text-primary"><input type="radio" name="chkType" value="2" onchange="change(2)"> Inserimento nuovo utente</h3>
                    <br>
                    @if ($insertUser == 'new')
                    <div class="newUser">
                        @if($newMemberFiscalCodeExist)
                        <span style="color:red">Attenzione, utente esistente</span>
                        @endif
                        @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.lazy="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.lazy="newMemberFiscalCode">
                            </div>
                        </div>
                        <div class="row mt-2 ">
                            <div class="col-md-6 d-flex gap-1 pt-3">
                                <input type="checkbox" id="newMemberToComplete" wire:model="newMemberToComplete">
                                <label for="newMemberToComplete" class="form-label">Tesserato</label>
                            </div>
                            <div class="col-md-6">
                                <label for="newMotivation" class="form-label">Motivazione</label>
                                <select class="form-select form-select-lg me-1 @error('newMemberMotivationId') is-invalid @enderror" id="newMemberMotivationIdX">
                                    <option value="">
                                        @foreach($motivations_add as $m)
                                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-12 mt-4">
                                <h6 class="mb-0">Seleziona il corso a cui l’utente è associato e per il quale va registrata la presenza</h6>
                            </div>
                            <div class="col-md-6">
                                <label for="motivation_course_name" class="form-label">Corso</label>
                                <select class="form-select form-select-lg me-1 @error('motivation_course_name') is-invalid @enderror" id="motivation_course_name" wire:model="motivation_course_name">
                                    <option value="">
                                    @foreach($course_names as $m)
                                        <option value="{{$m}}">{{$m}}</option>
                                    @endforeach
                                </select>
                            </div>
                            @if ($motivation_course_name)
                                <div class="col-md-6">
                                    <label for="motivation_course_level" class="form-label">Livello</label>
                                    <select class="form-select form-select-lg me-1 @error('motivation_course_level') is-invalid @enderror" id="motivation_course_level" wire:model="motivation_course_level">
                                        <option value="">
                                            @foreach($course_levels as $m)
                                            <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                            @endforeach
                                        </select>
                                </div>
                                @if ($motivation_course_level)
                                    <div class="col-md-6">
                                        <label for="motivation_course_type" class="form-label">Tipologia</label>
                                        <select class="form-select form-select-lg me-1 @error('motivation_course_type') is-invalid @enderror" id="motivation_course_type" wire:model="motivation_course_type">
                                            <option value="">
                                            @foreach($course_types as $m)
                                                <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    @if ($motivation_course_type)
                                        <div class="col-md-6">
                                            <label for="motivation_course_frequency" class="form-label">Frequenza</label>
                                            <select class="form-select form-select-lg me-1 @error('motivation_course_frequency') is-invalid @enderror" id="motivation_course_frequency" wire:model="motivation_course_frequency">
                                                <option value="">
                                                @foreach($course_frequencies as $m)
                                                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    @endif
                                @endif
                            @endif
                        </div>
                    </div>
                    @endif
                </div>
                <div class="modal-footer">
                    <button class="btn--ui lightGrey" onclick="annulla()">annulla</a>
                    <button type="button" class="btn--ui btn-primary" onclick="createMember()">Salva</button>
                </div>
            </div>
        </div>
    </div>

    <div wire:ignore.self class="modal fade" id="instructorModal" tabindex="-1" aria-labelledby="instructorModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-primary" id="instructorModalLabel">Inserimento nuovo istruttore</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <label for="userName" class="form-label">Nome</label>
                            <input class="form-control @error('userName') is-invalid @enderror" type="text" id="userName" placeholder="Nome" wire:model="userName">
                        </div>
                        <div class="col-md-6">
                            <label for="userEmail" class="form-label">Email</label>
                            <input class="form-control @error('userEmail') is-invalid @enderror" type="text" id="userEmail" placeholder="Email" wire:model="userEmail">
                        </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="createInstructor()">Salva</button>
                </div>
            </div>
        </div>
    </div>

    <div wire:ignore.self class="modal fade saved-modal" id="editPresencesModal" tabindex="-1" role="dialog" aria-labelledby="editPresencesModal" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-primary" id="instructorModalLabel">Modifica presenza</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <label for="save_court_id" class="form-label">Campo</label>
                            <select id="save_court_id" class="form-select form-select-lg me-1">
                                <option value="0">
                                    @foreach($courts as $c)
                                <option value="{{$c["id"]}}">{{$c["name"]}}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="col">
                            <label for="save_instructor_id" class="form-label">Istruttore aggiuntivo</label>
                            <select id="save_instructor_id" class="form-select form-select-lg me-1">
                                <option value="0">
                                    @foreach($instructors as $i)
                                <option value="{{$i["id"]}}" {{\Auth::user()->id == $i["id"] ? "disabled" : ""}}>{{$i["name"]}}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-auto mt-2">
                            <br>
                            <button type="button" class="btn--ui primary" data-bs-toggle="modal" data-bs-target="#instructorModal" style="width:50px">&nbsp;<i class="fa-solid fa-plus"></i></button>
                        </div>

                        <div class="col-md-12">
                            <label for="save_notes" class="form-label">Note</label>
                            <textarea class="form-control" id="save_notes"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn--ui lightGrey" onclick="annulla()">annulla</a>
                        <button type="button" class="btn--ui btn-primary" onclick="save()">Salva</button>
                </div>
            </div>
        </div>
    </div>

    <div wire:ignore.self class="modal fade saved-modal" id="savedModal" tabindex="-1" role="dialog" aria-labelledby="savedModal" 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">Presenze salvate con successo</div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    table.tableHead thead {
        /* 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>
    var type = 1;

        var showAlert = false;
        var isSaving = false;

        $(document).ready(function() {
            
            setTimeout(() => {
                $('.memberClass').select2({
                    tags: false,
                    dropdownParent: $('.memberClass').parent(),
                });
                $('.memberClass').on('change', function (e) {
                    var id = $('.memberClass').select2("val");
                    @this.add_member_id = id;
                });
            }, 100);

            $(".btAdd").click(function(){
                showAlert = true;
            });

            $(".form-select").change(function(){
                showAlert = true;
            });

            $(".chkM").click(function(){
                showAlert = true;
            });

        } );

        Livewire.on('reload', () => {
            setTimeout(() => {
                $('.memberClass').select2({
                    tags: false,
                    dropdownParent: $('.memberClass').parent(),
                });
                $('.memberClass').on('change', function (e) {
                    var id = $('.memberClass').select2("val");
                    @this.add_member_id = id;
                });
            }, 100);
            $(".showDelete").hide();
            $(".btSave").show();
        });

        window.livewire.on('saved', () => {
            $('#userModal').modal('hide');
            $('#deleteModal').modal('hide');
            $('#instructorModal').modal('hide');
            $('#editPresencesModal').modal('hide');
        });

        window.livewire.on('deleteSaved', () => {
            $('#deleteModal').modal('hide');
        });

        window.livewire.on('setSaving', () => {
            isSaving = true;
            showSavedAlert();
        });

        let saved_alert_timeout;
        function showSavedAlert() {
            $('#savedModal').modal("show");
            clearTimeout(saved_alert_timeout);
            saved_alert_timeout = setTimeout(() => {
                $('#savedModal').modal("hide");
            }, 3000);
        }

        let stay = false;
        let manual = false;
        function saveAndQuit()
        {
            stay = false;

            $('#editPresencesModal').modal("show");
        }

        function saveAndStay()
        {
            stay = true;

            $('#editPresencesModal').modal("show");
        }

        function saveManualCalendar()
        {
            manual = true;

            $('#editPresencesModal').modal("show");
        }

        function save()
        {   
            let presence_ids = [];
            $('input[name="presence"][type="checkbox"]').each(function () {
                if ($(this).is(":checked")) 
                {
                    var val = $(this).val();
                    presence_ids.push(val);
                }
            });

            // @if($manual)
            //     var motivation_manual_id = $("#motivation_manual_id").val();
            //     @this.set('motivation_manual_id', motivation_manual_id);
            // @endif

            
            var save_court_id = $("#save_court_id").val();
            @this.set('save_court_id', save_court_id);
            var save_instructor_id = $("#save_instructor_id").val();
            @this.set('save_instructor_id', save_instructor_id);
            var save_notes = $("#save_notes").val();
            @this.set('save_notes', save_notes);

            if (manual == true) {
                @this.saveManualCalendar();
            } else {
                if (stay == true) {
                    @this.saveAndStay(presence_ids);
                } else {
                    @this.save(presence_ids);
                }
            }
            
            $('#editPresencesModal').modal("hide");
        }

        function cancel()
        {
            var ids = [];
            $('input[name="annulla_lezione"][type="checkbox"]').each(function () {
                if ($(this).is(":checked")) 
                {
                    var val = $(this).val();
                    ids.push(val);
                }
            });
            var motivation_id = $("#motivation_id").val();
            @this.cancel(ids, motivation_id);
        }

        function createMember()
        {
            var ids = [];
            /*$('input[type=checkbox]').each(function () {
                if ($(this).is(":checked")) 
                {
                    var val = $(this).val();
                    ids.push(val);
                }
            });*/

            if (type == 1)
            {
                var data = $('.memberClass').select2("val");
                @this.addMember(data);
                @this.set('newMemberMotivationId', $("#newMemberMotivationId").val());
            }
            else
            {
                @this.set('newMemberMotivationId', $("#newMemberMotivationIdX").val());
                // @this.set('newMemberFirstName', $("#newMemberFirstName").val());
                // @this.set('newMemberLastName', $("#newMemberLastName").val());
                // @this.set('newMemberEmail', $("#newMemberEmail").val());
                // @this.set('newMemberFiscalCode', $("#newMemberFiscalCode").val());
            }
            
            
            @this.createMember();
        }

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

        function annulla()
        {
            $('#userModal').modal('hide');
            $('#deleteModal').modal('hide');
            $('#instructorModal').modal('hide');
            $('#editPresencesModal').modal('hide');
        }

        function togglePresenceCheckboxDisabled(disabled = false) {
            let presence_checkboxes = document.querySelectorAll("input[name='presence'][type='checkbox']");
            presence_checkboxes.forEach((presence_checkbox) => {
                presence_checkbox.disabled = disabled;
            });
        }

        function showHideDelete()
        {
            togglePresenceCheckboxDisabled(true);
            $(".annulla-lezione").show();
            $(".showDelete").show();
            $(".btSave").hide();
        }
        
        function hideShowDelete()
        {
            togglePresenceCheckboxDisabled(false);
            $(".annulla-lezione").hide();
            $(".showDelete").hide();
            $(".btSave").show();
        }

        window.onbeforeunload = function(){
            
            if (showAlert && !isSaving)
                return 'Sei sicuro';

        };

        function addUser()
        {
            $("#newMemberMotivationId").val('');
            $("#newMemberMotivationIdX").val('');
            $("#newMemberFirstName").val('');
            $("#newMemberLastName").val('');
            $("#newMemberEmail").val('');
            $("#newMemberFiscalCode").val('');   
            $(".existUser").show();         
            $(".newUser").hide();
            let radioOption = jQuery("input:radio[value=1]");
            radioOption.prop("checked", true);
        }

        function change(val) {
            if (val == 1) {
                @this.insertUser = 'exist';
                $(".existUser").css("display", "block");
                $(".newUser").css("display", "none");
            } else if (val == 2) {
                @this.insertUser = 'new';
                $(".newUser").css("display", "block");
                $(".existUser").css("display", "none");
            } 
            type = val;
        }

        Livewire.on('resetCreationForm', () => {
            @this.insertUser = 'exist';
            $(".existUser").css("display", "block");
            $(".newUser").css("display", "none");
        });
        
</script>
@endpush

@push("css")
<link href="/css/calendar.css" rel="stylesheet" />
@endpush