<div class="col card--ui" id="card--dashboard">
    @if(!$add && !$update)

        <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">Utenti</h2>
            </div>

            @if(Auth::user()->level == 0)
                <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>

        <!-- Success/Error Messages -->
        @if (session()->has('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session()->get('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

        @if (session()->has('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ session()->get('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

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

            <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
                <thead>
                    <tr>
                        <th scope="col">Cognome</th>
                        <th scope="col">Nome</th>
                        <th scope="col">Email</th>
                        <th scope="col">Livello</th>
                        <th scope="col">Abilitato</th>
                        <th scope="col">...</th>
                    </tr>
                </thead>
                <tbody id="checkall-target">
                    @foreach($records as $record)
                        <tr>
                            <td>{{$record->cognome}}</td>
                            <td>{{$record->name}}</td>
                            <td>{{$record->email}}</td>
                            <td>{{$record->level == 0 ? 'Admin' : ($record->level == 1 ? 'Worker' : 'Istruttore')}}</td>
                            <td> <span class="tablesaw-cell-content"><span class="badge tessera-badge {{$record->enabled ? 'active' : 'suspended'}}">{{$record->enabled ? 'attivo' : 'disattivo'}}</span></span></td>
                            <td>
                                @php
                                    $currentUser = Auth::user();
                                    $isCurrentUser = $record->master_user_id == $currentUser->id;
                                    $isAdmin = $currentUser->level == 0;
                                    // $canEdit = $record->email != 'admin@admin.com' && ($isAdmin || $isCurrentUser);
                                    $canEdit = ($isAdmin || $isCurrentUser);
                                    // $canDelete = $record->email != 'admin@admin.com' && $isAdmin && !$isCurrentUser;
                                    $canDelete = $isAdmin && !$isCurrentUser;
                                @endphp

                                @if($canEdit)
                                    <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>
                                @endif

                                @if($canDelete)
                                    <button type="button" class="btn delete-user-btn" data-user-id="{{ $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>
                                @endif
                            </td>
                        </tr>
                    @endforeach

                </tbody>
            </table>

        </section>

    @else
    <a class="btn--ui lightGrey" href="/users"><i class="fa-solid fa-arrow-left"></i></a><br><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-md-6">
                                <div class="form--item">
                                    <label for="name" 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-md-6">
                                <div class="form--item">
                                    <label for="name" class="form-label">Cognome</label>
                                    <input class="form-control js-keyupTitle @error('cognome') is-invalid @enderror" type="text" id="cognome" placeholder="Cognome" wire:model="cognome">
                                    @error('cognome')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            @php
                                $currentUser = Auth::user();
                                $isEditingOwnProfile = false;
                                if (isset($dataId)) {
                                    $currentTenantUser = \App\Models\User::where('master_user_id', $currentUser->id)->first();
                                    if ($currentTenantUser) {
                                        $isEditingOwnProfile = $update && $currentTenantUser->id == $dataId;
                                    }
                                }
                                $canEditEmailAndPassword = $add || $isEditingOwnProfile;
                            @endphp

                            @if($canEditEmailAndPassword)
                                <div class="col-md-6 mt-3">
                                    <div class="form--item">
                                        <label for="email" class="form-label">Email</label>
                                        <input class="form-control js-keyupTitle @error('email') is-invalid @enderror" type="text" id="email" placeholder="Email" wire:model="email" type="email">
                                        @error('email')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            @else
                                <div class="col-md-6 mt-3">
                                    <div class="form--item">
                                        <label for="email" class="form-label">Email</label>
                                        <input class="form-control" type="text" id="email" value="{{ $email }}" disabled>
                                        <small class="text-muted">Solo l'utente può modificare la propria email</small>
                                    </div>
                                </div>
                            @endif

                            <div class="col-md-6 mt-3">
                                <div class="form--item">
                                    <label for="enabled" class="form-label">Livello</label>
                                    <select class="form-control" id="level" wire:model="level">
                                        <option value="0">Admin
                                        <option value="1">Worker
                                        <option value="2">Istruttore
                                    </select>
                                </div>
                            </div>

                            @if ($add)
                                <div class="col-md-6 mt-3">
                                    <div class="form--item">
                                        <label for="password" class="form-label">Password</label>
                                        <div class="password-wrapper">
                                            <input class="form-control js-keyupTitle @error('password') is-invalid @enderror" type="password" id="password" placeholder="Password" wire:model="password">
                                            <div class="password-eye" onclick="togglePassword(this)">
                                                <i class="fas fa-eye password-hidden"></i>
                                                <i class="fas fa-eye-slash password-shown"></i>
                                            </div>
                                        </div>
                                        @error('password')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6 mt-3">
                                    <div class="form--item">
                                        <label for="password_confirmation" class="form-label">Conferma password</label>
                                        <div class="password-wrapper">
                                            <input class="form-control js-keyupTitle @error('password_confirmation') is-invalid @enderror" type="password" id="password_confirmation" placeholder="Ripeti password" wire:model="password_confirmation">
                                            <div class="password-eye" onclick="togglePassword(this)">
                                                <i class="fas fa-eye password-hidden"></i>
                                                <i class="fas fa-eye-slash password-shown"></i>
                                            </div>
                                        </div>
                                        @error('password_confirmation')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            @elseif($canEditEmailAndPassword)
                                <div class="col-md-6 mt-3">
                                    <div class="form--item">
                                        <label for="password" class="form-label">Password</label>
                                        <div class="password-wrapper">
                                            <input class="form-control js-keyupTitle @error('password') is-invalid @enderror" type="password" id="password" placeholder="Password" wire:model="password">
                                            <div class="password-eye" onclick="togglePassword(this)">
                                                <i class="fas fa-eye password-hidden"></i>
                                                <i class="fas fa-eye-slash password-shown"></i>
                                            </div>
                                        </div>
                                        <small>Lasciare vuota per NON modificarla</small>
                                        @error('password')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6 mt-3">
                                    <div class="form--item">
                                        <label for="password_confirmation" class="form-label">Conferma password</label>
                                        <div class="password-wrapper">
                                            <input class="form-control js-keyupTitle @error('password_confirmation') is-invalid @enderror" type="password" id="password_confirmation" placeholder="Ripeti password" wire:model="password_confirmation">
                                            <div class="password-eye" onclick="togglePassword(this)">
                                                <i class="fas fa-eye password-hidden"></i>
                                                <i class="fas fa-eye-slash password-shown"></i>
                                            </div>
                                        </div>
                                        @error('password_confirmation')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            @else
                                <div class="col-md-6 mt-3">
                                    <div class="form--item">
                                        <label for="password" class="form-label">Password</label>
                                        <input class="form-control" type="password" value="********" disabled>
                                        <small class="text-muted">Solo l'utente può modificare la propria password</small>
                                    </div>
                                </div>
                            @endif

                        </div>
                        <div class="row mt-3 mb-3">
                            <div class="col-md-6">
                                <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>

                        <div class="form--item">
                            <button type="button" class="btn--ui lightGrey" wire:click="cancel()">Annulla</button>
                            @if($add)
                                <button type="submit" class="btn--ui" wire:click.prevent="store()">Invita</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>

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

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

        Livewire.on('userDeleted', () => {
            setTimeout(function() {
                location.reload();
            }, 1500);
        });

        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: 'collection',
                        //         text: 'ESPORTA',
                                buttons: [
                                    {
                                        extend: 'excelHtml5',
                                        text: '<i class="fa-solid fa-file-excel"></i>',
                                        action: newexportaction,
                                        title: date_export + 'Utenti',
                                        filename: date_export + 'Utenti',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'pdfHtml5',
                                        text: '<i class="fa-solid fa-file-pdf"></i>',
                                        action: newexportaction,
                                        title: date_export + 'Utenti',
                                        filename: date_export + 'Utenti',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'print',
                                        action: newexportaction,
                                        text: '<i class="fa-solid fa-print"></i>',
                                        title: date_export + 'Utenti',
                                        filename: date_export + 'Utenti',
                                        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) {
                    @if(Auth::user()->level == 0)
                        var html = '&nbsp;<a href="#" class="addData btn--ui"><i class="fa-solid fa-plus"></i></a>';
                        $(".dt-search").append(html);
                    @endif
                }
            });
            $('#tablesaw-350 thead tr th').addClass('col');
            $('#tablesaw-350 thead tr th').css("background-color", "#f6f8fa");

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

                $(document).on("click", ".delete-user-btn", function(e) {
                    e.preventDefault();

                    var userId = $(this).data('user-id');
                    var userRow = $(this).closest('tr');
                    var userName = userRow.find('td:eq(1)').text();
                    var userSurname = userRow.find('td:eq(0)').text();

                    if (confirm('Sei sicuro di voler eliminare l\'utente ' + userName + ' ' + userSurname + '?')) {
                        $(this).prop('disabled', true);
                        $(this).html('<i class="fa fa-spinner fa-spin"></i>');

                        @this.call('delete', userId);
                    }
                });
            });
        }

    </script>
@endpush
