<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">@if(!$add && !$update)SMS Templates @else Inserimento/modifica template SMS @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>

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

        <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">Oggetto</th>
                        <th scope="col">Messaggio</th>
                        <th scope="col">Caratteri</th>
                        <th scope="col">Data Creazione</th>
                        <th scope="col">...</th>
                    </tr>
                </thead>
                <tbody id="checkall-target">
                    @foreach($records as $record)
                        <tr>
                            <td>
                                <strong>{{$record->name}}</strong>
                            </td>
                            <td>
                                {{ Str::limit($record->content, 50) }}
                            </td>
                            <td>
                                @php
                                    $length = strlen($record->content);
                                    $badgeClass = $length > 160 ? 'bg-danger' : ($length > 140 ? 'bg-warning' : 'bg-success');
                                @endphp
                                <span class="badge {{ $badgeClass }}">{{ $length }}/160</span>
                            </td>
                            <td>{{ $record->created_at->format('d/m/Y H:i') }}</td>
                            <td>
                                <button type="button" class="btn" wire:click="sendTemplate({{ $record->id }})" data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Invia SMS"><i class="fa-solid fa-paper-plane"></i></button>
                                <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>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </section>

    @else

        <div class="container">

            <a class="btn--ui lightGrey" href="/sms_comunications"><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

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

                    <form action="">

                        <div class="row mb-3">
                            <div class="col">
                                <div class="form--item">
                                    <label for="subject" class="form-label">Oggetto</label>
                                    <input type="text" class="form-control @error('subject') is-invalid @enderror" id="subject" wire:model="subject" placeholder="Inserisci l'oggetto del template">
                                    @error('subject')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col">
                                <div class="form--item">
                                    <label for="message" class="form-label">Messaggio</label>
                                    <textarea class="form-control @error('message') is-invalid @enderror" id="message" wire:model="message" rows="4" placeholder="Inserisci il contenuto del messaggio (max 160 caratteri)" maxlength="160"></textarea>
                                    <div class="form-text">
                                        Caratteri: <span class="fw-bold">{{ strlen($message) }}</span>/160
                                        @if(strlen($message) > 160)
                                            <span class="text-danger"> - Troppi caratteri!</span>
                                        @endif
                                    </div>
                                    @error('message')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        @if($add)
                        <div class="row mb-3">
                            <div class="col">
                                <label class="form-label">Destinatari</label>
                                <div class="mb-2">
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAllUsers()">
                                        <i class="fas fa-users me-1"></i>Seleziona Tutti
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm ms-2" onclick="deselectAllUsers()">
                                        <i class="fas fa-times me-1"></i>Deseleziona Tutti
                                    </button>
                                </div>
                                <div style="max-height: 200px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 0.375rem; padding: 10px;">
                                    @foreach($members as $member)
                                        <div class="form-check mb-1">
                                            <input class="form-check-input" type="checkbox" value="{{ $member->id }}" wire:model="selectedRecipients" id="recipient_{{ $member->id }}">
                                            <label class="form-check-label" for="recipient_{{ $member->id }}">
                                                <strong>{{ $member->last_name }}</strong>
                                                @if($member->phone)
                                                    <small class="text-muted">({{ $member->phone }})</small>
                                                @else
                                                    <small class="text-danger">(no phone)</small>
                                                @endif
                                            </label>
                                        </div>
                                    @endforeach
                                </div>
                                <div class="form-text">
                                    <small class="text-muted">Selezionati: <span id="selectedCount">{{ count($selectedRecipients) }}</span> utenti</small>
                                </div>
                                @error('selectedRecipients')
                                    <div class="text-danger">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col">
                                <label class="form-label">Opzioni di Invio</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="sendOption" id="sendNow" wire:model="sendNow" value="true">
                                    <label class="form-check-label" for="sendNow">
                                        <i class="fas fa-paper-plane me-2"></i>Invia Immediatamente
                                    </label>
                                </div>
                                <div class="form-check mt-2">
                                    <input class="form-check-input" type="radio" name="sendOption" id="scheduleFor" wire:model="sendNow" value="false">
                                    <label class="form-check-label" for="scheduleFor">
                                        <i class="fas fa-clock me-2"></i>Programma per dopo
                                    </label>
                                </div>
                            </div>
                        </div>

                        @if($sendNow === false || $sendNow === 'false')
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="scheduledDateTime" class="form-label">Data e Ora di Invio</label>
                                <input type="datetime-local" class="form-control @error('scheduledDateTime') is-invalid @enderror" id="scheduledDateTime" wire:model="scheduledDateTime">
                                @error('scheduledDateTime')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        @endif
                        @endif

                        <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()">
                                    @if($sendNow === false || $sendNow === 'false')
                                        Salva e Invia
                                    @else
                                        Salva e Programma
                                    @endif
                                </button>
                            @endif
                            @if($update)
                                <button type="submit" class="btn--ui" wire:click.prevent="update()">Salva</button>
                            @endif
                        </div>

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

    @endif
</div>

@if (session()->has('success'))
    <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
        {{ session()->get('success') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
@endif

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

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

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

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

            $('#tablesaw-350').DataTable({
                processing: 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 + 'Templates SMS',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'pdfHtml5',
                                        text: '<i class="fa-solid fa-file-pdf"></i>',
                                        action: newexportaction,
                                        title: date_export + 'Templates SMS',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    },
                                    {
                                        extend: 'print',
                                        action: newexportaction,
                                        text: '<i class="fa-solid fa-print"></i>',
                                        title: date_export + 'Templates SMS',
                                        exportOptions: {
                                            columns: ":not(':last')"
                                        }
                                    }
                                ],
                        //         dropup: true
                        //     }
                        // ]
                    },
                    top1B : {
                        pageLength: {
                            menu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "Tutti"]]
                        }
                    },
                    top1C :'search',
                },
                pagingType: 'numbers',
                "language": {
                    "url": "/assets/js/Italian.json"
                },
                "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);
                }
            });
            $('#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")
                });
            });

        }

        function selectAllUsers() {
            $('input[wire\\:model="selectedRecipients"]').prop('checked', true).trigger('change');
            updateSelectedCount();
        }

        function deselectAllUsers() {
            $('input[wire\\:model="selectedRecipients"]').prop('checked', false).trigger('change');
            updateSelectedCount();
        }

        function updateSelectedCount() {
            setTimeout(function() {
                let count = $('input[wire\\:model="selectedRecipients"]:checked').length;
                $('#selectedCount').text(count);
            }, 100);
        }

        // Update count when checkboxes change
        $(document).on('change', 'input[wire\\:model="selectedRecipients"]', function() {
            updateSelectedCount();
        });

    </script>
@endpush
