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



        <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">
                    <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"></th>-->
                        <th scope="col">Data pagamento</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">...</th>
                    </tr>
                </thead>

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


            <!--
            <div class="paginator d-flex justify-content-center">
                <nav aria-label="Page navigation example">
                    <ul class="pagination">
                        <li class="page-item">
                        <a class="page-link" href="#" aria-label="Previous">
                            <span aria-hidden="true"></span>
                        </a>
                        </li>
                        <li class="page-item"><a class="page-link" href="#">1</a></li>
                        <li class="page-item"><a class="page-link" href="#">2</a></li>
                        <li class="page-item"><a class="page-link" href="#">3</a></li>
                        <li class="page-item"><a class="page-link" href="#">3</a></li>

                        <li class="page-item"><span class="more-page">...</span></li>

                        <li class="page-item">
                        <a class="page-link" href="#" aria-label="Next">
                            <span aria-hidden="true"></span>
                        </a>
                        </li>
                    </ul>
                    </nav>
            </div>
            -->

            <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-12">
                                    <div class="check--invoice d-flex align-items-center">
                                        <div class="form-check me-3">
                                            <input class="form-check-input" type="radio" value="1" wire:model="commercial" 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>

                            <div class="col-md-6">
                                <span class="title-form d-block w-100 text-right">Data di Pagamento</span>
                                <div class="input-group mb-3">
                                    <input id="date" type="date" class="form-control"  wire:model="date">
                                </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>

                        @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" :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">
                                    <input class="form-control " type="text" placeholder="Dettaglio causale" wire:model="rows.{{$idx}}.note">
                                </div>
                            </div>


                            <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>
            @if(false)
            <div class="accountingExit_resume card--ui">
                <header>
                    <div class="username d-flex align-items-start">
                        <i class="ico--ui accountingResume me-2"></i>
                        <div class="user--resume_name d-flex flex-column"><span class="primary">Ricevuta</span></div></div>
                </header>

                <div class="resume--body d-flex justify-content-between flex-column">
                    <header>
                        @if($this->supplier)
                            <ul class="resume-item mb-4 p-0">
                                <li><span class="evidence_name">{{$this->supplier->name}}</span></li>
                                <li><span>P.IVA: {{$this->supplier->vat}}</span></li>
                            </ul>
                        @endif
                        <ul class="resume-item date p-0">
                            <li><strong>Data di Pagamento</strong></li>
                            <li>{{ date("d/m/Y", strtotime($date)) }}</li>
                        </ul>
                        @if($this->causal)
                            <ul class="resume-item date p-0">
                                <li><strong>Causale</strong></li>
                                <li>{{$this->causal->getTree()}}</li>
                            </ul>
                        @endif

                    </header>

                    <footer>
                        <div class="total--wrapper">
                            <div class="total--wrapper_amount d-flex align-items-center justify-content-between w-100 mb-3">
                                <span class="amount_p"><strong>Importo</strong></span><span class="amount_data"><strong>{{$amount}}</strong></span>
                            </div>
                            <!--<div class="total--wrapper_tax d-flex align-items-center justify-content-between w-100 mb-2 pb-3">
                                <span class="taxt_p">IVA (22%):</span><span class="tax_data">€ 22,00</span>
                            </div>-->
                            <div class="total--wrapper_netprice d-flex align-items-center justify-content-between w-100">
                                <span class="netprice_p"><strong>Totale Netto</strong></span><span class="netprice_data"><strong>{{$amount}}</strong></span>
                            </div>
                        </div>
                    </footer>
                </div>
            </div>
            @endif
        </section>

    @endif
</div>

@push('scripts')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        table.tableHead thead {
            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;
        }
        .select2-container {
            box-sizing: border-box;
            display: inline-block;
            margin: 0;
            position: relative;
            vertical-align: middle;
        }
        .select2-container .select2-selection--single {
            box-sizing: border-box;
            cursor: pointer;
            display: block;
            height: 38px;
            user-select: none;
            -webkit-user-select: none;
        }
        .select2-container .select2-selection--single .select2-selection__rendered {
            display: block;
            padding-left: 8px;
            padding-right: 20px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    </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;
        }
        window.livewire.on('refresh', () => {
            $('.causalClass').select2({
                    matcher: function(params, data) {
                        return matchStart(params, data);
                    }
                });
            $('.supplierClass').select2({
                    /*matcher: function(params, data) {
                        return matchStart(params, data);
                    }*/
                });
            $('.paymentClass').select2({
                    matcher: function(params, data) {
                        return matchStart(params, data);
                    }
                });
        });

        $(document).ready(function(){

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

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

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

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

        });

        Livewire.on('load-select', () => {
            
            $('.causalClass').each(function(i, obj) {
                $(obj).select2({"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({
                    /*matcher: function(params, data) {
                        return matchStart(params, data);
                    }*/
                });
            $('.supplierClass').on('change', function (e) {
                loadDiv();
                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) {
                loadDiv();
                var data = $('.paymentClass').select2("val");
                @this.set('payment_method_id', data);
            });

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

        });

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

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

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

        @if(isset($_GET["showFilters"]))
            var filterSupplier = localStorage.getItem("filterSupplierRecordOut");
            if (filterSupplier && filterSupplier != "null" && filterSupplier != "undefined")
            {
                console.log("1");
                console.log(filterSupplier);
                $('.filterSupplier').val(filterSupplier);
                $('.filterSupplier').trigger('change');
            }
            var filterPaymentMethod = localStorage.getItem("filterPaymentMethodRecordOut");
            if (filterPaymentMethod && filterPaymentMethod != "null" && filterPaymentMethod != "undefined")
            {
                console.log("2");
                $('.filterPaymentMethod').val(filterPaymentMethod);
                $('.filterPaymentMethod').trigger('change');
            }
            var filterCausals = localStorage.getItem("filterCausalsRecordOut");
            if (filterCausals && filterCausals != "null" && filterCausals != "undefined")
            {
                console.log("3");
                $('.filterCausals').val(filterCausals);
                $('.filterCausals').trigger('change');
            }
            var filterOrigins = localStorage.getItem("filterOriginsRecordOut");
            if (filterOrigins && filterOrigins != "null" && filterOrigins != "undefined")
            {
                console.log("3");
                $('.filterOrigins').val(filterOrigins);
                $('.filterOrigins').trigger('change');
            }
            var filterFrom = localStorage.getItem("filterFromRecordOut");
            if (filterFrom && filterFrom != "" && filterFrom != "undefined")
            {
                console.log("4");
                $('.filterFrom').val(filterFrom);
            }
            var filterTo = localStorage.getItem("filterToRecordOut");
            if (filterTo && filterTo != "" && filterTo != "undefined")
            {
                console.log("5");
                $('.filterTo').val(filterTo);
            }
        @endif

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

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

        } );

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

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

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

        });

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

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

        function reset()
        {
            $(".todayButton").addClass("lightGrey");
            $(".yesterdayButton").addClass("lightGrey");
            $('.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);

            $('#tablesaw-350').DataTable({
                //searching: false,
                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: "date",
                        render: function (data, type){
                            if (data == "")
                                return " TOTALE";
                            if (type == "sort"){
                                return new Date(data).getTime();
                            }
                            // Split class and text
                            const j = data.split(" ");
                            const d = j[0].split("-");
                            var ret = d[2] + "/" + d[1] + "/" + d[0];
                            return ret;
                        }, className: "numericCol"
                    },
                    { data: 'total', className: "numericCol" },
                    { data: 'supplier' },
                    { data: 'causals' },
                    { data: 'payment' },
                    { data: 'origin' },
                    {
                        data: "action",
                        render: function (data){
                            if (data == "")
                                return "";
                            const j = data.split("|");
                            //$(".totalDiv").html('Totale&nbsp;:&nbsp;<b>' + j[1] + '</b>');
                            //$(".total").html('Totale&nbsp;:&nbsp;<b>' + j[1] + '</b>');
                            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="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: [[0, 'desc']],
                thead: {
                'th': {'background-color': 'blue'}
                },
                layout: {
                    topStart : null,
                    topEnd : null,
                    top1A: {
                        buttons: [
                            {
                                extend: 'collection',
                                text: 'ESPORTA',
                                buttons: [
                                    {
                                    extend: 'excelHtml5',"action":newexportaction,
                                        title: 'Uscite',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'pdfHtml5',"action":newexportaction,
                                        title: 'Uscite',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'print',"action":newexportaction,
                                        text: 'Stampa',
                                        title: '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).ready(function() {
            $(document).on("click",".addData",function() {
                $(".title--section_addButton").trigger("click")
            });
        } );

        var isEdit = false;

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

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

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

        };

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

    </script>

@endpush
