@extends('layouts.adminlte')
@section('title', 'Impostazioni Email')
@section('page_title', 'Configurazione Email')

@section('breadcrumbs')
<li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
<li class="breadcrumb-item"><a href="/impostazioni">Impostazioni</a></li>
<li class="breadcrumb-item active">Email Settings</li>
@endsection

@section('content')
<div class="row">
    <div class="col-md-3">
        <div class="card card-secondary">
            <div class="card-header">
                <h3 class="card-title">Sezioni</h3>
            </div>
            <div class="list-group list-group-flush">
                <a href="#imap" class="list-group-item list-group-item-action active" data-toggle="tab">
                    <i class="nav-icon fas fa-server"></i> Server IMAP
                </a>
                <a href="#smtp" class="list-group-item list-group-item-action" data-toggle="tab">
                    <i class="nav-icon fas fa-paper-plane"></i> Server SMTP (Invio)
                </a>
                <a href="#account" class="list-group-item list-group-item-action" data-toggle="tab">
                    <i class="nav-icon fas fa-user"></i> Account
                </a>
                <a href="#sync" class="list-group-item list-group-item-action" data-toggle="tab">
                    <i class="nav-icon fas fa-sync"></i> Sincronizzazione
                </a>
                <a href="#signature" class="list-group-item list-group-item-action" data-toggle="tab">
                    <i class="nav-icon fas fa-signature"></i> Firma
                </a>
                <a href="#mittenti" class="list-group-item list-group-item-action" data-toggle="tab">
                    <i class="nav-icon fas fa-user-plus"></i> Mittenti Aggiuntivi
                </a>
            </div>
        </div>
    </div>
    <div class="col-md-9">
        <form method="POST" action="{{ route('impostazioni.email.save') }}">
            @csrf
            <input type="hidden" name="id" value="{{ $settings->id ?? 1 }}">
            
            <div class="tab-content">
                <div class="tab-pane active" id="imap">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">Configurazione Server IMAP</h3>
                        </div>
                        <div class="card-body">
                            @if(session('success'))
                                <div class="alert alert-success">{{ session('success') }}</div>
                            @endif
                            @if(session('error'))
                                <div class="alert alert-danger">{{ session('error') }}</div>
                            @endif

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="imap_host">Host IMAP</label>
                                        <input type="text" name="imap_host" id="imap_host" class="form-control" 
                                               value="{{ $settings->imap_host ?? 'imap.gmail.com' }}"  
                                               placeholder="es. imap.gmail.com">
                                        <small class="text-muted">Gmail: imap.gmail.com | Outlook: outlook.office365.com</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="imap_port">Porta</label>
                                        <input type="number" name="imap_port" id="imap_port" class="form-control" 
                                               value="{{ $settings->imap_port ?? 993 }}">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="imap_encryption">Crittografia</label>
                                        <select name="imap_encryption" id="imap_encryption" class="form-control">
                                            <option value="ssl" {{ ($settings->imap_encryption ?? 'ssl') == 'ssl' ? 'selected' : '' }}>SSL</option>
                                            <option value="tls" {{ ($settings->imap_encryption ?? '') == 'tls' ? 'selected' : '' }}>TLS</option>
                                            <option value="none" {{ ($settings->imap_encryption ?? '') == 'none' ? 'selected' : '' }}>Nessuna</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane" id="smtp">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">Configurazione Server SMTP (per invio email)</h3>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i> 
                                <strong>Nota:</strong> Per inviare email devi configurare il server SMTP. 
                                Per Gmail, usa <code>smtp.gmail.com</code> sulla porta <code>587</code> con TLS 
                                e genera una <a href="https://support.google.com/accounts/answer/185833" target="_blank">App Password</a>.
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="smtp_host">Host SMTP</label>
                                        <input type="text" name="smtp_host" id="smtp_host" class="form-control" 
                                               value="{{ $settings->smtp_host ?? 'smtp.gmail.com' }}" 
                                               placeholder="es. smtp.gmail.com">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="smtp_port">Porta</label>
                                        <input type="number" name="smtp_port" id="smtp_port" class="form-control" 
                                               value="{{ $settings->smtp_port ?? 587 }}">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="smtp_encryption">Crittografia</label>
                                        <select name="smtp_encryption" id="smtp_encryption" class="form-control">
                                            <option value="tls" {{ ($settings->smtp_encryption ?? 'tls') == 'tls' ? 'selected' : '' }}>TLS</option>
                                            <option value="ssl" {{ ($settings->smtp_encryption ?? '') == 'ssl' ? 'selected' : '' }}>SSL</option>
                                            <option value="none" {{ ($settings->smtp_encryption ?? '') == 'none' ? 'selected' : '' }}>Nessuna</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="smtp_username">Username SMTP</label>
                                        <input type="text" name="smtp_username" id="smtp_username" class="form-control" 
                                               value="{{ $settings->smtp_username ?? '' }}" 
                                               placeholder="lascia vuoto per usare l'account IMAP">
                                        <small class="text-muted">Generalmente uguale all'account email</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="smtp_password">Password SMTP / App Password</label>
                                        <input type="password" name="smtp_password" id="smtp_password" class="form-control" 
                                               placeholder="{{ $settings->smtp_password ? '••••••••' : '' }}">
                                        <small class="text-muted">Lascia vuoto per usare la password IMAP</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane" id="account">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">Credenziali Account</h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="imap_username">Username/Email</label>
                                        <input type="text" name="imap_username" id="imap_username" class="form-control" 
                                               value="{{ $settings->imap_username ?? '' }}"  
                                               placeholder="es. tuo@gmail.com">
                                        <small class="text-muted">Per Gmail usa l'indirizzo completo</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="imap_password">Password / App Password</label>
                                        <input type="password" name="imap_password" id="imap_password" class="form-control" 
                                               placeholder="">
                                        <small class="text-muted">
                                            <a href="https://support.google.com/accounts/answer/185833" target="_blank">
                                                Per Gmail: genera una App Password
                                            </a>
                                        </small>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="email_address">Email Indirizzo</label>
                                        <input type="email" name="email_address" id="email_address" class="form-control" 
                                               value="{{ $settings->email_address ?? '' }}">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="email_name">Nome Visualizzato</label>
                                        <input type="text" name="email_name" id="email_name" class="form-control" 
                                               value="{{ $settings->email_name ?? '' }}" 
                                               placeholder="es. Nome Cognome">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="reply_to">Email Risposta (Reply-To)</label>
                                        <input type="email" name="reply_to" id="reply_to" class="form-control" 
                                               value="{{ $settings->reply_to ?? '' }}">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane" id="sync">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">Sincronizzazione</h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="sync_interval_minutes">Intervallo Sync (minuti)</label>
                                        <select name="sync_interval_minutes" id="sync_interval_minutes" class="form-control">
                                            <option value="1" {{ ($settings->sync_interval_minutes ?? 5) == 1 ? 'selected' : '' }}>1 minuto</option>
                                            <option value="5" {{ ($settings->sync_interval_minutes ?? 5) == 5 ? 'selected' : '' }}>5 minuti</option>
                                            <option value="15" {{ ($settings->sync_interval_minutes ?? 5) == 15 ? 'selected' : '' }}>15 minuti</option>
                                            <option value="30" {{ ($settings->sync_interval_minutes ?? 5) == 30 ? 'selected' : '' }}>30 minuti</option>
                                            <option value="60" {{ ($settings->sync_interval_minutes ?? 5) == 60 ? 'selected' : '' }}>1 ora</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Stato Connessione</label>
                                        <div class="mt-2">
                                            @if($settings->last_sync_at)
                                                <span class="badge badge-success">
                                                    <i class="fas fa-check-circle"></i> Ultimo sync: {{ $settings->last_sync_at->format('d/m/Y H:i') }}
                                                </span>
                                            @else
                                                <span class="badge badge-secondary">
                                                    <i class="fas fa-clock"></i> Mai sincronizzato
                                                </span>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="is_active" 
                                           name="is_active" value="1" {{ ($settings->is_active ?? false) ? 'checked' : '' }}>
                                    <label class="custom-control-label" for="is_active">Account Email Attivo</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane" id="signature">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">Firma Email</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="signature_enabled" 
                                           name="signature_enabled" value="1" {{ ($settings->signature_enabled ?? true) ? 'checked' : '' }}>
                                    <label class="custom-control-label" for="signature_enabled">Attiva firma automatica</label>
                                </div>
                                <small class="text-muted">Quando attivo, la firma verrà aggiunta in fondo a ogni email inviata</small>
                            </div>
                            <hr>
                            <div class="form-group">
                                <label for="signature">Testo Firma (formato HTML)</label>
                                <div id="signature-editor" style="height: 200px;"></div>
                                <input type="hidden" name="signature" id="signature_input" value="{{ $settings->signature ?? '' }}">
                                <small class="text-muted">Usa il riquadro sopra per comporre la tua firma. HTML supportato.</small>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane" id="mittenti">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">Mittenti Aggiuntivi</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#senderModal" onclick="resetSenderForm()">
                                    <i class="fas fa-plus mr-1"></i> Nuovo Mittente
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            @if(session('success'))
                                <div class="alert alert-success">{{ session('success') }}</div>
                            @endif
                            @if(session('error'))
                                <div class="alert alert-danger">{{ session('error') }}</div>
                            @endif

                            @if($senderAccounts->count() > 0)
                            <div class="table-responsive">
                                <table class="table table-bordered table-hover table-sm">
                                    <thead>
                                        <tr>
                                            <th>Email</th>
                                            <th>Nome</th>
                                            <th>SMTP</th>
                                            <th>Reply-To</th>
                                            <th>Verify</th>
                                            <th>Stato</th>
                                            <th style="width: 160px;">Azioni</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($senderAccounts as $sender)
                                        <tr>
                                            <td><strong>{{ $sender->email_address }}</strong></td>
                                            <td>{{ $sender->email_name ?: '-' }}</td>
                                            <td><small>{{ $sender->smtp_host ?: '-' }}:{{ $sender->smtp_port ?: '-' }}</small></td>
                                            <td><small class="text-muted">{{ $sender->reply_to ?: '-' }}</small></td>
                                            <td><small class="text-muted">{{ $sender->verify_email ?: '-' }}</small></td>
                                            <td>
                                                @if($sender->is_active)
                                                    <span class="badge badge-success">Attivo</span>
                                                @else
                                                    <span class="badge badge-secondary">Disattivo</span>
                                                @endif
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-xs btn-info" onclick="editSender({{ $sender->id }})" title="Modifica">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button type="button" class="btn btn-xs btn-success" onclick="testSenderSmtp({{ $sender->id }})" title="Test SMTP">
                                                    <i class="fas fa-paper-plane"></i>
                                                </button>
                                                <form action="{{ route('impostazioni.sender.destroy', $sender->id) }}" method="POST" class="d-inline" onsubmit="return confirm('Eliminare il mittente {{ $sender->email_address }}?')">
                                                    @csrf @method('DELETE')
                                                    <button type="submit" class="btn btn-xs btn-danger" title="Elimina">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                            @else
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-user-plus fa-2x mb-2"></i>
                                <p class="mb-0">Nessun mittente aggiuntivo configurato.</p>
                                <p class="mb-0">Usa il pulsante "Nuovo Mittente" per aggiungere un account di invio dedicato (es. Newsletter).</p>
                            </div>
                            @endif
                        </div>
                    </div>

                    @if($senderAccounts->count() > 0)
                    <div class="card card-secondary">
                        <div class="card-header">
                            <h3 class="card-title"><i class="fas fa-info-circle mr-2"></i>Come funziona</h3>
                        </div>
                        <div class="card-body">
                            <ul class="mb-0">
                                <li>I mittenti aggiuntivi sono account <strong>solo invio</strong> (SMTP) senza IMAP.</li>
                                <li>Puoi selezionarli nel <strong>compose email</strong> o negli <strong>invii mailing</strong>.</li>
                                <li>Il campo <strong>Reply-To</strong> imposta l'indirizzo di risposta (es. <code>no-reply@parrocchia.it</code>).</li>
                                <li>Il campo <strong>Verify Email</strong> riceve un report di riepilogo dopo ogni invio massivo con l'esito (ok/falliti).</li>
                                <li>Se Reply-To non è impostato, viene usato Verify Email come fallback.</li>
                            </ul>
                        </div>
                    </div>
                    @endif
                </div>
            </div>

            <div class="card-footer">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save mr-1"></i> Salva Impostazioni
                </button>
                <button type="button" class="btn btn-info ml-2" onclick="testConnection()">
                    <i class="fas fa-plug mr-1"></i> Test Connessione IMAP
                </button>
                <button type="button" class="btn btn-success ml-2" onclick="testSmtp()">
                    <i class="fas fa-paper-plane mr-1"></i> Test Invio Email (SMTP)
                </button>
                <a href="{{ route('impostazioni.email.sync') }}" class="btn btn-warning ml-2">
                    <i class="fas fa-sync mr-1"></i> Sincronizza Ora
                </a>
            </div>
        </form>
    </div>
</div>
@endsection

<div class="modal fade" id="senderModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="senderForm" method="POST" action="{{ route('impostazioni.sender.store') }}">
                @csrf
                <input type="hidden" name="_method" id="senderMethod" value="POST">
                <input type="hidden" name="id" id="senderId" value="">
                <div class="modal-header bg-primary">
                    <h5 class="modal-title" id="senderModalTitle"><i class="fas fa-user-plus mr-2"></i>Nuovo Mittente</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sender_email">Email *</label>
                                <input type="email" name="email_address" id="sender_email" class="form-control" required placeholder="newsletter@parrocchia.it">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sender_name">Nome visualizzato</label>
                                <input type="text" name="email_name" id="sender_name" class="form-control" placeholder="Newsletter Parrocchiale">
                            </div>
                        </div>
                    </div>
                    <hr>
                    <h6>Configurazione SMTP</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sender_smtp_host">Host SMTP</label>
                                <input type="text" name="smtp_host" id="sender_smtp_host" class="form-control" placeholder="smtp.gmail.com">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="sender_smtp_port">Porta</label>
                                <input type="number" name="smtp_port" id="sender_smtp_port" class="form-control" value="587">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="sender_smtp_encryption">Crittografia</label>
                                <select name="smtp_encryption" id="sender_smtp_encryption" class="form-control">
                                    <option value="tls">TLS</option>
                                    <option value="ssl">SSL</option>
                                    <option value="none">Nessuna</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sender_smtp_username">Username SMTP</label>
                                <input type="text" name="smtp_username" id="sender_smtp_username" class="form-control" placeholder="Lascia vuoto per usare l'email">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sender_smtp_password">Password SMTP</label>
                                <input type="password" name="smtp_password" id="sender_smtp_password" class="form-control" placeholder="......">
                                <small class="text-muted">Lascia vuoto per non cambiare</small>
                            </div>
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sender_reply_to">Reply-To <small class="text-muted">(no-reply)</small></label>
                                <input type="email" name="reply_to" id="sender_reply_to" class="form-control" placeholder="no-reply@parrocchia.it">
                                <small class="text-muted">Indirizzo di risposta per le email inviate</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sender_verify_email">Verify Email <small class="text-muted">(report)</small></label>
                                <input type="email" name="verify_email" id="sender_verify_email" class="form-control" placeholder="verifica@parrocchia.it">
                                <small class="text-muted">Riceve report riepilogo dopo invii massivi</small>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="sender_note">Nota interna</label>
                        <textarea name="note" id="sender_note" class="form-control" rows="2" placeholder="Es. Newsletter settimanale"></textarea>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="sender_is_active" name="is_active" value="1" checked>
                            <label class="custom-control-label" for="sender_is_active">Mittente attivo</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Annulla</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save mr-1"></i> Salva Mittente
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@section('scripts')
<script>
let senderAccounts = @json($senderAccounts);

function resetSenderForm() {
    document.getElementById('senderForm').action = '{{ route('impostazioni.sender.store') }}';
    document.getElementById('senderMethod').value = 'POST';
    document.getElementById('senderModalTitle').textContent = 'Nuovo Mittente';
    document.getElementById('senderForm').reset();
    document.getElementById('senderId').value = '';
    document.getElementById('sender_is_active').checked = true;
    document.getElementById('sender_smtp_password').placeholder = '';
    document.getElementById('sender_smtp_password').required = false;
}

function editSender(id) {
    const sender = senderAccounts.find(s => s.id === id);
    if (!sender) return;

    document.getElementById('senderForm').action = '{{ route('impostazioni.sender.update', '') }}/' + id;
    document.getElementById('senderMethod').value = 'PUT';
    document.getElementById('senderModalTitle').textContent = 'Modifica Mittente - ' + sender.email_address;
    document.getElementById('senderId').value = sender.id;
    document.getElementById('sender_email').value = sender.email_address;
    document.getElementById('sender_name').value = sender.email_name || '';
    document.getElementById('sender_smtp_host').value = sender.smtp_host || '';
    document.getElementById('sender_smtp_port').value = sender.smtp_port || 587;
    document.getElementById('sender_smtp_encryption').value = sender.smtp_encryption || 'tls';
    document.getElementById('sender_smtp_username').value = sender.smtp_username || '';
    document.getElementById('sender_smtp_password').value = '';
    document.getElementById('sender_smtp_password').placeholder = '......';
    document.getElementById('sender_smtp_password').required = false;
    document.getElementById('sender_reply_to').value = sender.reply_to || '';
    document.getElementById('sender_verify_email').value = sender.verify_email || '';
    document.getElementById('sender_note').value = sender.note || '';
    document.getElementById('sender_is_active').checked = sender.is_active;

    $('#senderModal').modal('show');
}

function testSenderSmtp(id) {
    const email = prompt('Inserisci l\'indirizzo email a cui inviare il test:');
    if (!email || !email.includes('@')) return;

    const btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

    $.ajax({
        url: '{{ route('impostazioni.sender.test', '') }}/' + id,
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
        data: { email: email },
        timeout: 30000,
        success: function(response) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane"></i>';
            alert(response.success ? '✅ ' + response.message : '❌ ' + response.message);
        },
        error: function(xhr) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane"></i>';
            const msg = xhr.responseJSON?.message || 'Errore di connessione';
            alert('❌ ' + msg);
        }
    });
}

function testConnection() {
    $.ajax({
        url: '{{ route('impostazioni.email.test') }}',
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
        success: function(response) {
            if (response.success) {
                alert('✅ ' + response.message);
            } else {
                alert('❌ ' + response.message);
            }
        },
        error: function() {
            alert('❌ Errore nella richiesta');
        }
    });
}

function testSmtp() {
    var email = prompt('Inserisci l\'indirizzo email a cui inviare il test:');
    if (!email) return;
    
    if (!email.includes('@')) {
        alert('⚠️ Indirizzo email non valido');
        return;
    }
    
    var btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Invio...';
    
    $.ajax({
        url: '{{ route('impostazioni.email.testSmtp') }}',
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
        data: { email: email },
        timeout: 30000,
        success: function(response) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane mr-1"></i> Test Invio Email (SMTP)';
            if (response.success) {
                alert('✅ ' + response.message);
            } else {
                alert('❌ ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane mr-1"></i> Test Invio Email (SMTP)';
            if (xhr.responseJSON && xhr.responseJSON.message) {
                alert('❌ ' + xhr.responseJSON.message);
            } else {
                alert('❌ Errore: ' + status + ' - ' + error);
            }
        }
    });
}

function createEditor() {
    var container = document.querySelector('#signature-editor');
    if (!container || container.querySelector('.ql-toolbar')) return;
    
    var quill = new Quill('#signature-editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline'],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'header': 1 }, { 'header': 2 }, { 'header': 3 }],
                [{ 'align': [] }],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                ['link', 'image'],
                ['clean', 'code']
            ]
        }
    });
    
    var signatureInput = document.getElementById('signature_input');
    var isEditingHtml = false;
    
    quill.getModule('toolbar').addHandler('code', function() {
        if (!isEditingHtml) {
            var textarea = document.createElement('textarea');
            textarea.className = 'ql-editor';
            textarea.style.cssText = 'font-family: monospace; min-height: 150px; width: 100%;';
            textarea.value = signatureInput.value;
            quill.root.innerHTML = '';
            quill.root.appendChild(textarea);
            textarea.focus();
            isEditingHtml = true;
        } else {
            var textarea = quill.root.querySelector('textarea');
            if (textarea) {
                signatureInput.value = textarea.value;
                quill.root.innerHTML = textarea.value;
            }
            isEditingHtml = false;
        }
    });
    
    if (signatureInput.value) {
        quill.root.innerHTML = signatureInput.value;
    }
    
    quill.on('text-change', function() {
        if (!isEditingHtml) {
            signatureInput.value = quill.root.innerHTML;
        }
    });
}

function initSignatureEditor() {
    if (document.querySelector('#signature-editor .ql-toolbar')) return;
    
    if (typeof Quill === 'undefined') {
        var script = document.createElement('script');
        script.src = 'https://cdn.quilljs.com/1.3.7/quill.min.js';
        script.onload = createEditor;
        document.head.appendChild(script);
        
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cdn.quilljs.com/1.3.7/quill.snow.css';
        document.head.appendChild(link);
    } else {
        createEditor();
    }
}

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    if ($(e.target).attr('href') === '#signature') {
        setTimeout(initSignatureEditor, 100);
    }
});

if ($('#signature').hasClass('active')) {
    initSignatureEditor();
}
</script>
@endsection