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

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

        <div class="showFilter" style="display:none">
            <hr size="1">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;"><b>Data</b></div>
                        <div class="col-12 mb-2">
                            <input id="dateFrom" type="date" class="form-control filterFrom">
                        </div>
                        <div class="col-12">
                            <input id="dateTo" type="date" class="form-control filterTo">
                        </div>
                        <div class="col-6 mt-2">
                            <button class="btn--ui lightGrey todayButton" style="width:100%" onclick="setToday('{{date("Y-m-d")}}')">OGGI</button>
                        </div>
                        <div class="col-6 mt-2">
                            <button class="btn--ui lightGrey yesterdayButton" style="width:100%" onclick="setYesterday('{{date("Y-m-d",strtotime("-1 days"))}}')">IERI</button>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Origine</b>
                        </div>
                        <div class="col-12">
                            <select name="search_origin_id" class="form-select filterOrigins" multiple="multiple">
                                @foreach($origins as $origin)
                                    <option value="{{$origin->id}}">{{$origin->name}}
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="row">
                        <div class="col-md-12" style="margin-bottom:10px;">
                            <b>Destinazione</b>
                        </div>
                        <div class="col-12">
                            <select name="search_destination_id" class="form-select filterDestinations" multiple="multiple">
                                @foreach($destinations as $destination)
                                    <option value="{{$destination->id}}">{{$destination->name}}
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-3" 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">
            <table class="table tablesaw tableHead tablesaw-stack table--lista_movimenti tableHead" id="tablesaw-350" width="100%">
                <thead>
                    <tr>
                        <!--<th scope="col"></th>-->
                        <th scope="col">Data di pagamento</th>
                        <th scope="col">Importo</th>
                        <th scope="col">Origine</th>
                        <th scope="col">Destinazione</th>
                        <th scope="col">Causale</th>
                        <th scope="col">...</th>
                    </tr>
                </thead>

                <tbody id="checkall-target"></tbody>
            </table>

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

        </section>

    @else

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

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

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

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

                    </div>

                    <div class="row gx-2 mt-3">
                        <div class="col-md-6" >
                            <span class="title-form d-block w-100">Origine</span>
                            <select class="form-select  @error('origin_id') is-invalid @enderror" aria-label="Seleziona un'origine" wire:model="origin_id" style="width:100%">
                                <option value="">--Seleziona--</option>
                                @foreach($origins as $origin)
                                    <option value="{{$origin->id}}">{{$origin->name}}</option>
                                @endforeach
                            </select>
                            @error('origin_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-md-6" >
                            <span class="title-form d-block w-100">Destinazione</span>
                            <select class="form-select  @error('destination_id') is-invalid @enderror" aria-label="Seleziona una destinazione" wire:model="destination_id" style="width:100%">
                                <option value="">--Seleziona--</option>
                                @foreach($destinations as $destination)
                                    <option value="{{$destination->id}}">{{$destination->name}}</option>
                                @endforeach
                            </select>
                            @error('destination_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="row gx-2 mt-3">
                        <div class="col-md-6" >
                            <span class="title-form d-block w-100">Causale</span>
                            <input class="form-control" id="causal" type="text" placeholder="Causale" wire:model="causal_name" disabled>
                        </div>

                        <div class="col-md-6" >
                            <span class="title-form d-block w-100">Importo</span>
                            <input type="text" class="form-control totalInput text-end @error('amount') is-invalid @enderror" id="amountFormatted" wire:model="amountFormatted" onkeyup="formatEuro(this)" placeholder="€ 0,00">
                            @error('amount')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="row gx-2 mt-3">
                        <div class="col-md-12">
                            <span class="title-form d-block w-100">Note</span>
                            <input type="text" class="form-control @error('notes') is-invalid @enderror" id="notes" wire:model="notes">
                            @error('notes')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>


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

                        @if($add)
                            <button class="btn--ui primary d-flex ms-auto" wire:click.prevent="store()"><span>Inserisci movimento</span></button>
                        @endif
                        @if($update)
                            <button class="btn--ui primary d-flex ms-auto" wire:click.prevent="update()"><span>Aggiorna movimento</span></button>
                        @endif
                    </div>
                </div>
            </div>
        </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>
        [for="dt-search-0"],
        #dt-search-0 {
            display: none;
        }
        table.tableHead thead {
        /* Important */
            position: sticky;
            z-index: 100;
            top: 0;
        }
        .select2-container--default .select2-selection--single{
            background-color: #E9F0F5;
            border: 0.0625rem solid #DFE5EB;
            font-size: 0.75rem;
        }
        .select2-selection
        {
            height: 38px !important;
        }
        .select2-selection__rendered
        {
            padding-top:3px;
        }
        .select2 {
            width:100% !important;
        }
        .page-link.active, .active > .page-link {
            background-color:#006099 !important;
        }

        .select2-selection--multiple{
            overflow: hidden !important;
            height: auto !important;
        }
        .select2-container {
            box-sizing: border-box;
            display: inline-block;
            margin: 0;
            position: relative;
            vertical-align: middle;
        }
        .select2-container .select2-selection--single {
            box-sizing: border-box;
            cursor: pointer;
            display: block;
            height: 38px;
            user-select: none;
            -webkit-user-select: none;
        }
        .select2-container .select2-selection--single .select2-selection__rendered {
            display: block;
            padding-left: 8px;
            padding-right: 20px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        table.tablesaw tbody tr td.numericCol {
            padding-right: 20px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
@endpush

@push('scripts')
    <script>

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

        function matchStart(params, data) {
            params.term = params.term || '';
            if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
                return data;
            }
            return false;
        }

        $(document).ready(function(){

            $(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);
            });

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

        });

        Livewire.on('load-select', () => {
            $('.filterOrigins').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterOrigins').on('change', function (e) {});
            $('.filterDestinations').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
            $('.filterDestinations').on('change', function (e) {});
        });

        $('.filterOrigins').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterOrigins').on('change', function (e) {});
        $('.filterDestinations').select2({"language": {"noResults": function(){return "Nessun risultato";}}});
        $('.filterDestinations').on('change', function (e) {});

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

        function formatEuro(input) {
            let v = input.value.replace(/\D+/g, '');
            if (!v) {
                input.value = '';
                return;
            }

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

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

        @if(isset($_GET["showFilters"]))
            var filterOrigins = localStorage.getItem("filterOriginsFinancialMovements");
            if (filterOrigins && filterOrigins != "null" && filterOrigins != "undefined")
            {
                $('.filterOrigins').val(filterOrigins);
                $('.filterOrigins').trigger('change');
            }
            var filterDestinations = localStorage.getItem("filterDestinationsFinancialMovements");
            if (filterDestinations && filterDestinations != "null" && filterDestinations != "undefined")
            {
                $('.filterDestinations').val(filterDestinations);
                $('.filterDestinations').trigger('change');
            }
            var filterFrom = localStorage.getItem("filterFromFinancialMovements");
            if (filterFrom && filterFrom != "null" && filterFrom != "undefined")
            {
                $('.filterFrom').val(filterFrom);
            }
            var filterTo = localStorage.getItem("filterToFinancialMovements");
            if (filterTo && filterTo != "null" && filterTo != "undefined")
            {
                $('.filterTo').val(filterTo);
            }
        @endif

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

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

        } );

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

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

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

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

        });

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

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

        function reset()
        {
            $(".todayButton").addClass("lightGrey");
            $(".yesterdayButton").addClass("lightGrey");
            $('.filterOrigins').val('');
            $('.filterOrigins').trigger('change');
            $('.filterDestinations').val('');
            $('.filterDestinations').trigger('change');
            $('.filterFrom').val('');
            $('.filterTo').val('');

            loadDataTable();
        }


        function loadDataTable(){

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

            var filterOrigins = $('.filterOrigins').val();
            var filterDestinations = $('.filterDestinations').val();
            var filterFrom = $('.filterFrom').val();
            var filterTo = $('.filterTo').val();

            localStorage.setItem("filterOriginsFinancialMovements", filterOrigins);
            localStorage.setItem("filterDestinationsFinancialMovements", filterDestinations);
            localStorage.setItem("filterFromFinancialMovements", filterFrom);
            localStorage.setItem("filterToFinancialMovements", filterTo);

            var totalString = "";
            $('#tablesaw-350').DataTable({
                serverSide: true,
                processing: true,
                ajax: {
                    url : '/get_financial_movements?&filterOrigins=' + filterOrigins + '&filterDestinations=' + filterDestinations + '&filterFrom=' + filterFrom + '&filterTo=' + filterTo,
                    dataSrc: function (json){
                        if(json.totals){
                            $(".totalDiv").html('Totale&nbsp;:&nbsp;<b>' + json.totals + '</b>');
                        }
                        else
                        {
                            $(".totalDiv").html('');
                        }
                        @if(Auth::user()->level != 0)
                            $(".totalDiv").html('');
                        @endif
                        return json.data;
                    }
                },
                columns: [
                    // { data: 'id' },
                    {
                        data: "date",
                        render: function (data, type){
                            if (data == "") return " ";
                            if (type == "sort"){
                                return new Date(data).getTime();
                            }
                            const j = data.split(" ");
                            const d = j[0].split("-");
                            var ret = d[2] + "/" + d[1] + "/" + d[0];
                            return ret;
                        },
                    },
                    { data: 'total', className: "numericCol" },
                    { data: 'origin' },
                    { data: 'destination' },
                    { data: 'causal', "orderable": false, },
                    {
                        data: "action",
                        render: function (data){
                            if (data == "")
                                return "";
                            const j = data.split("|");
                            var ret = '';
                            if (j[2] != 'x')
                            {
                                ret = '<button type="button" class="btn" onclick="editData(' + j[0] + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Modifica"><i class="fa-regular fa-pen-to-square"></i></button>&nbsp;';
                                ret += '<button type="button" class="btn" onclick="deleteData(' + j[0] + ')"  data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Elimina"><i class="fa-regular fa-trash-can"></i></button>';
                                ret += '<button type="button" class="btn btn-outline-default btn-sm" onclick="duplicateData(' + j[0] + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Duplica"><i class="fa-regular fa-copy"></i></button>';
                            }
                            else
                            {
                                ret = '<button type="button" class="btn" onclick="editData(' + j[0] + ')" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Visualizza"><i class="fa-regular fa-file"></i></button>&nbsp;';
                            }
                            return ret;
                        }
                    },
                ],
                fixedHeader: false,
                order: [[0, 'desc']],
                thead: {
                'th': {'background-color': 'blue'}
                },
                layout: {
                    topStart : null,
                    topEnd : null,
                    top1A: {
                        buttons: [
                            {
                                extend: 'collection',
                                text: 'ESPORTA',
                                buttons: [
                                    {
                                    extend: 'excelHtml5',"action":newexportaction,
                                        title: 'Movimenti finanziari',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'pdfHtml5',"action":newexportaction,
                                        title: 'Movimenti finanziari',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'print',"action":newexportaction,
                                        text: 'Stampa',
                                        title: 'Movimenti finanziari',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    }
                                ],
                                dropup: true
                            }
                        ]
                    },
                    top1B : {
                        pageLength: {
                            menu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "Tutti"]]
                        }
                    },
                    top1C :'search',
                    bottomEnd: {
                        paging: {
                            boundaryNumbers: false
                        }
                    }
                },
                pagingType: 'first_last_numbers',
                language: {
                    "url": "/assets/js/Italian.json",
                    paginate: {
                        first: '<i class="fa-solid fa-angles-left"></i>',
                        last: '<i class="fa-solid fa-angles-right"></i>',
                    }
                },
                "fnInitComplete": function (oSettings, json) {
                    var html = '&nbsp;<a href="#" class="showHideFilter btn--ui"><i class="fa-solid fa-sliders"></i></a>';
                    html += '&nbsp;<a  style="cursor:pointer" class="addData btn--ui"><i class="fa-solid fa-plus"></i></a>';
                    $(".dt-search").append(html);
                }
            });
            $('#tablesaw-350 thead tr th').addClass('col');
            $('#tablesaw-350 thead tr th').css("background-color", "#f6f8fa");
            $('#tablesaw-350').on('draw.dt', function() {
                $('[data-bs-toggle="popover"]').popover()
            });

        }

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

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

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

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

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

@endpush