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

        <a class="btn--ui lightGrey" href="/settings?type=corsi"><i class="fa-solid fa-arrow-left"></i></a><br>

        <section id="resume-table">
            <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
                <thead>
                    <tr>
                        <th  style="text-align:center" scope="col"><input type="checkbox" class="checkAll"></th>
                        <th scope="col">Nome</th>
                        <th scope="col">N° partecipanti</th>
                        <th scope="col">...</th>
                    </tr>
                </thead>
                <tbody id="checkall-target">
                    @foreach($records as $record)
                        <tr>
                            <td style="text-align:center"><input type="checkbox" class="chkCourse" name="{{$record->id}}"></td>
                            <td>{{$record->name}}</td>
                            <td style="padding-right: 50px">{{$record->getCount()}}</td>
                            <td>
                                <button type="button" class="btn" wire:click="edit({{ $record->id }})" 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>
                                <button type="button" class="btn" onclick="confirm('Sei sicuro?') || event.stopImmediatePropagation()" wire:click="delete({{ $record->id }})" 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>
                                <button type="button" class="btn" wire:click="duplicate({{ $record->id }}, false)" 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>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </section>

    @else

        <a class="btn--ui lightGrey" href="/subscriptions"><i class="fa-solid fa-arrow-left"></i></a><br>

        <div class="container">

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

            <div class="row">
                <div class="col">

                    <form action="">

                        <div class="row mb-3 ">
                            <div class="col-6 mt-2">
                                <div class="form--item">
                                    <label for="inputName" class="form-label">Nome</label>
                                    <input class="form-control js-keyupTitle @error('name') is-invalid @enderror" type="text" id="name" placeholder="Nome" wire:model="name">
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-6 mt-2">
                                <div class="form--item">
                                    <label for="enabled" class="form-label">Abilitato</label>
                                    <input class="form-check-input form-control" style="width:22px; height:22px;" type="checkbox" id="enabled" wire:model="enabled">
                                </div>
                            </div>
                            
                            {{-- <div class="col-3 mt-2">
                                <div class="form--item">
                                    <label for="inputName" class="form-label">Data inizio</label>
                                    <input class="form-control @error('date_from') is-invalid @enderror" type="date" placeholder="Data inizio" wire:model="date_from">
                                </div>
                            </div>
                            <div class="col-3 mt-2">
                                <div class="form--item">
                                    <label for="inputName" class="form-label">Data fine</label>
                                    <input class="form-control @error('date_to') is-invalid @enderror" type="date" placeholder="Data fine" wire:model="date_to">
                                </div>
                            </div> --}}

                            <div class="col-6 mt-2">
                                <div class="form--item">
                                    <label for="inputName" class="form-label">Prezzo iscrizione</label>
                                    <input class="form-control js-keyupTitle @error('subscription_price') is-invalid @enderror" type="text" id="subscription_price" onkeyup="onlyNumberAmount(this)" placeholder="€ 0,00" wire:model="subscription_price">
                                    @error('subscription_price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-6 mt-2">
                                @foreach($prices as $idP => $p)
                                    <div class="row mt-2 ">
                                        <div class="col-6">
                                            <label for="abb" class="form-label">Pagamento</label>
                                            <select class="form-control" wire:model="prices.{{$idP}}.course_subscription_id">
                                                <option value=""></option>
                                                @foreach($course_subscriptions as $s)
                                                    <option value="{{$s["id"]}}">{{$s["name"]}}
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-4">
                                            <label for="price" class="form-label">Prezzo</label>
                                            <input class="form-control " type="text" onkeyup="onlyNumberAmount(this)" placeholder="€ 0,00" wire:model="prices.{{$idP}}.price">
                                        </div>
                                        <div class="col-2">
                                            @if($idP == 0)
                                                <br><button class="btn--ui primary add--daye" wire:click.prevent="addPrice()"><i class="fa-solid fa-plus"></i></button>
                                            @endif
                                            @if($idP > 0)
                                                <br><button class="btn--ui primary add--daye" wire:click.prevent="delPrice({{$idP}})"><i class="fa-solid fa-minus"></i></button>
                                            @endif
                                        </div>
                                        <div class="col-12">
                                            <span style="color:red">{{$msgPrices}}</span>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>

                        <div class="form--item mt-4">
                            <button type="button" class="btn--ui lightGrey" onclick="annulla()">Annulla</button>
                            @if($add)
                                <button type="submit" class="btn--ui" wire:click.prevent="store()">Salva</button>
                            @endif
                            @if($update)
                                <button type="submit" class="btn--ui" wire:click.prevent="update()">Salva</button>
                            @endif
                        </div>

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

    @endif
</div>

@push('scripts')
    <link href="/css/datatables.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <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>
@endpush

@push('scripts')
    <script>
        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.');
        }

        var isEdit = false;

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

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

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

        };

        $(document).ready(function() {
            loadDataTable();
        } );

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

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

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

            $('#tablesaw-350').DataTable({
                processing: true,
                stateSave: true,
                thead: {
                'th': {'background-color': 'blue'}
                },
                layout: {
                    topStart : null,
                    topEnd : null,
                    top1A: {
                        buttons: [
                            {
                                extend: 'excelHtml5',
                                text: '<i class="fa-solid fa-file-excel"></i>',
                                action: newexportaction,
                                title: date_export + 'Abbonamenti',
                                filename: date_export + 'Abbonamenti',
                                exportOptions: {
                                    columns: ":not(':last')"
                                }
                            },
                            {
                                extend: 'pdfHtml5',
                                text: '<i class="fa-solid fa-file-pdf"></i>',
                                action: newexportaction,
                                title: date_export + 'Abbonamenti',
                                filename: date_export + 'Abbonamenti',
                                exportOptions: {
                                    columns: ":not(':last')"
                                }
                            },
                            {
                                extend: 'print',
                                action: newexportaction,
                                text: '<i class="fa-solid fa-print"></i>',
                                title: date_export + 'Abbonamenti',
                                filename: date_export + 'Abbonamenti',
                                exportOptions: {
                                    columns: ":not(':last')"
                                }
                            }
                        ],
                    },
                    top1B : {
                        pageLength: {
                            menu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "Tutti"]]
                        }
                    },
                    top1C :'search',
                    bottomEnd: {
                        paging: {
                            boundaryNumbers: false
                        }
                    }
                },
                columnDefs: [
                    {
                        targets: 0,
                        orderable: 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="addData btn--ui"><i class="fa-solid fa-plus"></i></a>';
                    $(".dt-search").append(html);
                    html = '&nbsp;<a href="#" class="duplicateData btn--ui" style="display:none"><i class="fa-solid fa-copy fa-lg" style="height:5px;"></i></a>';
                    $(".dt-buttons").after(html);
                }
            });
            $('#tablesaw-350 thead tr th').addClass('col');
            $('#tablesaw-350 thead tr th').css("background-color", "#f6f8fa");

            var subscriptions = [];
            $(".chkCourse").click(function(){
                var id = $(this).attr('name');
                if(!subscriptions.includes(id)){
                    subscriptions.push(id);
                }else{
                    subscriptions.splice(subscriptions.indexOf(id), 1);  //deleting
                }
                if (subscriptions.length > 0)
                    $(".duplicateData").show();
                else
                    $(".duplicateData").hide();
            });

            $(document).ready(function() {
                $(document).on("click",".addData",function() {
                    $(".title--section_addButton").trigger("click");
                });
                $(document).on("click",".duplicateData",function() {
                    @this.duplicateMultiple(subscriptions);
                });
            } );

            var all = false;
            $(".checkAll").click(function(){
                all = !all;
                subscriptions = [];
                $('.chkCourse').each(function(){
                    $(this).prop('checked', all);
                    if (all)
                        subscriptions.push($(this).attr('name'));
                });
                if (subscriptions.length > 0)
                    $(".duplicateData").show();
                else
                    $(".duplicateData").hide();
            });
        }
    </script>
@endpush