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

@section('content')
<form action="/gruppi/{{ $gruppo->id }}" method="POST">
    @csrf @method('PUT')
    <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" value="{{ old('nome', $gruppo->nome) }}" required>
                    </div>
                    <div class="form-group">
                        <label>Gruppo Padre</label>
                        <select name="parent_id" class="form-control">
                            <option value="">Nessuno (gruppo radice)</option>
                            @foreach($gruppi as $g)
                                @if($g->id !== $gruppo->id)
                                    <option value="{{ $g->id }}" {{ old('parent_id', $gruppo->parent_id) == $g->id ? 'selected' : '' }}>
                                        {{ $g->full_path }}
                                    </option>
                                @endif
                            @endforeach
                        </select>
                    </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', $gruppo->diocesi_id) == $d->id ? 'selected' : '' }}>{{ $d->nome }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Responsabili (solo membri)</label>
                        <select name="responsabile_ids[]" class="form-control" multiple size="4">
                            @foreach($membri as $m)
                            <option value="{{ $m->id }}" {{ in_array($m->id, old('responsabile_ids', $gruppo->getResponsabiliIds() ?? [])) ? 'selected' : '' }}>
                                {{ $m->cognome }} {{ $m->nome }}
                            </option>
                            @endforeach
                        </select>
                        @if($membri->isEmpty())
                            <small class="text-muted">Prima aggiungi dei membri al gruppo</small>
                        @else
                            <small class="text-muted">Ctrl+click per selezionare più responsabili</small>
                        @endif
                    </div>
                    <div class="form-group">
                        <label>Descrizione</label>
                        <textarea name="descrizione" class="form-control" rows="3">{{ old('descrizione', $gruppo->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', $gruppo->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', $gruppo->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', $gruppo->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', $gruppo->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', $gruppo->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="showMembroForm()">
                <i class="fas fa-plus mr-1"></i> Aggiungi
            </button>
        </div>
        <div class="card-body p-0">

            @if($gruppo->individui->count() > 0)
            <table class="table table-bordered table-hover table-striped mb-0">
                <thead class="thead-light">
                    <tr>
                        <th style="width: 25%;">Individuo</th>
                        <th style="width: 80px;">Codice</th>
                        <th style="width: 25%;">Contatti</th>
                        <th style="width: 130px;">Ruolo</th>
                        <th style="width: 110px;">Data Adesione</th>
                        <th style="width: 80px;">Azioni</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($gruppo->individui as $membro)
                    <tr id="membro-row-{{ $membro->id }}">
                        <td>
                            <i class="fas fa-user text-primary mr-1"></i>
                            <a href="/individui/{{ $membro->id }}">{{ $membro->cognome }} {{ $membro->nome }}</a>
                        </td>
                        <td>{{ $membro->codice_id }}</td>
                        <td>
                            <small>
                                @if($membro->email_primaria)
                                    <span class="text-primary">{{ $membro->email_primaria }}</span><br>
                                @endif
                                @if($membro->telefono_primario)
                                    <span class="text-success">{{ $membro->telefono_primario }}</span>
                                @endif
                            </small>
                        </td>
                        <td>
                            @php $ruoliMembro = $membro->getRuoliForGruppo($gruppo->id) @endphp
                            @if($ruoliMembro->count() > 0)
                                @foreach($ruoliMembro as $ruolo)
                                    <span class="badge badge-info mr-1">{{ $ruolo->nome }}</span>
                                @endforeach
                            @else
                                -
                            @endif
                        </td>
                        <td>{{ $membro->pivot->data_adesione ? \Carbon\Carbon::parse($membro->pivot->data_adesione)->format('d/m/Y') : '-' }}</td>
                        <td>
                            <button type="button" class="btn btn-xs btn-warning" onclick="editMembroInline({{ $membro->id }})" title="Modifica">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button type="button" class="btn btn-xs btn-danger" onclick="deleteMembro({{ $membro->id }})" title="Rimuovi">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <tr id="membro-edit-{{ $membro->id }}" style="display:none;">
                        <td colspan="6">
                            <form action="/gruppi/{{ $gruppo->id }}/membri/{{ $membro->id }}" method="POST" class="mb-0">
                                @csrf @method('PUT')
                                <div class="row">
                                    <div class="col-md-4">
                                        <input type="text" class="form-control form-control-sm" value="{{ $membro->cognome }} {{ $membro->nome }}" disabled>
                                    </div>
                                    <div class="col-md-2">
                                        <input type="text" class="form-control form-control-sm" value="{{ $membro->codice_id }}" disabled>
                                    </div>
                                    <div class="col-md-3">
                                        <select name="ruolo_ids[]" class="form-control form-control-sm" multiple size="3">
                                            @foreach(\App\Models\Ruolo::attive() as $ruolo)
                                                @php $selected = in_array($ruolo->id, $membro->getRuoloIdsForGruppo($gruppo->id)) @endphp
                                                <option value="{{ $ruolo->id }}" {{ $selected ? 'selected' : '' }}>{{ $ruolo->nome }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <input type="date" name="data_adesione" class="form-control form-control-sm" value="{{ $membro->pivot->data_adesione }}">
                                    </div>
                                    <div class="col-md-1">
                                        <button type="submit" class="btn btn-xs btn-success"><i class="fas fa-check"></i></button>
                                        <button type="button" class="btn btn-xs btn-secondary" onclick="cancelEditMembro({{ $membro->id }})"><i class="fas fa-times"></i></button>
                                    </div>
                                </div>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            @else
            <div class="text-center text-muted py-4">
                <i class="fas fa-users fa-2x mb-2"></i>
                <p class="mb-0">Nessun membro associato</p>
            </div>
            @endif
        </div>
    </div>

    <div class="card mt-3">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-file mr-2"></i>Documenti</h3>
            <button type="button" class="btn btn-xs btn-success float-right" onclick="showDocumentoForm()">
                <i class="fas fa-plus mr-1"></i> Carica
            </button>
        </div>
        <div class="card-body p-0">
            <div id="documento-add-form" style="display:none;" class="p-3 bg-light border-bottom">
                <form action="/documenti" method="POST" enctype="multipart/form-data" class="mb-0">
                    @csrf
                    <input type="hidden" name="visibilita" value="gruppo">
                    <input type="hidden" name="visibilita_target_id" value="{{ $gruppo->id }}">
                    <input type="hidden" name="visibilita_target_type" value="App\Models\Gruppo">
                    <div class="row">
                        <div class="col-md-3">
                            <input type="text" name="nome_file" class="form-control form-control-sm" placeholder="Nome documento" required>
                        </div>
                        <div class="col-md-3">
                            <select name="tipologia" class="form-control form-control-sm" required>
                                <option value="">Tipologia...</option>
                                <option value="documento">Documento</option>
                                <option value="statuto">Statuto</option>
                                <option value="avatar">Avatar</option>
                                <option value="galleria">Galleria</option>
                                <option value="altro">Altro</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <input type="file" name="file" class="form-control form-control-sm" required>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-xs btn-success"><i class="fas fa-upload mr-1"></i>Carica</button>
                            <button type="button" class="btn btn-xs btn-secondary" onclick="hideDocumentoForm()"><i class="fas fa-times"></i></button>
                        </div>
                    </div>
                </form>
            </div>

            @if($gruppo->documenti && $gruppo->documenti->count() > 0)
            <table class="table table-bordered table-hover table-striped mb-0">
                <thead class="thead-light">
                    <tr>
                        <th>Nome</th>
                        <th style="width: 120px;">Tipologia</th>
                        <th style="width: 80px;">Dimensione</th>
                        <th style="width: 130px;">Data Upload</th>
                        <th style="width: 80px;">Azioni</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($gruppo->documenti as $documento)
                    <tr>
                        <td>
                            <i class="fas fa-file text-secondary mr-1"></i>
                            {{ $documento->nome_file }}
                        </td>
                        <td>{{ ucfirst(str_replace('_', ' ', $documento->tipologia)) }}</td>
                        <td>{{ number_format($documento->dimensione / 1024, 1) }} KB</td>
                        <td>{{ $documento->created_at->format('d/m/Y') }}</td>
                        <td>
                            @if($documento->file_path)
                                <button type="button" class="btn btn-xs btn-primary" onclick="previewDocumento({{ $documento->id }}, '{{ $documento->mime_type }}')" title="Anteprima">
                                    <i class="fas fa-eye"></i>
                                </button>
                            @endif
                            <form action="/documenti/{{ $documento->id }}" method="POST" class="d-inline">
                                @csrf @method('DELETE')
                                <button type="submit" class="btn btn-xs btn-danger" onclick="return confirm('Eliminare questo documento?')" title="Elimina">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            @else
            <div class="text-center text-muted py-4">
                <i class="fas fa-file fa-2x mb-2"></i>
                <p class="mb-0">Nessun documento</p>
            </div>
            @endif
        </div>
    </div>

    <div class="mt-3">
        <button type="submit" class="btn btn-success">
            <i class="fas fa-save mr-1"></i> Salva Modifiche
        </button>
        <a href="/gruppi/{{ $gruppo->id }}" class="btn btn-secondary">
            <i class="fas fa-times mr-1"></i> Annulla
        </a>
    </div>
</form>

<div class="card mt-3" id="membro-card" style="display:none; background-color: #fff3cd; border-color: #ffc107;">
    <div class="card-header bg-warning">
        <h3 class="card-title"><i class="fas fa-user-plus mr-2"></i>Aggiungi Membro</h3>
    </div>
    <div class="card-body">
        <div id="membro-form-container">
            <div class="row">
                <div class="col-md-4">
                    <select id="new-membro-individuo" class="form-control form-control-sm">
                        <option value="">Seleziona individuo...</option>
                        @foreach(\App\Models\Individuo::whereNotIn('id', $membri->pluck('id'))->orderBy('cognome')->orderBy('nome')->get() as $i)
                            <option value="{{ $i->id }}">{{ $i->cognome }} {{ $i->nome }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <select id="new-membro-ruolo" class="form-control form-control-sm" multiple size="3">
                        @foreach(\App\Models\Ruolo::attive() as $ruolo)
                            <option value="{{ $ruolo->id }}">{{ $ruolo->nome }}</option>
                        @endforeach
                    </select>
                    <small class="text-muted">Ctrl+click per selezionare più ruoli</small>
                </div>
                <div class="col-md-3">
                    <input type="date" id="new-membro-data" class="form-control form-control-sm">
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-success btn-sm" onclick="submitMembroForm()">
                        <i class="fas fa-check mr-1"></i> Associa
                    </button>
                    <button type="button" class="btn btn-secondary btn-sm" onclick="hideMembroForm()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="previewModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document" style="max-width: 90vw;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-file mr-2"></i><span id="previewModalTitle">Anteprima</span></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Chiudi">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body text-center p-0" style="min-height: 400px;">
                <iframe id="previewFrame" src="" style="width: 100%; height: 70vh; border: none;"></iframe>
            </div>
            <div class="modal-footer">
                <a id="previewDownloadBtn" href="#" class="btn btn-primary" download>
                    <i class="fas fa-download mr-1"></i> Scarica
                </a>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
function showMembroForm() {
    console.log('showMembroForm called');
    var card = document.getElementById('membro-card');
    console.log('Card element:', card);
    if (card) {
        card.style.display = 'block';
        card.scrollIntoView({ behavior: 'smooth', block: 'start' });
        console.log('Card shown');
    } else {
        console.error('Card not found');
    }
}

function hideMembroForm() {
    var card = document.getElementById('membro-card');
    if (card) {
        card.style.display = 'none';
    }
}

function submitMembroForm() {
    var individuoId = document.getElementById('new-membro-individuo').value;
    var ruoloSelect = document.getElementById('new-membro-ruolo');
    var dataAdesione = document.getElementById('new-membro-data').value;

    if (!individuoId) {
        alert('Seleziona un individuo');
        return;
    }

    document.getElementById('new-membro-individuo').removeAttribute('required');

    var formData = new URLSearchParams();
    formData.append('individuo_id', individuoId);
    
    var selectedRuoli = Array.from(ruoloSelect.selectedOptions).map(opt => opt.value).filter(v => v);
    selectedRuoli.forEach(function(ruoloId) {
        formData.append('ruolo_ids[]', ruoloId);
    });
    
    formData.append('data_adesione', dataAdesione);

    fetch('/gruppi/{{ $gruppo->id }}/membri', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => { throw new Error(text); });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            hideMembroForm();
            window.location.reload();
        } else {
            alert(data.error || 'Errore');
        }
    })
    .catch(error => {
        alert('Errore: ' + error.message);
    });
}

function editMembroInline(id) {
    document.getElementById('membro-row-' + id).style.display = 'none';
    document.getElementById('membro-edit-' + id).style.display = 'table-row';
}

function cancelEditMembro(id) {
    document.getElementById('membro-row-' + id).style.display = 'table-row';
    document.getElementById('membro-edit-' + id).style.display = 'none';
}

function deleteMembro(individuoId) {
    if (!confirm('Rimuovere questo membro dal gruppo?')) return;
    
    fetch('/gruppi/{{ $gruppo->id }}/membri/' + individuoId, {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => { throw new Error(text); });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            window.location.reload();
        } else {
            alert(data.error || 'Errore');
        }
    })
    .catch(error => {
        alert('Errore: ' + error.message);
    });
}

function showDocumentoForm() {
    document.getElementById('documento-add-form').style.display = 'block';
}

function hideDocumentoForm() {
    document.getElementById('documento-add-form').style.display = 'none';
}

function previewDocumento(id, mimeType) {
    document.getElementById('previewFrame').src = '/documenti/' + id + '/preview';
    document.getElementById('previewDownloadBtn').href = '/documenti/' + id + '/download';
    $('#previewModal').modal('show');
}
</script>
@endsection