@extends('layouts.adminlte')
@section('title', 'Nuovo Gruppo')
@section('page_title', 'Nuovo Gruppo')

@section('content')
<form action="/gruppi" method="POST">
    @csrf
    <div class="row">
        <div class="col-md-6">
            <div class="card card-primary">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-folder mr-2"></i>Dati Gruppo</h3>
                </div>
                <div class="card-body">
                    <div class="form-group">
                        <label>Nome *</label>
                        <input type="text" name="nome" class="form-control @error('nome') is-invalid @enderror" value="{{ old('nome') }}" required>
                        @error('nome')
                            <span class="invalid-feedback">{{ $message }}</span>
                        @enderror
                    </div>
                    <div class="form-group">
                        <label>Gruppo Padre</label>
                        <select name="parent_id" class="form-control">
                            <option value="">Nessuno (gruppo radice)</option>
                            @foreach($allGruppi as $g)
                                <option value="{{ $g->id }}" {{ old('parent_id') == $g->id || ($selectedParent && $selectedParent->id == $g->id) ? 'selected' : '' }}>
                                    {{ $g->full_path }}
                                </option>
                            @endforeach
                        </select>
                        @if($selectedParent)
                            <small class="form-text text-muted">
                                Verrà creato come sottogruppo di: <strong>{{ $selectedParent->nome }}</strong>
                            </small>
                        @endif
                    </div>
                    <div class="form-group">
                        <label>Diocesi</label>
                        <select name="diocesi_id" class="form-control">
                            <option value="">Seleziona...</option>
                            @foreach($diocesi as $d)
                            <option value="{{ $d->id }}" {{ old('diocesi_id') == $d->id ? 'selected' : '' }}>{{ $d->nome }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Responsabili</label>
                        <select name="responsabile_ids[]" class="form-control" multiple size="4" id="responsabile-select">
                            <option value="">-- Nessuno --</option>
                        </select>
                        <small class="text-muted">Ctrl+click per selezionare più responsabili</small>
                    </div>
                    <div class="form-group">
                        <label>Descrizione</label>
                        <textarea name="descrizione" class="form-control" rows="3">{{ old('descrizione') }}</textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header"><h3 class="card-title"><i class="fas fa-map-marker-alt mr-2"></i>Luogo Incontro</h3></div>
                <div class="card-body">
                    <div class="form-group">
                        <label>Indirizzo</label>
                        <input type="text" name="indirizzo_incontro" class="form-control" value="{{ old('indirizzo_incontro') }}">
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-4">
                            <label>CAP</label>
                            <input type="text" name="cap_incontro" class="form-control" value="{{ old('cap_incontro') }}">
                        </div>
                        <div class="form-group col-md-5">
                            <label>Città</label>
                            <input type="text" name="città_incontro" class="form-control" value="{{ old('città_incontro') }}">
                        </div>
                        <div class="form-group col-md-3">
                            <label>Provincia</label>
                            <input type="text" name="sigla_provincia_incontro" class="form-control" maxlength="2" value="{{ old('sigla_provincia_incontro') }}">
                        </div>
                    </div>
                    <div class="form-group mb-0">
                        <label>URL Mappa</label>
                        <input type="url" name="mappa_posizione" class="form-control" value="{{ old('mappa_posizione') }}" placeholder="https://...">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card mt-3">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-users mr-2"></i>Membri</h3>
            <button type="button" class="btn btn-xs btn-success float-right" onclick="aggiungiMembro()">
                <i class="fas fa-plus mr-1"></i> Aggiungi Membro
            </button>
        </div>
        <div class="card-body p-0">
            <table class="table table-bordered mb-0" id="membri-table">
                <thead class="thead-light">
                    <tr>
                        <th style="width: 30%;">Individuo</th>
                        <th>Codice</th>
                        <th>Contatti</th>
                        <th style="width: 20%;">Ruolo</th>
                        <th style="width: 100px;">Data Adesione</th>
                        <th style="width: 50px;"></th>
                    </tr>
                </thead>
                <tbody id="membri-tbody">
                </tbody>
            </table>
            <div id="no-membri-msg" class="text-center text-muted py-4">
                <p class="mb-0">Nessun membro aggiunto. Clicca su "Aggiungi Membro" per iniziare.</p>
            </div>
        </div>
    </div>

    <div class="mt-3">
        <button type="submit" class="btn btn-success">
            <i class="fas fa-save mr-1"></i> Salva
        </button>
        <a href="/gruppi" class="btn btn-secondary">
            <i class="fas fa-times mr-1"></i> Annulla
        </a>
    </div>
</form>
@endsection

@section('scripts')
<script>
let membriIndex = 0;
const membriResponsabiliMap = new Map();

function aggiungiMembro() {
    const tbody = document.getElementById('membri-tbody');
    const noMsg = document.getElementById('no-membri-msg');
    if (noMsg) noMsg.style.display = 'none';

    const row = document.createElement('tr');
    row.innerHTML = `
        <td>
            <select name="individui[${membriIndex}][individuo_id]" class="form-control" onchange="updateMembroInfo(this); updateResponsabiliFromMembri();" required>
                <option value="">Seleziona...</option>
                @foreach($individui as $i)
                    <option value="{{ $i->id }}" data-codice="{{ $i->codice_id }}" data-email="{{ $i->email_primaria }}" data-telefono="{{ $i->telefono_primario }}">
                        {{ $i->cognome }} {{ $i->nome }}
                    </option>
                @endforeach
            </select>
        </td>
        <td><span class="text-muted membro-codice">-</span></td>
        <td><small class="text-muted membro-contatti">-</small></td>
        <td><input type="text" name="individui[${membriIndex}][ruolo_nel_gruppo]" class="form-control" placeholder="Es. Membro"></td>
        <td><input type="date" name="individui[${membriIndex}][data_adesione]" class="form-control"></td>
        <td><button type="button" class="btn btn-danger btn-xs" onclick="rimuoviMembro(this); updateResponsabiliFromMembri();"><i class="fas fa-trash"></i></button></td>
    `;
    tbody.appendChild(row);
    membriIndex++;
}

function updateMembroInfo(select) {
    const row = select.closest('tr');
    const option = select.options[select.selectedIndex];
    const codice = option.dataset.codice || '-';
    const email = option.dataset.email || '';
    const telefono = option.dataset.telefono || '';
    
    row.querySelector('.membro-codice').textContent = codice;
    
    let contatti = [];
    if (email) contatti.push('<span class="text-primary">'+email+'</span>');
    if (telefono) contatti.push('<span class="text-success">'+telefono+'</span>');
    row.querySelector('.membro-contatti').innerHTML = contatti.length ? contatti.join(' | ') : '-';
}

function rimuoviMembro(btn) {
    const row = btn.closest('tr');
    row.remove();
    if (document.getElementById('membri-tbody').children.length === 0) {
        document.getElementById('no-membri-msg').style.display = 'block';
    }
}

function updateResponsabiliFromMembri() {
    const respSelect = document.getElementById('responsabile-select');
    const currentSelected = Array.from(respSelect.selectedOptions).map(o => o.value);
    const tbody = document.getElementById('membri-tbody');
    const rows = tbody.querySelectorAll('tr');
    
    const membroIds = new Set();
    const membroNames = new Map();
    
    rows.forEach(row => {
        const select = row.querySelector('select[name*="individuo_id"]');
        if (select && select.value) {
            membroIds.add(select.value);
            const option = select.options[select.selectedIndex];
            membroNames.set(select.value, option.text);
        }
    });
    
    respSelect.innerHTML = '';
    
    if (membroIds.size === 0) {
        const opt = document.createElement('option');
        opt.value = '';
        opt.textContent = '-- Aggiungi prima dei membri --';
        opt.disabled = true;
        respSelect.appendChild(opt);
    } else {
        membroIds.forEach(id => {
            const opt = document.createElement('option');
            opt.value = id;
            opt.textContent = membroNames.get(id);
            if (currentSelected.includes(id)) opt.selected = true;
            respSelect.appendChild(opt);
        });
    }
}

const respSelect = document.getElementById('responsabile-select');
const individuiList = @json($individui->map(fn($i) => ['id' => $i->id, 'text' => $i->cognome . ' ' . $i->nome]));
const initialResponsabili = @json(old('responsabile_ids', []));

const optPlaceholder = document.createElement('option');
optPlaceholder.value = '';
optPlaceholder.textContent = '-- Aggiungi prima dei membri --';
optPlaceholder.disabled = true;
respSelect.appendChild(optPlaceholder);

initialResponsabili.forEach(id => {
    const match = individuiList.find(i => i.id == id);
    if (match) {
        const opt = document.createElement('option');
        opt.value = match.id;
        opt.textContent = match.text;
        opt.selected = true;
        respSelect.appendChild(opt);
    }
});
</script>
@endsection