@extends('layouts.app-universal-v2')

@section('title', 'Comuni Italiani')

@section('content')
<div class="container-fluid">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0"><i class="fas fa-city text-primary me-2"></i>Comuni Italiani</h1>
                    <p class="text-muted mb-0">Archivio completo dei comuni italiani con codici ISTAT e dati geografici</p>
                </div>
                <div>
                    <a href="{{ route('superadmin.archivi.index') }}" class="btn btn-outline-secondary me-2">
                        <i class="fas fa-arrow-left me-2"></i>Torna agli Archivi
                    </a>
                    <button class="btn btn-primary" onclick="exportComuni()">
                        <i class="fas fa-download me-2"></i>Esporta CSV
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtri di ricerca -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <form id="filterForm" class="row g-3">
                        <div class="col-md-3">
                            <label for="search_nome" class="form-label">Nome Comune</label>
                            <input type="text" class="form-control" id="search_nome" name="search_nome" 
                                   placeholder="Cerca per nome..." value="{{ request('search_nome') }}">
                        </div>
                        <div class="col-md-2">
                            <label for="search_provincia" class="form-label">Provincia</label>
                            <input type="text" class="form-control" id="search_provincia" name="search_provincia" 
                                   placeholder="Sigla (es. MI)" value="{{ request('search_provincia') }}">
                        </div>
                        <div class="col-md-3">
                            <label for="search_regione" class="form-label">Regione</label>
                            <select class="form-select" id="search_regione" name="search_regione">
                                <option value="">Tutte le regioni</option>
                                <option value="LOMBARDIA" {{ request('search_regione') == 'LOMBARDIA' ? 'selected' : '' }}>Lombardia</option>
                                <option value="LAZIO" {{ request('search_regione') == 'LAZIO' ? 'selected' : '' }}>Lazio</option>
                                <option value="CAMPANIA" {{ request('search_regione') == 'CAMPANIA' ? 'selected' : '' }}>Campania</option>
                                <option value="SICILIA" {{ request('search_regione') == 'SICILIA' ? 'selected' : '' }}>Sicilia</option>
                                <option value="VENETO" {{ request('search_regione') == 'VENETO' ? 'selected' : '' }}>Veneto</option>
                                <option value="PIEMONTE" {{ request('search_regione') == 'PIEMONTE' ? 'selected' : '' }}>Piemonte</option>
                                <option value="EMILIA-ROMAGNA" {{ request('search_regione') == 'EMILIA-ROMAGNA' ? 'selected' : '' }}>Emilia-Romagna</option>
                                <!-- Aggiungi altre regioni -->
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="search_cap" class="form-label">CAP</label>
                            <input type="text" class="form-control" id="search_cap" name="search_cap" 
                                   placeholder="20121" value="{{ request('search_cap') }}">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-search me-2"></i>Cerca
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabella comuni -->
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-list me-2"></i>Elenco Comuni
                            <span class="badge bg-primary ms-2">{{ $comuni->total() }} risultati</span>
                        </h5>
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-info btn-sm" onclick="refreshData()">
                                <i class="fas fa-sync me-1"></i>Aggiorna
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Codice ISTAT</th>
                                    <th>Denominazione</th>
                                    <th>Provincia</th>
                                    <th>Regione</th>
                                    <th>CAP</th>
                                    <th>Codice Catastale</th>
                                    <th class="text-center">Azioni</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($comuni as $comune)
                                <tr>
                                    <td><code>{{ $comune->codice_istat }}</code></td>
                                    <td>
                                        <strong>{{ $comune->denominazione }}</strong>
                                        @if($comune->denominazione_straniera)
                                            <br><small class="text-muted">{{ $comune->denominazione_straniera }}</small>
                                        @endif
                                    </td>
                                    <td>
                                        @if($comune->provincia_denominazione)
                                            {{ $comune->provincia_denominazione }}
                                            @if($comune->provincia_codice)
                                                <br><small class="text-muted">{{ $comune->provincia_codice }}</small>
                                            @endif
                                        @else
                                            <span class="text-muted">N/A</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($comune->regione_denominazione)
                                            {{ $comune->regione_denominazione }}
                                            @if($comune->regione_codice)
                                                <br><small class="text-muted">{{ $comune->regione_codice }}</small>
                                            @endif
                                        @else
                                            <span class="text-muted">N/A</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($comune->cap)
                                            <span class="badge bg-secondary">{{ $comune->cap }}</span>
                                        @else
                                            <span class="text-muted">N/A</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($comune->codice_catastale)
                                            <code>{{ $comune->codice_catastale }}</code>
                                        @else
                                            <span class="text-muted">N/A</span>
                                        @endif
                                    </td>
                                    <td class="text-center">
                                        <button class="btn btn-outline-primary btn-sm" onclick="viewDettagli('{{ $comune->id }}')">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="7" class="text-center py-4">
                                        <div class="text-muted">
                                            <i class="fas fa-search fa-2x mb-3"></i>
                                            <p>Nessun comune trovato con i criteri di ricerca specificati.</p>
                                        </div>
                                    </td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
                @if($comuni->hasPages())
                <div class="card-footer">
                    {{ $comuni->links() }}
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

<!-- Modal Dettagli Comune -->
<div class="modal fade" id="dettagliModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-info-circle me-2"></i>Dettagli Comune</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="dettagliContent">
                <div class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Caricamento...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
function viewDettagli(comuneId) {
    const modal = new bootstrap.Modal(document.getElementById('dettagliModal'));
    modal.show();
    
    fetch(`/superadmin/comuni/${comuneId}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('dettagliContent').innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <h6>Informazioni Generali</h6>
                        <dl class="row">
                            <dt class="col-sm-5">Codice ISTAT:</dt>
                            <dd class="col-sm-7"><code>${data.codice_istat}</code></dd>
                            <dt class="col-sm-5">Denominazione:</dt>
                            <dd class="col-sm-7">${data.denominazione}</dd>
                            ${data.denominazione_straniera ? `
                            <dt class="col-sm-5">Denominazione Straniera:</dt>
                            <dd class="col-sm-7">${data.denominazione_straniera}</dd>
                            ` : ''}
                            <dt class="col-sm-5">Codice Catastale:</dt>
                            <dd class="col-sm-7"><code>${data.codice_catastale || 'N/A'}</code></dd>
                            <dt class="col-sm-5">CAP:</dt>
                            <dd class="col-sm-7">${data.cap || 'N/A'}</dd>
                        </dl>
                    </div>
                    <div class="col-md-6">
                        <h6>Ubicazione Geografica</h6>
                        <dl class="row">
                            <dt class="col-sm-5">Provincia:</dt>
                            <dd class="col-sm-7">${data.provincia_denominazione || 'N/A'} (${data.provincia_codice || 'N/A'})</dd>
                            <dt class="col-sm-5">Regione:</dt>
                            <dd class="col-sm-7">${data.regione_denominazione || 'N/A'} (${data.regione_codice || 'N/A'})</dd>
                        </dl>
                        <h6 class="mt-3">Metadati</h6>
                        <dl class="row">
                            <dt class="col-sm-5">Creato:</dt>
                            <dd class="col-sm-7">${new Date(data.created_at).toLocaleDateString('it-IT')}</dd>
                            <dt class="col-sm-5">Aggiornato:</dt>
                            <dd class="col-sm-7">${new Date(data.updated_at).toLocaleDateString('it-IT')}</dd>
                        </dl>
                    </div>
                </div>
            `;
        })
        .catch(error => {
            document.getElementById('dettagliContent').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    Errore nel caricamento dei dettagli: ${error.message}
                </div>
            `;
        });
}

function exportComuni() {
    const formData = new FormData(document.getElementById('filterForm'));
    const params = new URLSearchParams(formData);
    
    // Aggiungi parametro export
    params.append('export', 'csv');
    
    window.location.href = `{{ route('superadmin.archivi.comuni') }}?${params.toString()}`;
}

function refreshData() {
    location.reload();
}

// Auto-submit form on change
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('filterForm');
    const inputs = form.querySelectorAll('input, select');
    
    inputs.forEach(input => {
        input.addEventListener('change', function() {
            // Debounce per input text
            if (this.type === 'text') {
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => form.submit(), 500);
            } else {
                form.submit();
            }
        });
    });
});
</script>
@endpush
