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

    <header id="title--section" style="display:none !important"  class="d-flex align-items-center justify-content-between">
        <div class="title--section_name d-flex align-items-center justify-content-between">
            <i class="ico--ui title_section uscite me-2"></i>
            <h2 class="primary" >@if(!$add && !$update)Uscite @else Inserimento/modifica uscita @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)

    <div class="title--section_addButton d-flex justify-content-end">
        <button type="button" class="btn--ui entrata"
                wire:click="openImportModal" onclick="openImportModal()">
            Importa
        </button>
    </div>

        <div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true"
     wire:ignore.self>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header modal-header-blu">
                    <h5 class="modal-title" id="importModalLabel">Importa fatture passive</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" onclick="closeImportModal()" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form wire:submit.prevent="importReceipts">
                        <div class="mb-3" wire:ignore>
                            <label for="selectedCausal" class="form-label">Seleziona causale uscita*</label>
                            <select class="form-select import-causal-select" required id="selectedCausal" wire:model.defer="selectedCausal">
                                <option value="">Seleziona una causale</option>
                                @forelse($importCausals as $causal)
                                    <option value="{{ $causal['id'] }}">{{ $causal['name'] }}</option>
                                @empty
                                    <option value="" disabled>Nessuna causale disponibile</option>
                                @endforelse
                            </select>
                            @error('selectedCausal') <span class="text-danger">{{ $message }}</span> @enderror
                        </div>
                        <div class="mb-3">
                            <label for="receiptFiles" class="form-label">Seleziona files xml</label>
                            <input type="file" class="form-control" id="receiptFiles" wire:model="receiptFiles" multiple>
                            @error('receiptFiles.*') <span class="text-danger">{{ $message }}</span> @enderror
                            <small class="form-text text-muted">Massimo {{ ini_get('max_file_uploads') }} file consentiti.</small>
                        </div>
                        <div class="progress mb-2" wire:ignore>
                            <div class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0"
                                 aria-valuemin="0" aria-valuemax="100">0%
                            </div>
                        </div>
                        <div class="d-flex justify-content-end">
                            <button type="button" class="btn--ui lightGrey me-2" onclick="closeImportModal()">Annulla</button>
                            <button type="submit" class="btn--ui" >Importa</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

        <section id="subheader" class="d-flex align-items-center justify-content-between">
            @if(false)
                <form action="" class="group--action d-flex align-items-center">
                        <select class="form-select form-select-lg me-1" aria-label=".form-select-lg example" wire:model="multipleAction">
                            <option selected>Azione multipla</option>
                            <option value="delete"><i class="fa-regular fa-trash-can"></i></option>
                            </select>
                            <button type="submit" class="btn--ui" wire:click.prevent="executeMultipleAction()">applica</button>
                        </form>

                <form action="" class="compare--form d-flex align-items-center">
                    <select class="form-select form-select-lg me-1" aria-label=".form-select-lg example" wire:model="selectedFilter">
                        <option value="">--Seleziona--</option>
                        <option value="0">Oggi</option>
                        <option value="1">Questo mese: <span class="date-range">{{date("01/m/Y")}} - {{date("t/m/Y")}}</span></option>
                        <option value="2">Questo anno: <span class="date-range">{{date("01/01/Y")}} - {{date("31/12/Y")}}</span></option>
                        <option value="3">Tutte</option>
                        </select>
                    </form>
            @endif
        </section>

        <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 pagamento</b>
                        </div>
                        <div class="col-12">
                            <input id="dateFrom" type="date" class="form-control filterFrom  mb-2"  >
                        </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>Fornitore</b>
                        </div>
                        <div class="col-12">
                            <select name="search_supplier_id" class="form-select filterSupplier">
                                <option value="">--Seleziona--
                                @foreach($suppliers as $supplier)
                                    <option value="{{$supplier->id}}">{{$supplier->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" style="display: none;">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Origini</b>
                        </div>
                        <div class="col-12">
                            <select name="search_origin_id" class="form-select filterOrigins" 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">N° Fattura</th>
                        <th scope="col">Data</th>
                        <th scope="col">Importo</th>
                        <th scope="col">Fornitore</th>
                        <th scope="col">Causale</th>
                        <th scope="col">Pagamento</th>
                        {{-- <th scope="col">Origine</th> --}}
                        <th scope="col">Stato</th>
                        <th scope="col">...</th>
                    </tr>
                </thead>

                <tbody id="checkall-target">
                </tbody>
            </table>
            <br><b class="totalDiv"></b>

        </section>

    @else

        <a style="margin-top:20px" class="btn--ui lightGrey" href="/{{$fromPage != '' ? ($fromPage . '?showFilters=1') : 'out'}}"><i class="fa-solid fa-arrow-left"></i></a><br><br>

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

        <section id="accountingExit" class="d-flex"  wire:key='reload-{{$selectId}}'>
            <div class="accountingExit_data">
                <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-3">
                                    <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" id="commercial_1">
                                            <label class="form-check-label" for="commercial_1" style="cursor: pointer;">&nbsp;Commerciale</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" value="0" wire:model="commercial" id="commercial_0">
                                            <label class="form-check-label" for="commercial_0" style="cursor: pointer;">&nbsp;Non Commerciale</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            @if($commercial == 1)
                                {{-- <span class="title-form d-block w-100">N° Fattura</span>
                                <div class="input-group mb-3">
                                    <div class="col-md-4">
                                        <input class="form-control " type="text" placeholder="Numero fattura" wire:model="numero_fattura">
                                    </div>
                                </div> --}}
                                <div class="col-md-4">
                                    <span class="title-form d-block w-100">N° Fattura</span>
                                    <input class="form-control " type="text" placeholder="Numero fattura" wire:model="numero_fattura">
                                </div>
                            @endif

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

                            <div class="col-md-4">
                                <span class="title-form d-block w-100">Data Pagamento</span>
                                <div class="input-group mb-3">
                                    <input id="datePagamento" type="date" class="form-control"  wire:model="data_pagamento">
                                </div>
                            </div>
                            <div class="col-12">
                                <span class="title-form d-block w-100">Fornitore</span>

                                <select name="supplier_id" class="form-select supplierClass @error('supplier_id') is-invalid @enderror" aria-label="Seleziona un fornitore" wire:model="supplier_id">
                                    <option value="">--Seleziona--
                                    @foreach($suppliers as $supplier)
                                        <option value="{{$supplier->id}}">{{$supplier->name}}
                                    @endforeach
                                </select>
                                @error('supplier_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <div class="row gx-2 mt-5">
                            <div class="col-6">
                                <span class="title-form d-block w-100">Metodo di pagamento</span>
                                <div class="col-md-12">
                                    <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">
                                        <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>
                            <div class="col-6">
                                <span class="title-form d-block w-100">Origine</span>
                                <div class="col-md-12">
                                    <select name="origin_id" class="form-select" aria-label="Seleziona un origine" wire:model="origin_id">
                                        <option value="">--Seleziona--
                                        @foreach($banks as $bank)
                                            <option value="{{$bank->id}}">{{$bank->name}}
                                        @endforeach
                                    </select>
                                    @error('origin_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row gx-2 mt-5">
                            <span class="title-form d-block w-100">
                                Allegato
                            </span>
                            <div class="col-md-12">
                                @if ($attachment_old != '')
                                    <div class="alert alert-info d-flex align-items-center justify-content-between mb-3">
                                        <div class="d-flex align-items-center">
                                            <i class="fa-solid fa-file-check me-2"></i>
                                            <div>
                                                <strong>Allegato presente:</strong>
                                                <a href="{{ $this->getAttachmentUrl($attachment_old) }}" target="_blank" class="ms-2 btn btn-sm btn-outline-primary">
                                                    <i class="fa-regular fa-eye me-1"></i>Visualizza
                                                </a>
                                            </div>
                                        </div>
                                        <button type="button"
                                                wire:click.prevent="removeAttachment()"
                                                class="btn btn-sm btn-outline-danger"
                                                data-bs-toggle="popover"
                                                data-bs-trigger="hover focus"
                                                data-bs-placement="bottom"
                                                data-bs-content="Elimina allegato corrente">
                                            <i class="fa-regular fa-trash-can me-1"></i>Rimuovi
                                        </button>
                                    </div>
                                @endif

                                <div class="mb-3">
                                    <label for="attachment" class="form-label d-flex align-items-center">
                                        <i class="fa-solid fa-cloud-upload-alt me-2"></i>
                                        @if ($attachment_old != '')
                                            Sostituisci allegato esistente
                                        @else
                                            Carica nuovo allegato
                                        @endif
                                    </label>

                                    <div class="file-upload-container position-relative">
                                        <input class="form-control file-input"
                                            type="file"
                                            id="attachment"
                                            wire:model="attachment"
                                            accept="image/*,.pdf,.doc,.docx,.xml,.txt,.csv,.xls,.xlsx"
                                            style="opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer; z-index: 2;">

                                        <div class="file-drop-zone border-2 border-dashed rounded p-4 text-center position-relative"
                                             id="file-drop-zone"
                                             style="border-color: #dee2e6; background-color: #f8f9fa; min-height: 120px; display: flex; flex-direction: column; justify-content: center;">
                                            <div class="file-drop-content">
                                                <i class="fa-solid fa-cloud-upload-alt fa-2x text-muted mb-2"></i>
                                                <p class="mb-1"><strong>Clicca per selezionare</strong> o trascina qui il file</p>
                                                <small class="text-muted">
                                                    Formati: Immagini, PDF, Word, XML, TXT, CSV, Excel<br>
                                                    Dimensione massima: 10MB
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div id="upload-progress" class="mb-3" style="display: none;">
                                    <div class="d-flex justify-content-between mb-1">
                                        <span class="upload-status">
                                            <i class="fa-solid fa-spinner fa-spin me-2"></i>
                                            Caricamento in corso...
                                        </span>
                                        <span class="upload-percentage">0%</span>
                                    </div>
                                    <div class="progress" style="height: 8px;">
                                        <div class="progress-bar bg-primary progress-bar-striped progress-bar-animated"
                                             role="progressbar" style="width: 0%"></div>
                                    </div>
                                    <small class="text-muted mt-1 d-block upload-details"></small>
                                </div>

                                @if($attachment)
                                    <div class="alert alert-success d-flex align-items-center mb-3 file-selected-info">
                                        <i class="fa-solid fa-check-circle me-2"></i>
                                        <div class="flex-grow-1">
                                            <strong>Nuovo allegato selezionato:</strong>
                                            <span class="text-muted">{{ $attachment->getClientOriginalName() }}</span>
                                            <br><small class="text-muted">
                                                Dimensione: <span class="file-size-display">{{ number_format($attachment->getSize() / 1024, 1) }} KB</span>
                                                @if($attachment->getSize() > 10 * 1024 * 1024)
                                                    <span class="badge bg-warning ms-2">
                                                        <i class="fa-solid fa-exclamation-triangle me-1"></i>
                                                        File di grandi dimensioni
                                                    </span>
                                                @endif
                                            </small>
                                        </div>
                                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearFileSelection()">
                                            <i class="fa-solid fa-times"></i>
                                        </button>
                                    </div>
                                @endif

                                @error('attachment')
                                    <div class="alert alert-danger">
                                        <i class="fa-solid fa-exclamation-triangle me-2"></i>{{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div>
                        @foreach($rows as $idx => $row)

                            <div class="row gx-2 mt-5" wire:ignore.self>
                                <span class="title-form d-block w-100">Causale</span>
                                <div class="col-md-12">

                                    <livewire:causals :type="$typeOUT" :idx="$idx" :show_hidden=0 :causal_id="$rows[$idx]['causal_id']" :wire:key="$idx" />

                                    @if(false)
                                        <select name="rows.{{$idx}}.causal_id" class="form-select causalClass @error('row.' . $idx . '.causal_id') is-invalid @enderror" aria-label="Seleziona una causale" wire:model="rows.{{$idx}}.causal_id">
                                            <option value="">--Seleziona--
                                            @foreach($causals as $causal)
                                                <option value="{{$causal["id"]}}">{!!$causal["name"]!!}
                                            @endforeach
                                        </select>
                                        @error('causal_id')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    @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-5">
                                <span class="title-form d-block w-100">Dettaglio causale</span>
                                <div class="col-md-12">
                                    <textarea class="form-control" style ="background-color: #E9F0F5 !important;" placeholder="Dettaglio causale" wire:model="rows.{{$idx}}.note"></textarea>
                                </div>
                            </div>

                            <div class="row gx-2 mt-5 align-items-center">
                                <div class="col-md-6">
                                    <span class="total primary">Imponibile</span>
                                </div>
                                <div class="col-md-6">
                                    @if($add)
                                        <input type="text" class="form-control totalInput text-end @error('rows.{{$idx}}.imponibile') is-invalid @enderror"
                                            id="rows.{{$idx}}.imponibile" wire:model="rows.{{$idx}}.imponibile"
                                            wire:keydown.enter="store(false)" onkeyup="onlyNumberAmount(this)" placeholder="€ 0,00">
                                    @endif
                                    @if($update)
                                        <input type="text" class="form-control totalInput text-end @error('rows.{{$idx}}.imponibile') is-invalid @enderror"
                                            id="rows.{{$idx}}.imponibile" placeholder="€ 0,00" wire:model="rows.{{$idx}}.imponibile"
                                            onkeyup="onlyNumberAmount(this)" wire:keydown.enter="update(false)">
                                    @endif
                                    @error('rows.'. $idx . '.imponibile')
                                        <span style="margin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            @if($commercial)
                                <div class="row gx-2 mt-5 align-items-center">
                                    <div class="col-md-6">
                                        <span class="total primary">Aliquota IVA</span>
                                    </div>
                                    <div class="col-md-2 ms-auto">
                                        @if($add || $update )
                                            <select class="form-select text-end @error('rows.'.$idx.'.aliquota_iva') is-invalid @enderror"
                                                id="rows.{{$idx}}.aliquota_iva"
                                                wire:model="rows.{{$idx}}.aliquota_iva">
                                                <option value="">--Seleziona--</option>
                                                @foreach($vats as $vat)
                                                    <option value="{{$vat->value}}">{{$vat->name}}</option>
                                                @endforeach
                                            </select>
                                            @error('rows.'. $idx . '.aliquota_iva')
                                                <span style="margin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
                                            @enderror
                                        @endif
                                    </div>
                                </div>
                            @endif
                            <div class="row gx-2 mt-5 align-items-center">
                                <div class="col-md-6">
                                    <span class="total primary">Importo</span>
                                </div>
                                <div class="col-md-6">
                                    @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)" placeholder="€ 0,00">
                                    @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)" wire:keydown.enter="update(false)">
                                    @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-5 align-items-center">
                                <div class="col-md-4">
                                    <span class="total primary">Periodo</span>
                                </div>
                                <div class="col-md-8">

                                    @if($multiP)
                                        <div class="row">
                                            <div class="col-md-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">
                                                        @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="multiYearFrom" >
                                                </div>
                                            </div>
                                            <div class="col-md-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">
                                                        @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="multiYearTo" >
                                                </div>
                                            </div>
                                            <div class="col-md-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-md-6">
                                                <button type="button" class="btn--ui lightGrey" wire:click.prevent="multiPeriodCancel()" style="margin-top:20px">
                                                    Annulla multi periodo
                                                </button>
                                            </div>
                                        </div>

                                    @else

                                        <div class="row">
                                            @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">
                                                            @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" >
                                                    </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"]) / sizeof($rows[$idx]["when"])) : ""}}</b></span>
                                                </div>

                                                <div class="col-md-2"><br>
                                                    <button type="button" class="btn--ui primary" wire:click.prevent="delPeriod({{$idx}}, {{$xxx}})" style="float:right">
                                                        -
                                                    </button>
                                                </div>
                                            @endforeach
                                            <div class="d-flex justify-content-between mt-3">
                                                <button type="button" class="btn--ui primary 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>
                                        </div>
                                    @endif
                                </div>
                            </div>

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

                        @endforeach

                        <br>
                        <button type="button" class="btn--ui primary" wire:click.prevent="addRow()">
                            Aggiungi causale
                        </button>

                        <div class="accountingExit--btn d-flex align-items-center justify-content-between">

                        <button class="btn--ui lightGrey" onclick="annulla()">annulla</button>
                            @if($add)
                                <button class="btn--ui primary"  type="submit" wire:click.prevent="store()">inserisci</button>
                            @endif
                            @if($update)
                                <button class="btn--ui primary"  type="submit" wire:click.prevent="update()">salva</button>
                            @endif

                        </div>
            </form>
            </div>
        </section>

    @endif

    <div class="modal fade" id="importResultModal" tabindex="-1" aria-labelledby="importResultModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header modal-header-blu">
                    <h5 class="modal-title" id="importResultModalLabel" >Importazione Completata</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="importResultMessage"></div>
                </div>
                <div class="modal-footer" style="background-color: #FFF!important;">
                    <button type="button" class="btn--ui lightGrey" data-bs-dismiss="modal">Chiudi</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="recordDetailsModal" tabindex="-1" aria-labelledby="recordDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header modal-header-blu">
                    <h5 class="modal-title" id="recordDetailsModalLabel">Dettaglio uscita</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6 class="primary">Informazioni generali</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <th>Data:</th>
                                    <td id="recordDate"></td>
                                </tr>
                                <tr>
                                    <th>Data pagamento:</th>
                                    <td id="recordPaymentDate"></td>
                                </tr>
                                <tr>
                                    <th>Fornitore:</th>
                                    <td id="recordSupplier"></td>
                                </tr>
                                <tr>
                                    <th>Metodo di pagamento:</th>
                                    <td id="recordPaymentMethod"></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6 class="primary">Importo e pagamento</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <th>Importo totale:</th>
                                    <td id="recordTotalAmount" class="primary fw-bold"></td>
                                </tr>
                                <tr>
                                    <th>Stato pagamento:</th>
                                    <td><span id="recordPaymentStatus" class="badge"></span></td>
                                </tr>
                            </table>
                             <h6 class="primary mt-3">Allegato</h6>
                            <div id="recordAttachmentSection">
                                <div id="recordAttachmentPresent" style="display: none;">
                                    <div class="d-flex align-items-center">
                                        <i class="fa-solid fa-file-pdf me-2 text-danger"></i>
                                        <div>
                                            <a id="recordAttachmentLink" href="#" target="_blank" class="btn btn-sm btn-outline-primary">
                                                <i class="fa-regular fa-eye me-1"></i>
                                                <span id="recordAttachmentName">Visualizza allegato</span>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div id="recordAttachmentMissing" style="display: none;">
                                    <span class="text-muted">
                                        <i class="fa-regular fa-file me-2"></i>
                                        Nessun allegato presente
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <h6 class="primary">Dettaglio causali</h6>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th scope="col">N.</th>
                                    <th scope="col">Descrizione</th>
                                    <th scope="col">Imponibile</th>
                                    <th scope="col">IVA</th>
                                    <th scope="col">Imposta</th>
                                    <th scope="col">Totale</th>
                                </tr>
                            </thead>
                            <tbody id="recordRowsContainer">
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer" style="background-color: #FFF!important;">
                    <button type="button" class="btn--ui lightGrey" data-bs-dismiss="modal">Chiudi</button>
                </div>
            </div>
        </div>
    </div>

    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="loading-content">
            <div class="loading-spinner"></div>
            <div class="loading-text">Caricamento...</div>
            <div class="loading-progress">
                <div class="progress-bar-custom">
                    <div class="progress-fill"></div>
                </div>
                <div class="progress-details mt-2">
                    <small class="text-muted d-block loading-details"></small>
                </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 {
            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;
        }
        .select2-selection--multiple{
            overflow: hidden !important;
            height: auto !important;
        }

        .file-upload-container {
            position: relative;
        }

        .file-drop-zone {
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .file-drop-zone:hover {
            border-color: var(--color-blu) !important;
            background-color: #f0f8ff !important;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(12, 97, 151, 0.15);
        }

        .file-drop-zone.dragover {
            border-color: var(--color-blu) !important;
            background-color: #e6f3ff !important;
            transform: scale(1.02);
            box-shadow: 0 8px 25px rgba(12, 97, 151, 0.25);
        }

        .file-input:focus + .file-drop-zone {
            border-color: var(--color-blu) !important;
            box-shadow: 0 0 0 0.25rem rgba(12, 97, 151, 0.25);
        }

        .file-requirements ul {
            list-style-type: none;
            padding-left: 1rem;
        }

        .file-requirements li:before {
            content: "•";
            color: #6c757d;
            margin-right: 0.5rem;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            backdrop-filter: blur(3px);
        }

        .loading-content {
            background: white;
            padding: 40px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            min-width: 350px;
            max-width: 90vw;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid var(--color-blu);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 25px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading-text {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 20px;
        }

        .progress-bar-custom {
            width: 100%;
            height: 6px;
            background: #f0f0f0;
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 10px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--color-blu), #1e7bb8, var(--color-blu));
            width: 0%;
            transition: width 0.5s ease;
            animation: progressShimmer 2s ease-in-out infinite;
        }

        @keyframes progressShimmer {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }

        .loading-details {
            color: #666;
            font-size: 0.9em;
            min-height: 1.2em;
        }

        #upload-progress {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
        }

        #upload-progress .progress {
            height: 10px;
            border-radius: 5px;
            overflow: hidden;
        }

        #upload-progress .progress-bar {
            transition: width 0.3s ease;
        }

        .upload-status {
            font-weight: 600;
            color: var(--color-blu);
        }

        .upload-percentage {
            font-weight: bold;
            color: #28a745;
        }

        .loading-active {
            pointer-events: none;
            opacity: 0.7;
            transition: opacity 0.3s ease;
        }

        .file-selected-info {
            border-left: 4px solid #28a745;
            background-color: #f8fff9;
        }

        .file-size-display {
            font-weight: 600;
        }

        @media (max-width: 768px) {
            .loading-content {
                padding: 30px 20px;
                min-width: 300px;
            }

            .file-drop-zone {
                min-height: 100px;
                padding: 20px 15px;
            }
        }

        @keyframes fileUploadSuccess {
            0% { transform: scale(0.8); opacity: 0; }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); opacity: 1; }
        }

        .file-selected-info {
            animation: fileUploadSuccess 0.5s ease-out;
        }

        #recordAttachmentSection {
            min-height: 50px;
        }

        #recordAttachmentPresent {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 6px;
            border-left: 4px solid #28a745;
        }

        #recordAttachmentMissing {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 6px;
            border-left: 4px solid #6c757d;
        }

        #recordAttachmentLink {
            text-decoration: none;
            transition: all 0.2s ease;
        }

        #recordAttachmentLink:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        /* Stili per i diversi tipi di file */
        .fa-file-pdf {
            color: #dc3545 !important;
        }

        .fa-file-code {
            color: #17a2b8 !important;
        }

        .fa-file-image {
            color: #28a745 !important;
        }

        .fa-file-word {
            color: #007bff !important;
        }

        .fa-file-excel {
            color: #28a745 !important;
        }

        .fa-file {
            color: #6c757d !important;
        }

        /* Animazione per la transizione del campo numero fattura */
        .numero-fattura-field {
            transition: all 0.3s ease;
            overflow: hidden;
        }

        .numero-fattura-field.hidden {
            max-height: 0;
            opacity: 0;
            margin-bottom: 0 !important;
        }

        .numero-fattura-field.visible {
            max-height: 100px;
            opacity: 1;
        }

        /* Miglioramenti per i radio button */
        .check--invoice .form-check-input:checked {
            background-color: var(--color-blu);
            border-color: var(--color-blu);
        }

        .check--invoice .form-check-label {
            font-weight: 500;
            transition: color 0.2s ease;
        }

        .check--invoice .form-check-input:checked + .form-check-label {
            color: var(--color-blu);
        }

        /* Responsive per mobile */
        @media (max-width: 768px) {
            #recordAttachmentSection {
                margin-top: 15px;
            }

            #recordAttachmentPresent,
            #recordAttachmentMissing {
                padding: 8px;
            }

            #recordAttachmentName {
                font-size: 0.9em;
            }
        }
    </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 matchStart(params, data) {
            params.term = params.term || '';
            if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
                return data;
            }
            return false;
        }

        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.');
        }

        let selectedFileInfo = null;
        let fileUploadProgressInterval = null;

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function getFileTypeDescription(mimeType) {
            const typeMap = {
                'image/jpeg': 'Immagine JPEG',
                'image/jpg': 'Immagine JPG',
                'image/png': 'Immagine PNG',
                'image/gif': 'Immagine GIF',
                'application/pdf': 'Documento PDF',
                'application/msword': 'Documento Word',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Documento Word',
                'text/xml': 'File XML',
                'application/xml': 'File XML',
                'text/plain': 'File di testo',
                'text/csv': 'File CSV',
                'application/vnd.ms-excel': 'File Excel',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'File Excel'
            };
            return typeMap[mimeType] || 'Documento';
        }

        function validateFile(file) {
            const maxSize = 50 * 1024 * 1024;
            if (file.size > maxSize) {
                alert('File troppo grande. Dimensione massima: 50MB');
                return false;
            }

            const allowedTypes = [
                'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp',
                'application/pdf',
                'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'text/xml', 'application/xml', 'text/plain', 'text/csv',
                'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            ];

            if (!allowedTypes.includes(file.type)) {
                alert('Tipo di file non supportato. Formati consentiti: immagini, PDF, documenti Word, XML, TXT, CSV, Excel');
                return false;
            }

            return true;
        }

        function clearFileSelection() {
            const attachmentInput = document.getElementById('attachment');
            if (attachmentInput) {
                attachmentInput.value = '';
            }

            const fileInfo = document.querySelector('.file-selected-info');
            if (fileInfo) {
                fileInfo.remove();
            }

            selectedFileInfo = null;

            if (window.Livewire) {
                Livewire.first().set('attachment', null);
            }
        }

        function showLoading(message = 'Caricamento...', details = '') {
            const loadingOverlay = document.getElementById('loadingOverlay');
            const loadingText = loadingOverlay.querySelector('.loading-text');
            const loadingDetails = loadingOverlay.querySelector('.loading-details');
            const progressFill = loadingOverlay.querySelector('.progress-fill');
            const form = document.getElementById('accountingExit');

            if (loadingText) {
                loadingText.textContent = message;
            }

            if (loadingDetails) {
                loadingDetails.textContent = details;
            }

            if (progressFill) {
                progressFill.style.width = '0%';
            }

            if (form) {
                form.classList.add('loading-active');
            }

            loadingOverlay.style.display = 'flex';
            startProgressAnimation();
        }

        function showFileUploadLoading(fileName, fileSize) {
            const estimatedTime = Math.max(3, Math.floor(fileSize / (1024 * 1024)) * 2);
            const details = `File: ${fileName} (${formatFileSize(fileSize)})`;

            showLoading('Caricamento allegato in corso...', details);
            startFileUploadProgress(estimatedTime);
        }

        function updateLoading(message, details = '') {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (!loadingOverlay || loadingOverlay.style.display === 'none') return;

            const loadingText = loadingOverlay.querySelector('.loading-text');
            const loadingDetails = loadingOverlay.querySelector('.loading-details');
            const progressFill = loadingOverlay.querySelector('.progress-fill');

            if (loadingText) {
                loadingText.textContent = message;
            }

            if (loadingDetails && details) {
                loadingDetails.textContent = details;
            }

            // Increase progress
            if (progressFill) {
                const currentWidth = parseInt(progressFill.style.width) || 0;
                const newWidth = Math.min(currentWidth + 20, 90);
                progressFill.style.width = newWidth + '%';
            }
        }

        function hideLoading() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (!loadingOverlay) return;

            const progressFill = loadingOverlay.querySelector('.progress-fill');
            const form = document.getElementById('accountingExit');

            if (progressFill) {
                progressFill.style.width = '100%';
            }

            setTimeout(() => {
                loadingOverlay.style.display = 'none';

                if (form) {
                    form.classList.remove('loading-active');
                }

                if (fileUploadProgressInterval) {
                    clearInterval(fileUploadProgressInterval);
                    fileUploadProgressInterval = null;
                }
            }, 500);
        }

        function startProgressAnimation() {
            const progressFill = document.querySelector('#loadingOverlay .progress-fill');
            if (!progressFill) return;

            let progress = 0;
            const interval = setInterval(() => {
                if (progress < 15) {
                    progress += 1;
                    progressFill.style.width = progress + '%';
                }
            }, 200);

            window.baseProgressInterval = interval;
        }

        function startFileUploadProgress(estimatedSeconds) {
            const progressFill = document.querySelector('#loadingOverlay .progress-fill');
            if (!progressFill) return;

            let progress = 15;
            const increment = 75 / (estimatedSeconds * 10);

            fileUploadProgressInterval = setInterval(() => {
                if (progress < 90) {
                    progress += increment;
                    progressFill.style.width = Math.min(progress, 90) + '%';
                }
            }, 100);
        }

        function setupDragAndDrop() {
            const fileDropZone = document.getElementById('file-drop-zone');
            const fileInput = document.getElementById('attachment');

            if (!fileDropZone || !fileInput) return;

            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                fileDropZone.addEventListener(eventName, preventDefaults, false);
                document.body.addEventListener(eventName, preventDefaults, false);
            });

            ['dragenter', 'dragover'].forEach(eventName => {
                fileDropZone.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                fileDropZone.addEventListener(eventName, unhighlight, false);
            });

            fileDropZone.addEventListener('drop', handleDrop, false);

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            function highlight(e) {
                fileDropZone.classList.add('dragover');
            }

            function unhighlight(e) {
                fileDropZone.classList.remove('dragover');
            }

            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;

                if (files.length > 0) {
                    const file = files[0];
                    if (validateFile(file)) {
                        fileInput.files = files;

                        const event = new Event('change', { bubbles: true });
                        fileInput.dispatchEvent(event);
                    }
                }
            }
        }

        $(document).ready(function() {
            setupDragAndDrop();

            const attachmentInput = document.getElementById('attachment');
            if (attachmentInput) {
                attachmentInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (!file) return;

                    if (!validateFile(file)) {
                        e.target.value = '';
                        return;
                    }

                    selectedFileInfo = {
                        name: file.name,
                        size: file.size,
                        type: file.type
                    };

                    if (file.size > 10 * 1024 * 1024) {
                        const warning = document.createElement('div');
                        warning.className = 'alert alert-warning mt-2 large-file-warning';
                        warning.innerHTML = `
                            <i class="fa-solid fa-exclamation-triangle me-2"></i>
                            <strong>File di grandi dimensioni:</strong> ${file.name} (${formatFileSize(file.size)})
                            <br><small>Il caricamento richiederà tempo aggiuntivo. Assicurati di avere una connessione stabile.</small>
                        `;

                        const existingWarning = document.querySelector('.large-file-warning');
                        if (existingWarning) {
                            existingWarning.remove();
                        }

                        const container = attachmentInput.closest('.col-md-12');
                        container.appendChild(warning);

                        setTimeout(() => {
                            warning.remove();
                        }, 5000);
                    }
                });
            }
        });

        document.addEventListener('click', function(e) {
            const target = e.target;

            if ((target.textContent.includes('inserisci') || target.textContent.includes('salva')) &&
                target.classList.contains('btn--ui')) {

                const fileInput = document.getElementById('attachment');
                const hasFile = fileInput && fileInput.files.length > 0;

                if (hasFile && selectedFileInfo) {
                    setTimeout(() => {
                        showFileUploadLoading(selectedFileInfo.name, selectedFileInfo.size);
                    }, 100);
                } else {
                    setTimeout(() => {
                        const action = target.textContent.includes('inserisci') ? 'Salvataggio' : 'Aggiornamento';
                        showLoading(action + ' in corso...');
                    }, 100);
                }
            }
        });

        window.livewire.on('refresh', () => {
            $('.causalClass').select2({
                matcher: function(params, data) {
                    return matchStart(params, data);
                }
            });
            $('.supplierClass').select2({});
            $('.paymentClass').select2({
                matcher: function(params, data) {
                    return matchStart(params, data);
                }
            });
        });

        Livewire.on('load-select', () => {
            $('.causalClass').each(function(i, obj) {
                $(obj).select2({"language": {"noResults": function(){return "Nessun risultato";}}});
                $(obj).on('change', function (e) {
                    var data = $(obj).select2("val");
                    var name = $(obj).select2().attr("name");
                    @this.set(name, data);
                });
            });
            $('.supplierClass').select2({});
            $('.supplierClass').on('change', function (e) {
                var data = $('.supplierClass').select2("val");
                @this.set('supplier_id', data);
            });
            $('.paymentClass').select2({
                matcher: function(params, data) {
                    return matchStart(params, data);
                }
            });
            $('.paymentClass').on('change', function (e) {
                var data = $('.paymentClass').select2("val");
                @this.set('payment_method_id', data);
            });

            $('.filterSupplier').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterPaymentMethod').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterCausals').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterOrigins').select2({"language": {"noResults": function(){return "Nessun risultato";}}});

            setTimeout(setupDragAndDrop, 100);
        });

        $('.filterSupplier').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterPaymentMethod').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterCausals').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterOrigins').select2({"language": {"noResults": function(){return "Nessun risultato";}}});

        Livewire.on('start-loading', message => {
            showLoading(message);
        });

        Livewire.on('update-loading', message => {
            updateLoading(message);
        });

        Livewire.on('stop-loading', () => {
            hideLoading();
        });

        Livewire.on('flash-error', message => {
            hideLoading();

            const alert = document.createElement('div');
            alert.classList.add('alert', 'alert-danger', 'alert-dismissible', 'fade', 'show');
            alert.setAttribute('role', 'alert');
            alert.innerHTML = `
                <i class="fa-solid fa-exclamation-triangle me-2"></i>
                ${message}
                <button type="button" class="btn-close"`;

            const accountingExit = document.getElementById('accountingExit');
            if (accountingExit) {
                accountingExit.prepend(alert);
            } else {
                const mainContainer = document.querySelector('.col.card--ui');
                if (mainContainer) {
                    mainContainer.prepend(alert);
                }
            }

            setTimeout(() => {
                alert.remove();
            }, 7000);
        });

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

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

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

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

        function initImportCausalSelect() {
            $('.import-causal-select').select2({
                dropdownParent: $('#importModal .modal-content'),
                language: {
                    noResults: function() {
                        return "Nessun risultato";
                    }
                }
            });

            $('.import-causal-select').on('change', function() {
                let selectedValue = $(this).val();
                Livewire.first().set('selectedCausal', selectedValue);
            });
        }

        function openImportModal() {
            let tableState = null;
            if ($.fn.DataTable.isDataTable('#tablesaw-350')) {
                tableState = $('#tablesaw-350').DataTable().state.save();
            }

            const importModal = new bootstrap.Modal(document.getElementById('importModal'));
            importModal.show();

            setTimeout(function() {
                initImportCausalSelect();

                if (!$.fn.DataTable.isDataTable('#tablesaw-350')) {
                    loadDataTable();
                    if (tableState) {
                        $('#tablesaw-350').DataTable().state.load(tableState);
                    }
                }
            }, 200);
        }

        function closeImportModal() {
            const importModal = bootstrap.Modal.getInstance(document.getElementById('importModal'));
            if (importModal) {
                importModal.hide();
            }

            setTimeout(function() {
                if (!$.fn.DataTable.isDataTable('#tablesaw-350')) {
                    loadDataTable();
                }
            }, 100);
        }

        // IMPORT PROGRESS AND RESULTS
        Livewire.on('update-progress', (progress) => {
            const progressBar = document.querySelector('.progress-bar');
            if (progressBar) {
                progressBar.style.width = `${progress}%`;
                progressBar.setAttribute('aria-valuenow', progress);
                progressBar.textContent = `${Math.round(progress)}%`;
            }
        });

        Livewire.on('import-started', () => {
            const closeButton = document.querySelector('#importModal .btn-close');
            const submitButton = document.querySelector('#importModal button[type="submit"]');
            if (closeButton) closeButton.disabled = true;
            if (submitButton) submitButton.disabled = true;
        });

        let transitioningToResultModal = false;

        Livewire.on('show-import-result', data => {
            transitioningToResultModal = true;

            const resultDiv = document.getElementById('importResultMessage');
            resultDiv.innerHTML = data.message;
            const importModal = bootstrap.Modal.getInstance(document.getElementById('importModal'));
            if (importModal) {
                importModal.hide();
            }

            setTimeout(() => {
                const resultModal = new bootstrap.Modal(document.getElementById('importResultModal'));
                resultModal.show();
            }, 300);
        });

        document.getElementById('importModal').addEventListener('hidden.bs.modal', function () {
            if (!transitioningToResultModal) {
                setTimeout(function() {
                    window.location.reload();
                }, 500);
            } else {
                transitioningToResultModal = false;
            }
        });

        document.getElementById('importResultModal').addEventListener('hidden.bs.modal', function () {
            window.location.reload();
        });

        function calculateAmount(rowIndex) {
            const imponibileField = document.getElementById(`rows.${rowIndex}.imponibile`);
            const aliquotaField = document.getElementById(`rows.${rowIndex}.aliquota_iva`);
            const amountField = document.getElementById(`rows.${rowIndex}.amount`);

            if (imponibileField && aliquotaField && amountField) {
                let imponibile = imponibileField.value.replace('€', '').replace(/\./g, '').replace(',', '.').trim();
                imponibile = parseFloat(imponibile) || 0;

                let aliquota = parseFloat(aliquotaField.value) || 0;

                const imposta = imponibile * (aliquota / 100);
                const totalAmount = imponibile + imposta;

                let formattedAmount = "€ " + totalAmount.toFixed(2).replace('.', ',').replace(/\B(?=(\d{3})+(?!\d))/g, ".");
                amountField.value = formattedAmount;

                const component = Livewire.find(document.querySelector('[wire\\:id]').getAttribute('wire:id'));
                if (component) {
                    component.set(`rows.${rowIndex}.amount`, formattedAmount);
                }
            }
        }

        function setupCalculationListeners() {
            const rows = document.querySelectorAll('input[id^="rows."][id$=".imponibile"], select[id^="rows."][id$=".aliquota_iva"]');

            rows.forEach(field => {
                field.addEventListener('blur', function() {
                    const match = this.id.match(/rows\.(\d+)\./);
                    if (match) {
                        const rowIndex = match[1];
                        calculateAmount(rowIndex);
                    }
                });

                field.addEventListener('change', function() {
                    const match = this.id.match(/rows\.(\d+)\./);
                    if (match) {
                        const rowIndex = match[1];
                        calculateAmount(rowIndex);
                    }
                });
            });
        }

        document.addEventListener('livewire:load', setupCalculationListeners);
        document.addEventListener('livewire:update', setupCalculationListeners);
        Livewire.on('load-select', function() {
            setTimeout(setupCalculationListeners, 300);
        });

        function viewData(id) {
            Livewire.first().viewData(id);
            setTimeout(function() {
                const modalElement = document.getElementById('recordDetailsModal');
                if (modalElement) {
                    const modal = new bootstrap.Modal(modalElement);
                    modal.show();

                    modalElement.addEventListener('hidden.bs.modal', function() {
                        setTimeout(function() {
                            window.location.reload();
                        }, 100);
                    });
                }
            }, 300);
        }

        window.addEventListener('show-record-details', function(event) {
            showRecordDetailsModal(event.detail.record);
        });

        function showRecordDetailsModal(record) {
            const modalElement = document.getElementById('recordDetailsModal');
            if (!modalElement) return;

            try {
                let recordDetailsModal = new bootstrap.Modal(modalElement);

                document.getElementById('recordDate').textContent = record.formatted_date || 'N/A';
                document.getElementById('recordPaymentDate').textContent = record.formatted_data_pagamento || 'N/A';
                document.getElementById('recordSupplier').textContent = record.supplier_name || 'N/A';
                document.getElementById('recordPaymentMethod').textContent = record.payment_method_name || 'N/A';
                document.getElementById('recordTotalAmount').textContent = record.formatted_amount || 'N/A';

                const paymentStatusElement = document.getElementById('recordPaymentStatus');
                if (paymentStatusElement) {
                    paymentStatusElement.textContent = record.payment_status || 'N/A';
                    paymentStatusElement.className = 'badge ' + (record.is_paid ? 'bg-success' : 'bg-warning');
                }

                const rowsContainer = document.getElementById('recordRowsContainer');
                if (rowsContainer) {
                    rowsContainer.innerHTML = '';

                    if (record.rows && record.rows.length > 0) {
                        record.rows.forEach(function(row, index) {
                            const tr = document.createElement('tr');

                            tr.innerHTML = `
                                <td>${index + 1}</td>
                                <td>${row.note && row.note.trim() !== '' ? row.note : (row.causal_name || 'N/A')}</td>
                                <td>${row.formatted_imponibile || 'N/A'}</td>
                                <td>${row.aliquota_iva ? row.aliquota_iva + '%' : '-'}</td>
                                <td>${row.formatted_imposta || 'N/A'}</td>
                                <td class="fw-bold">${row.formatted_amount || 'N/A'}</td>
                            `;

                            rowsContainer.appendChild(tr);
                        });
                    } else {
                        const tr = document.createElement('tr');
                        tr.innerHTML = '<td colspan="6" class="text-center">Nessuna riga disponibile</td>';
                        rowsContainer.appendChild(tr);
                    }
                }

                recordDetailsModal.show();

            } catch (error) {
                console.error('Error displaying modal:', error);
            }
        }

        window.addEventListener('beforeunload', function() {
            hideLoading();
            if (fileUploadProgressInterval) {
                clearInterval(fileUploadProgressInterval);
            }
            if (window.baseProgressInterval) {
                clearInterval(window.baseProgressInterval);
            }
        });
    </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() {
            loadDataTable();
        });

        var filterSupplier = localStorage.getItem("filterSupplierRecordOut");
        if (filterSupplier && filterSupplier != "null" && filterSupplier != "undefined") {
            $('.filterSupplier').val(filterSupplier);
            $('.filterSupplier').trigger('change');
        }
        var filterPaymentMethod = localStorage.getItem("filterPaymentMethodRecordOut");
        if (filterPaymentMethod && filterPaymentMethod != "null" && filterPaymentMethod != "undefined") {
            $('.filterPaymentMethod').val(filterPaymentMethod);
            $('.filterPaymentMethod').trigger('change');
        }
        var filterCausals = localStorage.getItem("filterCausalsRecordOut");
        if (filterCausals && filterCausals != "null" && filterCausals != "undefined") {
            $('.filterCausals').val(filterCausals);
            $('.filterCausals').trigger('change');
        }
        var filterOrigins = localStorage.getItem("filterOriginsRecordOut");
        if (filterOrigins && filterOrigins != "null" && filterOrigins != "undefined") {
            $('.filterOrigins').val(filterOrigins);
            $('.filterOrigins').trigger('change');
        }
        var filterFrom = localStorage.getItem("filterFromRecordOut");
        if (filterFrom && filterFrom != "" && filterFrom != "undefined") {
            $('.filterFrom').val(filterFrom);
        }
        var filterTo = localStorage.getItem("filterToRecordOut");
        if (filterTo && filterTo != "" && filterTo != "undefined") {
            $('.filterTo').val(filterTo);
        }

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

            $(document).on("select2:open",".filterCausals",function() {
                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",".filterOrigins",function() {
                setTimeout(() => {
                    $(".select2-results__option").each(function(){
                        var txt = $(this).html();
                        var count = (txt.match(/-/g) || []).length;
                        $(this).addClass('paddingLeftSelect' + count);
                    });
                }, 100);
            });

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

        function editData(id) {
            @this.edit(id);
        }

        function deleteData(id) {
            if (confirm('Sei sicuro?'))
                @this.delete(id).then(() => {
                    window.location.reload();
                });
        }

        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");
            $('.filterSupplier').val('');
            $('.filterSupplier').trigger('change');
            $('.filterPaymentMethod').val('');
            $('.filterPaymentMethod').trigger('change');
            $('.filterCausals').val('');
            $('.filterCausals').trigger('change');
            $('.filterOrigins').val('');
            $('.filterOrigins').trigger('change');
            $('.filterFrom').val('');
            $('.filterTo').val('');
            localStorage.clear();
            loadDataTable();
        }

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

            var filterSupplier = $('.filterSupplier').val();
            var filterPaymentMethod = $('.filterPaymentMethod').val();
            var filterCausals = $('.filterCausals').val();
            var filterOrigins = $('.filterOrigins').val();
            var filterFrom = $('.filterFrom').val();
            var filterTo = $('.filterTo').val();

            localStorage.setItem("filterSupplierRecordOut", filterSupplier);
            localStorage.setItem("filterPaymentMethodRecordOut", filterPaymentMethod);
            localStorage.setItem("filterCausalsRecordOut", filterCausals);
            localStorage.setItem("filterOriginsRecordOut", filterOrigins);
            localStorage.setItem("filterFromRecordOut", filterFrom);
            localStorage.setItem("filterToRecordOut", filterTo);

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


            $('#tablesaw-350').DataTable({
                stateSave: true,
                ajax: {
                    url : "/get_record_out?filterSupplier=" + filterSupplier + "&filterPaymentMethod=" + filterPaymentMethod + "&filterOrigins=" + filterOrigins + "&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: 'numero_fattura' },
                    {
                        data: "date",
                        render: function (data, type){
                            if (data == "") return " TOTALE";
                            if (type == "sort"){
                                return new Date(data).getTime();
                            }
                            const j = data.split(" ");
                            const d = j[0].split("-");
                            var ret = d[2] + "/" + d[1] + "/" + d[0];
                            return ret;
                        }
                    },
                    { data: 'total', className: "numericCol" },
                    { data: 'supplier' },
                    { data: 'causals' },
                    { data: 'payment' },
                    // { data: 'origin' },
                    {
                        data: 'is_paid',
                        render: function (data) {
                            if (data === true || data === 'true' || data === 1 || data === '1' || data === 'Pagato') {
                                return '<span class="badge bg-success">Pagato</span>';
                            } else {
                                return '<span class="badge bg-warning">Da Pagare</span>';
                            }
                        }
                    },
                    {
                        data: "action",
                        render: function (data){
                            if (data == "") return "";
                            const j = data.split("|");
                            var 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="viewData(' + j[0] + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Info"><i class="fa-regular fa-eye"></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>';
                            return ret;
                        }
                    },
                ],
                order: [[1, 'desc']],
                thead: {
                    'th': {'background-color': 'blue'}
                },
                layout: {
                    topStart : null,
                    topEnd : null,
                    top1A: {
                        // buttons: [
                        //     {
                        //         extend: 'collection',
                        //         text: 'ESPORTA',
                                buttons: [
                                    {
                                        extend: 'excelHtml5',
                                        text: '<i class="fa-solid fa-file-excel"></i>',
                                        action: newexportaction,
                                        title: date_export + 'Uscite',
                                        filename: date_export + 'Uscite',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        },
                                        exportLeftCols: [0]
                                    },
                                    {
                                        extend: 'pdfHtml5',
                                        text: '<i class="fa-solid fa-file-pdf"></i>',
                                        action: newexportaction,
                                        title: date_export + 'Uscite',
                                        filename: date_export + 'Uscite',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'print',
                                        action: newexportaction,
                                        text: '<i class="fa-solid fa-print"></i>',
                                        title: date_export + 'Uscite',
                                        filename: date_export + 'Uscite',
                                        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 href="#" 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.addEventListener('livewire:initialized', () => {
            let importModalOpen = false;
            const importModal = document.getElementById('importModal');

            importModal.addEventListener('shown.bs.modal', function () {
                importModalOpen = true;
            });

            importModal.addEventListener('hidden.bs.modal', function () {
                importModalOpen = false;
                setTimeout(() => {
                    if (!$.fn.DataTable.isDataTable('#tablesaw-350')) {
                        loadDataTable();
                    }
                }, 100);
            });

            document.addEventListener('livewire:update', function() {
                if (importModalOpen) {
                    const modalInstance = bootstrap.Modal.getInstance(importModal);
                    if (!modalInstance) {
                        const newModal = new bootstrap.Modal(importModal);
                        newModal.show();
                    } else if (!importModal.classList.contains('show')) {
                        modalInstance.show();
                    }

                    setTimeout(() => {
                        if (!$.fn.DataTable.isDataTable('#tablesaw-350')) {
                            loadDataTable();
                        }
                    }, 100);
                }
            });

            document.querySelectorAll('.select2-container').forEach(select => {
                select.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            if (document.getElementById('importModal')) {
                initImportCausalSelect();
            }

            Livewire.on('load-select', function() {
                if (document.getElementById('importModal') &&
                    document.getElementById('importModal').classList.contains('show')) {
                    initImportCausalSelect();
                }
            });

            setupCalculationListeners();
            setupDragAndDrop();

            const recordDetailsModal = document.getElementById('recordDetailsModal');
            if (recordDetailsModal) {
                recordDetailsModal.addEventListener('hidden.bs.modal', function() {
                    setTimeout(function() {
                        window.location.reload();
                    }, 100);
                });
            }
        });

        function pollAttachmentStatus(recordId) {
            const pollInterval = setInterval(function() {
                fetch(`/check-attachment-status/${recordId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'completed') {
                            clearInterval(pollInterval);
                            showSuccess('Allegato caricato con successo!');
                        } else if (data.status === 'failed') {
                            clearInterval(pollInterval);
                            showError('Caricamento allegato fallito');
                        }
                    });
            }, 2000);

            setTimeout(() => clearInterval(pollInterval), 300000);
        }

        function showRecordDetailsModal(record) {
            const modalElement = document.getElementById('recordDetailsModal');
            if (!modalElement) return;

            try {
                let recordDetailsModal = new bootstrap.Modal(modalElement);

                document.getElementById('recordDate').textContent = record.formatted_date || 'N/A';
                document.getElementById('recordPaymentDate').textContent = record.formatted_data_pagamento || 'N/A';
                document.getElementById('recordSupplier').textContent = record.supplier_name || 'N/A';
                document.getElementById('recordPaymentMethod').textContent = record.payment_method_name || 'N/A';
                document.getElementById('recordTotalAmount').textContent = record.formatted_amount || 'N/A';

                const paymentStatusElement = document.getElementById('recordPaymentStatus');
                if (paymentStatusElement) {
                    paymentStatusElement.textContent = record.payment_status || 'N/A';
                    paymentStatusElement.className = 'badge ' + (record.is_paid ? 'bg-success' : 'bg-warning');
                }

                const attachmentPresentDiv = document.getElementById('recordAttachmentPresent');
                const attachmentMissingDiv = document.getElementById('recordAttachmentMissing');
                const attachmentLink = document.getElementById('recordAttachmentLink');
                const attachmentName = document.getElementById('recordAttachmentName');

                if (record.attachment && record.attachment_url) {
                    attachmentPresentDiv.style.display = 'block';
                    attachmentMissingDiv.style.display = 'none';

                    // Configura il link per l'allegato
                    attachmentLink.href = record.attachment_url;

                    // Estrai il nome del file dal percorso
                    let fileName = record.attachment;
                    if (fileName.includes('/')) {
                        fileName = fileName.split('/').pop();
                    }
                    if (fileName.includes('\\')) {
                        fileName = fileName.split('\\').pop();
                    }

                    // Se il nome è troppo lungo, troncalo
                    if (fileName.length > 30) {
                        const extension = fileName.substring(fileName.lastIndexOf('.'));
                        const baseName = fileName.substring(0, fileName.lastIndexOf('.'));
                        fileName = baseName.substring(0, 25) + '...' + extension;
                    }

                    attachmentName.textContent = fileName;

                    // Aggiorna l'icona in base al tipo di file
                    const iconElement = attachmentPresentDiv.querySelector('i.fa-file-pdf');
                    if (fileName.toLowerCase().includes('.pdf')) {
                        iconElement.className = 'fa-solid fa-file-pdf me-2 text-danger';
                    } else if (fileName.toLowerCase().includes('.xml')) {
                        iconElement.className = 'fa-solid fa-file-code me-2 text-info';
                    } else if (fileName.toLowerCase().match(/\.(jpg|jpeg|png|gif|webp)$/)) {
                        iconElement.className = 'fa-solid fa-file-image me-2 text-success';
                    } else if (fileName.toLowerCase().match(/\.(doc|docx)$/)) {
                        iconElement.className = 'fa-solid fa-file-word me-2 text-primary';
                    } else if (fileName.toLowerCase().match(/\.(xls|xlsx|csv)$/)) {
                        iconElement.className = 'fa-solid fa-file-excel me-2 text-success';
                    } else {
                        iconElement.className = 'fa-solid fa-file me-2 text-secondary';
                    }
                } else {
                    // Mostra la sezione senza allegato
                    attachmentPresentDiv.style.display = 'none';
                    attachmentMissingDiv.style.display = 'block';
                }

                // Popola le righe come prima
                const rowsContainer = document.getElementById('recordRowsContainer');
                if (rowsContainer) {
                    rowsContainer.innerHTML = '';

                    if (record.rows && record.rows.length > 0) {
                        record.rows.forEach(function(row, index) {
                            const tr = document.createElement('tr');

                            tr.innerHTML = `
                                <td>${index + 1}</td>
                                <td>${row.note && row.note.trim() !== '' ? row.note : (row.causal_name || 'N/A')}</td>
                                <td>${row.formatted_imponibile || 'N/A'}</td>
                                <td>${row.aliquota_iva ? row.aliquota_iva + '%' : '-'}</td>
                                <td>${row.formatted_imposta || 'N/A'}</td>
                                <td class="fw-bold">${row.formatted_amount || 'N/A'}</td>
                            `;

                            rowsContainer.appendChild(tr);
                        });
                    } else {
                        const tr = document.createElement('tr');
                        tr.innerHTML = '<td colspan="6" class="text-center">Nessuna riga disponibile</td>';
                        rowsContainer.appendChild(tr);
                    }
                }

                recordDetailsModal.show();

            } catch (error) {
                console.error('Error displaying modal:', error);
            }
        }

        // Aggiungere questo listener per gestire i cambi di stato del campo commercial
        document.addEventListener('livewire:load', function() {
            // Listener per il cambio del radio button commerciale/non commerciale
            const commercialRadios = document.querySelectorAll('input[name="commercial"]');
            commercialRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    console.log('Commercial value changed to:', this.value);
                    // Il campo numero fattura sarà nascosto/mostrato automaticamente da Livewire
                });
            });
        });

        // Listener per gli aggiornamenti di Livewire
        document.addEventListener('livewire:update', function() {
            // Re-attach listeners dopo gli aggiornamenti di Livewire
            const commercialRadios = document.querySelectorAll('input[name="commercial"]');
            commercialRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    console.log('Commercial value changed to:', this.value);
                });
            });
        });
    </script>
@endpush
