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

@php
$canWriteGruppi = Auth::user()->canManage('gruppi');
$canDeleteGruppi = Auth::user()->canDelete('gruppi');
@endphp

@section('breadcrumbs')
<li class="breadcrumb-item"><a href="{{ route('gruppi.index') }}">Gruppi</a></li>
<li class="breadcrumb-item active">{{ $gruppo->nome }}</li>
@endsection

@if(session('success'))
<div class="alert alert-success alert-dismissible">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    {{ session('success') }}
</div>
@endif
@if(session('error'))
<div class="alert alert-danger alert-dismissible">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    {{ session('error') }}
</div>
@endif

@section('content')
<div class="row">
    <div class="col-md-4">
        <div class="card card-success">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-folder text-warning mr-2"></i>
                    {{ $gruppo->nome }}
                </h3>
            </div>
            <div class="card-body">
                <table class="table table-sm table-borderless">
                    <tr>
                        <td style="width: 130px;"><strong>Path:</strong></td>
                        <td class="text-muted small">{{ $gruppo->full_path }}</td>
                    </tr>
                    <tr>
                        <td><strong>Gruppo Padre:</strong></td>
                        <td>
                            @if($gruppo->parent)
                                <a href="{{ route('gruppi.show', $gruppo->parent->id) }}">{{ $gruppo->parent->nome }}</a>
                            @else
                                <span class="badge badge-success">Gruppo radice</span>
                            @endif
                        </td>
                    </tr>
                    <tr>
                        <td><strong>Diocesi:</strong></td>
                        <td>{{ $gruppo->diocesi?->nome ?? '-' }}</td>
                    </tr>
                    <tr>
                        <td><strong>Responsabili:</strong></td>
                        <td>
                            @php $responsabili = $gruppo->getResponsabili() @endphp
                            @if($responsabili->count() > 0)
                                @foreach($responsabili as $resp)
                                    <a href="{{ route('individui.show', $resp->id) }}">
                                        <i class="fas fa-user text-info mr-1"></i>
                                        {{ $resp->nome_completo }}
                                    </a><br>
                                @endforeach
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <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">
                <table class="table table-sm table-borderless mb-0">
                    <tr>
                        <td style="width: 100px;"><strong>Indirizzo:</strong></td>
                        <td>{{ $gruppo->indirizzo_incontro ?: '-' }}</td>
                    </tr>
                    <tr>
                        <td><strong>CAP:</strong></td>
                        <td>{{ $gruppo->cap_incontro ?: '-' }}</td>
                    </tr>
                    <tr>
                        <td><strong>Città:</strong></td>
                        <td>{{ $gruppo->città_incontro ?: '-' }} {{ $gruppo->sigla_provincia_incontro ? "({$gruppo->sigla_provincia_incontro})" : '' }}</td>
                    </tr>
                </table>
                @if($gruppo->mappa_posizione)
                    <a href="{{ $gruppo->mappa_posizione }}" target="_blank" class="btn btn-sm btn-outline-primary mt-2">
                        <i class="fas fa-external-link-alt mr-1"></i> Visualizza su mappa
                    </a>
                @endif
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header"><h3 class="card-title"><i class="fas fa-chart-pie mr-2"></i>Statistiche</h3></div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="border-right">
                            <h2 class="mb-0 text-primary">{{ $gruppo->individui->count() }}</h2>
                            <small class="text-muted">Membri</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <h2 class="mb-0 text-warning">{{ $gruppo->children->count() }}</h2>
                        <small class="text-muted">Sottogruppi</small>
                    </div>
</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-camera mr-2"></i>Avatar</h3>
            </div>
            <div class="card-body text-center">
                @if($gruppo->avatar_url)
                    <img src="{{ $gruppo->avatar_url }}"
                         alt="{{ $gruppo->nome }}"
                         class="img-thumbnail mb-2"
                         style="max-width: 120px; max-height: 120px; object-fit: cover; border-radius: 50%;">
                    <br>
                    <form id="remove-avatar-form" class="d-inline">
                        <button type="button" class="btn btn-danger btn-sm" onclick="removeAvatar()">
                            <i class="fas fa-trash mr-1"></i>Rimuovi
                        </button>
                    </form>
                @else
                    <div class="bg-secondary d-flex align-items-center justify-content-center mb-3"
                         style="width: 120px; height: 120px; margin: 0 auto; border-radius: 50%;">
                        <i class="fas fa-folder fa-4x text-white"></i>
                    </div>
                @endif
                <form id="avatar-upload-form" enctype="multipart/form-data">
                    @csrf
                    <div class="custom-file mb-2">
                        <input type="file" class="custom-file-input" id="avatar-input" name="avatar" accept="image/jpeg,image/png,image/gif,image/webp">
                        <label class="custom-file-label" for="avatar-input">Scegli immagine...</label>
                    </div>
                    <button type="button" class="btn btn-primary btn-sm" onclick="uploadAvatar()">
                        <i class="fas fa-upload mr-1"></i>Carica
                    </button>
                </form>
                <div id="avatar-message" class="mt-2"></div>
            </div>
        </div>
    </div>

    @php
    $incontroEvento = $gruppo->eventi->where('is_incontro_gruppo', true)->first();
    @endphp
    @if($incontroEvento)
    <div class="row">
        <div class="col-md-4">
            <div class="card card-success">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-calendar-check mr-2"></i>
                        Giorno di Incontro
                    </h3>
                </div>
                <div class="card-body">
                    <table class="table table-sm table-borderless mb-0">
                        <tr>
                            <td style="width: 100px;"><strong>Evento:</strong></td>
                            <td>{{ $incontroEvento->nome_evento }}</td>
                        </tr>
                        <tr>
                            <td><strong>Quando:</strong></td>
                            <td>
                                @if($incontroEvento->tipo_recorrenza === 'settimanale')
                                    {{ $incontroEvento->giorno_settimana_label }}
                                    <span class="badge badge-info ml-1">Settimanale</span>
                                @elseif($incontroEvento->tipo_recorrenza === 'mensile')
                                    {{ $incontroEvento->occorrenza_mensile_label }}
                                    @if($incontroEvento->mesi_recorrenza)
                                        <small class="text-muted">({{ $incontroEvento->mesi_recorrenza_label }})</small>
                                    @endif
                                    <span class="badge badge-info ml-1">Mensile</span>
                                @elseif($incontroEvento->tipo_recorrenza === 'annuale')
                                    {{ $incontroEvento->mese_annuale_label }}
                                    @if($incontroEvento->giorno_mese)
                                        , giorno {{ $incontroEvento->giorno_mese }}
                                    @endif
                                    <span class="badge badge-info ml-1">Annuale</span>
                                @elseif($incontroEvento->tipo_recorrenza === 'altro')
                                    {{ $incontroEvento->giorno_settimana_label }}
                                    <span class="badge badge-info ml-1">Altro</span>
                                @else
                                    {{ $incontroEvento->data_specifica?->format('d/m/Y') ?: '-' }}
                                @endif
                            </td>
                        </tr>
                        @if($incontroEvento->ora_inizio)
                        <tr>
                            <td><strong>Ora:</strong></td>
                            <td>ore {{ $incontroEvento->ora_inizio->format('H:i') }}</td>
                        </tr>
                        @endif
                    </table>
                    @if($incontroEvento->responsabili->count() > 0)
                    <hr>
                    <small class="text-muted"><strong>Responsabili:</strong></small>
                    @foreach($incontroEvento->responsabili as $resp)
                        <div class="mt-1">
                            <i class="fas fa-user text-info mr-1"></i>
                            <a href="/individui/{{ $resp->id }}">{{ $resp->cognome }} {{ $resp->nome }}</a>
                            @if($resp->telefono_primario)
                                <br><small class="text-success ml-3">{{ $resp->telefono_primario }}</small>
                            @endif
                        </div>
                    @endforeach
                    @endif
                    <div class="mt-2">
                        <a href="/eventi/{{ $incontroEvento->id }}" class="btn btn-xs btn-outline-primary">
                            <i class="fas fa-eye mr-1"></i> Vedi evento
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif

    @if($gruppo->descrizione)
<div class="row mt-3">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header"><h3 class="card-title"><i class="fas fa-align-left mr-2"></i>Descrizione</h3></div>
            <div class="card-body">
                <p class="mb-0">{!! nl2br(e($gruppo->descrizione)) !!}</p>
            </div>
        </div>
    </div>
</div>
@endif

<div class="card mt-3">
    <div class="card-header">
        <h3 class="card-title">
            <i class="fas fa-users mr-2"></i>Membri ({{ $gruppo->individui->count() }})
        </h3>
    </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: 100px;">Codice</th>
                        <th>Nome Completo</th>
                        <th>Email</th>
                        <th>Telefono</th>
                        <th style="width: 150px;">Ruolo</th>
                        <th style="width: 110px;">Data Adesione</th>
                        <th style="width: 80px;">Azioni</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($gruppo->individui as $individuo)
                    <tr>
                        <td><span class="badge badge-secondary">{{ $individuo->codice_id }}</span></td>
                        <td>
                            <a href="{{ route('individui.show', $individuo->id) }}">
                                <i class="fas fa-user text-info mr-1"></i>
                                {{ $individuo->cognome }} {{ $individuo->nome }}
                            </a>
                        </td>
                        <td>{{ $individuo->email_primaria ?? '-' }}</td>
                        <td>{{ $individuo->telefono_primario ?? '-' }}</td>
                        <td>
                            @php
                                $ruoloIds = $individuo->pivot->ruolo_ids ? json_decode($individuo->pivot->ruolo_ids, true) : [];
                                $ruoli = \App\Models\Ruolo::findByIds($ruoloIds);
                            @endphp
                            @if($ruoli->count() > 0)
                                @foreach($ruoli as $ruolo)
                                    <span class="badge badge-info mr-1">{{ $ruolo->nome }}</span>
                                @endforeach
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            @if($individuo->pivot->data_adesione)
                                {{ \Carbon\Carbon::parse($individuo->pivot->data_adesione)->format('d/m/Y') }}
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            <a href="{{ route('individui.show', $individuo->id) }}" class="btn btn-xs btn-info" title="Visualizza">
                                <i class="fas fa-eye"></i>
                            </a>
                        </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</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 ({{ $gruppo->documenti->count() }})
        </h3>
        @if($canWriteGruppi)
        <button type="button" class="btn btn-xs btn-primary float-right" data-toggle="modal" data-target="#uploadDocumentoModal">
            <i class="fas fa-upload mr-1"></i> Carica
        </button>
        @endif
    </div>
    <div class="card-body p-0">
        @if($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: 100px;">Azioni</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($gruppo->documenti as $documento)
                    <tr>
                        <td>
                            <a href="#" onclick="event.preventDefault(); previewDocumento({{ $documento->id }}, '{{ $documento->mime_type }}');">
                                <i class="fas fa-file text-secondary mr-1"></i>
                                {{ $documento->nome_file }}
                            </a>
                        </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)
                                <a href="{{ url('/documenti/' . $documento->id . '/download') }}" class="btn btn-xs btn-primary" title="Scarica">
                                    <i class="fas fa-download"></i>
                                </a>
                            @endif
                        </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="card mt-3">
    <div class="card-header">
        <h3 class="card-title">
            <i class="fas fa-sitemap mr-2"></i>Sottogruppi ({{ $gruppo->children->count() }})
        </h3>
        <a href="{{ route('gruppi.create', ['parent_id' => $gruppo->id]) }}" class="btn btn-xs btn-success float-right">
            <i class="fas fa-plus mr-1"></i> Aggiungi Sottogruppo
        </a>
    </div>
    <div class="card-body p-0">
        @if($gruppo->children->count() > 0)
            <table class="table table-bordered table-hover table-striped mb-0">
                <thead class="thead-light">
                    <tr>
                        <th>Nome</th>
                        <th>Diocesi</th>
                        <th>Responsabile</th>
                        <th style="text-align: center;">Membri</th>
                        <th style="width: 100px;">Azioni</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($gruppo->children->sortBy('nome') as $child)
                    <tr>
                        <td>
                            <a href="{{ route('gruppi.show', $child->id) }}">
                                <i class="fas fa-folder-open text-warning mr-1"></i>
                                {{ $child->nome }}
                            </a>
                        </td>
                        <td>{{ $child->diocesi?->nome ?? '-' }}</td>
                        <td>{{ $child->getResponsabili()->isNotEmpty() ? $child->getResponsabili()->first()->nome_completo : '-' }}</td>
                        <td class="text-center">
                            @if($child->individui()->count() > 0)
                                <span class="badge badge-info">{{ $child->individui()->count() }}</span>
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            <a href="{{ route('gruppi.show', $child->id) }}" class="btn btn-xs btn-info" title="Visualizza">
                                <i class="fas fa-eye"></i>
                            </a>
                            @if($canWriteGruppi)
                            <a href="{{ route('gruppi.edit', $child->id) }}" class="btn btn-xs btn-warning" title="Modifica">
                                <i class="fas fa-edit"></i>
                            </a>
                            @endif
                            @if($canDeleteGruppi)
                            <form action="{{ route('gruppi.destroy', $child->id) }}" method="POST" class="d-inline">
                                @csrf @method('DELETE')
                                <button type="submit" class="btn btn-xs btn-danger" onclick="return confirm('Eliminare {{ $child->nome }}?')" title="Elimina">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                            @endif
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        @else
            <div class="text-center text-muted py-4">
                <i class="fas fa-folder-open fa-2x mb-2"></i>
                <p class="mb-0">Nessun sottogruppo</p>
            </div>
        @endif
    </div>
</div>

<div class="mt-3">
    @if($canWriteGruppi)
    <a href="{{ url('/gruppi/' . $gruppo->id . '/edit') }}" class="btn btn-warning">
        <i class="fas fa-edit mr-1"></i> Modifica
    </a>
    @endif
    @if($canDeleteGruppi)
    <form action="{{ url('/gruppi/' . $gruppo->id) }}" method="POST" class="d-inline">
        @csrf @method('DELETE')
        <button type="submit" class="btn btn-danger" onclick="return confirm('Confermi l\'eliminazione di {{ $gruppo->nome }}? Verranno eliminati anche tutti i sottogruppi.')">
            <i class="fas fa-trash mr-1"></i> Elimina
        </button>
    </form>
    @endif
    <a href="{{ route('gruppi.index') }}" class="btn btn-secondary">
        <i class="fas fa-arrow-left mr-1"></i> Torna all'elenco
    </a>
</div>

<div class="modal fade" id="uploadDocumentoModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-upload mr-2"></i>Carica Documento</h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form action="/documenti" method="POST" enctype="multipart/form-data">
                @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">
                <input type="hidden" name="_redirect" value="{{ url()->current() }}">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Nome *</label>
                        <input type="text" name="nome_file" class="form-control" placeholder="Nome del documento" required>
                    </div>
                    <div class="form-group">
                        <label>Tipologia *</label>
                        <select name="tipologia" class="form-control" required>
                            <option value="">Seleziona...</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="form-group">
                        <label>File *</label>
                        <input type="file" name="file" class="form-control" required>
                        <small class="text-muted">Max 10MB</small>
                    </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-upload mr-1"></i> Carica
                    </button>
                </div>
            </form>
        </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 previewDocumento(id, mimeType) {
    var previewUrl = '/documenti/' + id + '/preview';
    var downloadUrl = '/documenti/' + id + '/download';

    document.getElementById('previewFrame').src = previewUrl;
    document.getElementById('previewDownloadBtn').href = downloadUrl;
    document.getElementById('previewModalTitle').textContent = 'Anteprima';

    document.getElementById('previewDownloadBtn').style.display = 'inline-block';

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

document.getElementById('avatar-input').addEventListener('change', function(e) {
    if (e.target.files.length > 0) {
        var label = e.target.files[0].name;
        var next = e.target.nextElementSibling;
        if (next && next.classList.contains('custom-file-label')) {
            next.textContent = label;
        }
    }
});

function uploadAvatar() {
    var input = document.getElementById('avatar-input');
    if (!input.files.length) {
        document.getElementById('avatar-message').innerHTML = '<span class="text-danger">Seleziona un\'immagine</span>';
        return;
    }

    var formData = new FormData();
    formData.append('avatar', input.files[0]);
    formData.append('_token', '{{ csrf_token() }}');

    document.getElementById('avatar-message').innerHTML = '<span class="text-info"><i class="fas fa-spinner fa-spin"></i> Caricamento...</span>';

    fetch('{{ url('/gruppi/' . $gruppo->id . '/avatar') }}', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('avatar-message').innerHTML = '<span class="text-success">Avatar caricato!</span>';
            setTimeout(function() { window.location.reload(); }, 1000);
        } else {
            document.getElementById('avatar-message').innerHTML = '<span class="text-danger">' + (data.message || 'Errore') + '</span>';
        }
    })
    .catch(error => {
        document.getElementById('avatar-message').innerHTML = '<span class="text-danger">Errore: ' + error + '</span>';
    });
}

function removeAvatar() {
    if (!confirm('Rimuovere l\'avatar?')) return;

    fetch('{{ url('/gruppi/' . $gruppo->id . '/avatar') }}', {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('avatar-message').innerHTML = '<span class="text-success">Avatar rimosso!</span>';
            setTimeout(function() { window.location.reload(); }, 1000);
        } else {
            document.getElementById('avatar-message').innerHTML = '<span class="text-danger">' + (data.message || 'Errore') + '</span>';
        }
    })
    .catch(error => {
        document.getElementById('avatar-message').innerHTML = '<span class="text-danger">Errore: ' + error + '</span>';
    });
}
</script>
@endsection
