<?php $__env->startSection('title', 'Nuova Email'); ?>
<?php $__env->startSection('page_title', 'Composizione Email'); ?>

<?php $__env->startSection('content'); ?>
<div class="row">
    <div class="col-md-12">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-edit mr-2"></i>Nuova Email</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="<?php echo e(route('email.send')); ?>" id="emailForm" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>

                    <?php if($senderAccounts->count() > 0): ?>
                    <div class="form-group">
                        <label for="mittente_id">Da (mittente)</label>
                        <select name="mittente_id" id="mittente_id" class="form-control">
                            <option value="0">Sistema — <?php echo e(optional(\App\Models\EmailSetting::getActive())->email_address ?? 'Configura email'); ?></option>
                            <?php $__currentLoopData = $senderAccounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $sender): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($sender->id); ?>"><?php echo e($sender->email_name ?: $sender->email_address); ?> &lt;<?php echo e($sender->email_address); ?>&gt;</option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <small class="text-muted">Seleziona un mittente alternativo per l'invio. Lascia "Sistema" per usare l'account predefinito.</small>
                    </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label>Destinatari *</label>
                        <div class="mb-2">
                            <select name="destinatario_tipo" id="destinatario_tipo" class="form-control" onchange="toggleDestinatari()">
                                <option value="manuale">Email Manuale</option>
                                <option value="individui">Singoli Individui</option>
                                <option value="gruppo">Membri di un Gruppo</option>
                                <option value="mailing_list">Mailing List</option>
                            </select>
                        </div>

                        <div id="manual-input" class="destinatari-section">
                            <input type="text" name="to" id="to_manual" class="form-control" 
                                   placeholder="destinatario@email.it" value="<?php echo e($prefill['to'] ?? ''); ?>">
                        </div>

                        <div id="individui-input" class="destinatari-section" style="display: none;">
                            <select name="individui[]" id="individui-select" class="form-control" multiple size="5">
                                <?php $__currentLoopData = $individui; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ind): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($ind->id); ?>"><?php echo e($ind->cognito); ?> <?php echo e($ind->nome); ?> (<?php echo e($ind->email_primaria ?? 'senza email'); ?>)</option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                            <small class="text-muted">Tieni premuto Ctrl per selezionare più individui</small>
                        </div>

                        <div id="gruppo-input" class="destinatari-section" style="display: none;">
                            <select name="gruppo_id" id="gruppo-select" class="form-control mb-2" onchange="loadGruppiContatti()">
                                <option value="">Seleziona gruppo...</option>
                                <?php $__currentLoopData = $gruppi; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $gruppo): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($gruppo->id); ?>"><?php echo e($gruppo->nome); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                            <div id="gruppo-contatti" class="border rounded p-2" style="max-height: 150px; overflow-y: auto;">
                                <em class="text-muted">Seleziona un gruppo per vedere i contatti</em>
                            </div>
                        </div>

                        <div id="mailing-list-input" class="destinatari-section" style="display: none;">
                            <select name="mailing_list_id" id="mailing-list-select" class="form-control">
                                <option value="">Seleziona mailing list...</option>
                                <?php $__currentLoopData = $mailingLists; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $list): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($list->id); ?>"><?php echo e($list->nome); ?> (<?php echo e($list->contatti->count()); ?> contatti)</option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="subject">Oggetto *</label>
                        <input type="text" name="subject" id="subject" class="form-control" 
                               value="<?php echo e($prefill['subject'] ?? ''); ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="body">Messaggio *</label>
                        <textarea name="body" id="body" class="form-control" rows="15" required><?php echo e($prefill['body'] ?? ''); ?></textarea>
                    </div>

                    <div class="form-group">
                        <label>Allegati</label>
                        <div class="border rounded p-3 bg-light">
                            <label class="btn btn-sm btn-success mb-0">
                                <i class="fas fa-upload mr-1"></i> Carica file
                                <input type="file" name="allegati[]" multiple class="d-none">
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane mr-1"></i> Invia
                        </button>
                        <button type="button" class="btn btn-secondary ml-2" onclick="saveDraft()">
                            <i class="fas fa-save mr-1"></i> Salva Bozze
                        </button>
                        <a href="<?php echo e(route('email.index')); ?>" class="btn btn-default ml-2">
                            Annulla
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
function toggleDestinatari() {
    const tipo = document.getElementById('destinatario_tipo').value;
    
    document.querySelectorAll('.destinatari-section').forEach(el => el.style.display = 'none');
    
    if (tipo === 'manuale') {
        document.getElementById('manual-input').style.display = 'block';
    } else if (tipo === 'individui') {
        document.getElementById('individui-input').style.display = 'block';
    } else if (tipo === 'gruppo') {
        document.getElementById('gruppo-input').style.display = 'block';
    } else if (tipo === 'mailing_list') {
        document.getElementById('mailing-list-input').style.display = 'block';
    }
}

function loadGruppiContatti() {
    const gruppoId = document.getElementById('gruppo-select').value;
    const container = document.getElementById('gruppo-contatti');
    
    if (!gruppoId) {
        container.innerHTML = '<em class="text-muted">Seleziona un gruppo per vedere i contatti</em>';
        return;
    }

    fetch('/gruppi/' + gruppoId + '/individui-email')
        .then(response => response.json())
        .then(data => {
            if (data.length === 0) {
                container.innerHTML = '<em class="text-muted">Nessun contatto email nel gruppo</em>';
                return;
            }
            
            let html = '';
            data.forEach(ind => {
                if (ind.email) {
                    html += `<div class="form-check">
                        <input class="form-check-input" type="checkbox" name="gruppo_emails[]" value="${ind.email}" id="email-${ind.id}">
                        <label class="form-check-label" for="email-${ind.id}">${ind.cogname} ${ind.nome} - ${ind.email}</label>
                    </div>`;
                }
            });
            container.innerHTML = html || '<em class="text-muted">Nessun contatto email nel gruppo</em>';
        });
}

function saveDraft() {
    const form = document.getElementById('emailForm');
    const formData = new FormData(form);
    
    fetch('<?php echo e(route('email.draft')); ?>', {
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        alert('Bozza salvata!');
    });
}
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.adminlte', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/glastree/resources/views/email/compose.blade.php ENDPATH**/ ?>