@extends('admin.layouts.netgescon')

@section('title', isset($stabile) ? 'Modifica Stabile' : 'Nuovo Stabile')
@section('page-title', isset($stabile) ? 'Modifica Stabile' : 'Nuovo Stabile')

@section('breadcrumb')
    <li class="text-gray-600">
        <a href="{{ route('admin.stabili.index') }}" class="hover:text-blue-600">
            <i class="fas fa-building mr-2"></i>
            Stabili
        </a>
    </li>
    @if(isset($stabile))
        <li class="text-gray-600">
            <i class="fas fa-chevron-right mx-2"></i>
            <a href="{{ route('admin.stabili.show', $stabile) }}" class="hover:text-blue-600">
                {{ Str::limit($stabile->denominazione, 30) }}
            </a>
        </li>
        <li class="text-gray-600">
            <i class="fas fa-chevron-right mx-2"></i>
            Modifica
        </li>
    @else
        <li class="text-gray-600">
            <i class="fas fa-chevron-right mx-2"></i>
            Nuovo Stabile
        </li>
    @endif
@endsection

@section('content')
<div class="space-y-6">
    <!-- Header -->
    <div class="flex justify-between items-center">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">
                @if(isset($stabile))
                    Modifica Stabile
                @else
                    Nuovo Stabile
                @endif
            </h1>
            <p class="text-gray-600 mt-1">
                @if(isset($stabile))
                    Modifica i dati di: {{ $stabile->denominazione }}
                @else
                    Compila tutti i campi per aggiungere un nuovo condominio al sistema
                @endif
            </p>
        </div>
        <div class="flex space-x-3">
            @if(isset($stabile))
                <a href="{{ route('admin.stabili.show', $stabile) }}" 
                   class="netgescon-btn netgescon-btn-secondary">
                    <i class="fas fa-eye mr-2"></i>
                    Visualizza
                </a>
            @endif
            <a href="{{ route('admin.stabili.index') }}" 
               class="netgescon-btn netgescon-btn-secondary">
                <i class="fas fa-arrow-left mr-2"></i>
                Torna alla Lista
            </a>
        </div>
    </div>

    <!-- Form Unificato -->
    <div class="bg-white rounded-lg shadow-sm border">
        <form method="POST" 
              action="{{ isset($stabile) ? route('admin.stabili.update', $stabile) : route('admin.stabili.store') }}" 
              class="space-y-6">
            @csrf
            @if(isset($stabile))
                @method('PUT')
            @endif
            
            <!-- Tabs Navigation -->
            <div class="border-b border-gray-200 px-6 pt-6">
                <nav class="-mb-px flex space-x-8" aria-label="Tabs" role="tablist">
                    <button type="button" class="netgescon-tab-btn active" data-tab="dati-generali" role="tab">
                        <i class="fas fa-info-circle mr-2"></i>
                        Dati Generali
                    </button>
                    <button type="button" class="netgescon-tab-btn" data-tab="palazzine" role="tab">
                        <i class="fas fa-building mr-2"></i>
                        Palazzine
                    </button>
                    <button type="button" class="netgescon-tab-btn" data-tab="dati-bancari" role="tab">
                        <i class="fas fa-university mr-2"></i>
                        Dati Bancari
                    </button>
                    <button type="button" class="netgescon-tab-btn" data-tab="tabelle-millesimali" role="tab">
                        <i class="fas fa-table mr-2"></i>
                        Tabelle Millesimali
                    </button>
                    @if(isset($stabile))
                        <button type="button" class="netgescon-tab-btn" data-tab="unita-immobiliari" role="tab">
                            <i class="fas fa-home mr-2"></i>
                            Unità Immobiliari
                        </button>
                        <button type="button" class="netgescon-tab-btn" data-tab="gestione-documentale" role="tab">
                            <i class="fas fa-folder-open mr-2"></i>
                            Gestione Documentale
                        </button>
                    @endif
                </nav>
            </div>

            <!-- Tab Content -->
            <div class="px-6 pb-6">
                <!-- Dati Generali -->
                <div id="dati-generali" class="netgescon-tab-content active">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Sezione Identificazione -->
                        <div class="md:col-span-2">
                            <h4 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">
                                <i class="fas fa-id-card text-blue-600 mr-2"></i>
                                Dati Identificativi
                            </h4>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Denominazione Stabile <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="denominazione" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Nome del condominio"
                                   value="{{ old('denominazione', $stabile->denominazione ?? '') }}">
                            @error('denominazione')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Codice Stabile <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="codice_stabile" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Codice identificativo univoco"
                                   value="{{ old('codice_stabile', $stabile->codice_stabile ?? '') }}">
                            @error('codice_stabile')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Tipo Stabile</label>
                            <select name="tipo_stabile" 
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="">Seleziona tipo</option>
                                <option value="residenziale" {{ old('tipo_stabile', $stabile->tipo_stabile ?? '') == 'residenziale' ? 'selected' : '' }}>Residenziale</option>
                                <option value="commerciale" {{ old('tipo_stabile', $stabile->tipo_stabile ?? '') == 'commerciale' ? 'selected' : '' }}>Commerciale</option>
                                <option value="misto" {{ old('tipo_stabile', $stabile->tipo_stabile ?? '') == 'misto' ? 'selected' : '' }}>Misto</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Data Costruzione</label>
                            <input type="date" name="data_costruzione"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   value="{{ old('data_costruzione', $stabile->data_costruzione ?? '') }}">
                        </div>

                        <!-- Sezione Indirizzo -->
                        <div class="md:col-span-2 mt-6">
                            <h4 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">
                                <i class="fas fa-map-marker-alt text-green-600 mr-2"></i>
                                Indirizzo Completo
                            </h4>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Via/Piazza <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="indirizzo" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Via/Piazza e numero civico"
                                   value="{{ old('indirizzo', $stabile->indirizzo ?? '') }}">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">CAP</label>
                            <input type="text" name="cap"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="00000"
                                   maxlength="5"
                                   value="{{ old('cap', $stabile->cap ?? '') }}">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Città <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="citta" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Nome della città"
                                   value="{{ old('citta', $stabile->citta ?? '') }}">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Provincia</label>
                            <input type="text" name="provincia"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="XX"
                                   maxlength="2"
                                   value="{{ old('provincia', $stabile->provincia ?? '') }}">
                        </div>

                        <!-- Sezione Dati Catastali -->
                        <div class="md:col-span-2 mt-6">
                            <h4 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">
                                <i class="fas fa-file-alt text-purple-600 mr-2"></i>
                                Dati Catastali
                            </h4>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Foglio</label>
                            <input type="text" name="foglio"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Foglio catastale"
                                   value="{{ old('foglio', $stabile->foglio ?? '') }}">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Particella</label>
                            <input type="text" name="particella"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Particella catastale"
                                   value="{{ old('particella', $stabile->particella ?? '') }}">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Subalterno</label>
                            <input type="text" name="subalterno"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Subalterno catastale"
                                   value="{{ old('subalterno', $stabile->subalterno ?? '') }}">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Codice Fiscale</label>
                            <input type="text" name="codice_fiscale"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="Codice fiscale condominio"
                                   value="{{ old('codice_fiscale', $stabile->codice_fiscale ?? '') }}">
                        </div>

                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Note</label>
                            <textarea name="note" rows="3"
                                      class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      placeholder="Note aggiuntive sul condominio">{{ old('note', $stabile->note ?? '') }}</textarea>
                        </div>
                    </div>
                </div>

                <!-- Palazzine -->
                <div id="palazzine" class="netgescon-tab-content hidden">
                    <div class="space-y-6">
                        <div class="flex justify-between items-center">
                            <h4 class="text-lg font-semibold text-gray-900">
                                <i class="fas fa-building text-blue-600 mr-2"></i>
                                Gestione Palazzine
                            </h4>
                            <button type="button" onclick="aggiungiPalazzina()" 
                                    class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center space-x-2">
                                <i class="fas fa-plus"></i>
                                <span>Aggiungi Palazzina</span>
                            </button>
                        </div>

                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <p class="text-sm text-blue-800">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>Gerarchia:</strong> STABILE → PALAZZINE → SCALE → INTERNI/LOCALI<br>
                                Ogni palazzina rappresenta un edificio separato del condominio. 
                                Dopo la creazione, le unità immobiliari verranno generate automaticamente.
                            </p>
                        </div>

                        <!-- Container per le palazzine -->
                        <div id="palazzine-container">
                            <!-- Palazzina template che verrà clonata -->
                            <div class="palazzina-item bg-white border border-gray-200 rounded-lg p-6" data-index="0">
                                <div class="flex justify-between items-start mb-4">
                                    <h5 class="text-md font-semibold text-gray-800">Palazzina 1</h5>
                                    <button type="button" onclick="rimuoviPalazzina(0)" 
                                            class="text-red-600 hover:text-red-800 hidden">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            Nome Palazzina <span class="text-red-500">*</span>
                                        </label>
                                        <input type="text" name="palazzine[0][nome]" required
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                               placeholder="es: Via Roma 15"
                                               value="Palazzina A">
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            Codice <span class="text-red-500">*</span>
                                        </label>
                                        <input type="text" name="palazzine[0][codice]" required
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                               placeholder="A"
                                               value="A">
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            Numero Scale <span class="text-red-500">*</span>
                                        </label>
                                        <input type="number" name="palazzine[0][numero_scale]" required min="1" max="5"
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                               value="1"
                                               onchange="aggiornaUnitaPalazzina(0)">
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            Numero Piani <span class="text-red-500">*</span>
                                        </label>
                                        <input type="number" name="palazzine[0][numero_piani]" required min="1" max="20"
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                               value="3"
                                               onchange="aggiornaUnitaPalazzina(0)">
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            Unità per Piano <span class="text-red-500">*</span>
                                        </label>
                                        <input type="number" name="palazzine[0][unita_per_piano]" required min="1" max="10"
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                               value="2"
                                               onchange="aggiornaUnitaPalazzina(0)">
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Tipo Palazzina</label>
                                        <select name="palazzine[0][tipo]" 
                                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                            <option value="principale" selected>Principale</option>
                                            <option value="secondaria">Secondaria</option>
                                            <option value="pertinenze">Pertinenze</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="mt-4">
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Note/Descrizione</label>
                                    <textarea name="palazzine[0][note]" rows="2"
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                              placeholder="Note aggiuntive su questa palazzina"></textarea>
                                </div>

                                <!-- Riepilogo unità -->
                                <div class="mt-4 bg-gray-50 border border-gray-200 rounded-lg p-3">
                                    <div class="flex items-center justify-between">
                                        <span class="text-sm font-medium text-gray-700">Unità totali in questa palazzina:</span>
                                        <span id="unita-palazzina-0" class="text-lg font-semibold text-blue-600">6</span>
                                    </div>
                                    <p class="text-xs text-gray-500 mt-1">Scale × Piani × Unità per Piano = Totale Unità</p>
                                </div>
                            </div>
                        </div>

                        <!-- Riepilogo generale -->
                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <div class="flex items-center justify-between">
                                <span class="text-sm font-medium text-blue-800">Totale Unità Immobiliari (Tutte le Palazzine):</span>
                                <span id="totale-generale-unita" class="text-xl font-bold text-blue-900">6</span>
                            </div>
                            <p class="text-xs text-green-600 mt-1">
                                Conferma la creazione per generare automaticamente tutte le unità immobiliari
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Dati Bancari -->
                <div id="dati-bancari" class="netgescon-tab-content hidden">
                    <div class="space-y-6">
                        <div class="flex justify-between items-center">
                            <h4 class="text-lg font-semibold text-gray-900">
                                <i class="fas fa-university text-blue-600 mr-2"></i>
                                Conti Bancari del Condominio
                            </h4>
                        </div>

                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <p class="text-sm text-blue-800">
                                <i class="fas fa-info-circle mr-2"></i>
                                Configura i conti bancari utilizzati per la gestione finanziaria del condominio.
                            </p>
                        </div>

                        <!-- Conto Principale -->
                        <div class="bg-white border border-gray-200 rounded-lg p-6">
                            <h5 class="text-md font-semibold text-gray-800 mb-4">Conto Principale</h5>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Banca</label>
                                    <input type="text" name="banca_principale"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                           placeholder="Nome della banca"
                                           value="{{ old('banca_principale', $stabile->banca_principale ?? '') }}">
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">IBAN</label>
                                    <input type="text" name="iban_principale"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                           placeholder="IT00 0000 0000 0000 0000 0000 000"
                                           value="{{ old('iban_principale', $stabile->iban_principale ?? '') }}">
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Intestatario</label>
                                    <input type="text" name="intestatario_principale"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                           placeholder="Intestatario del conto"
                                           value="{{ old('intestatario_principale', $stabile->intestatario_principale ?? '') }}">
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Tipo Conto</label>
                                    <select name="tipo_conto_principale" 
                                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                        <option value="ordinario" {{ old('tipo_conto_principale', $stabile->tipo_conto_principale ?? '') == 'ordinario' ? 'selected' : '' }}>Ordinario</option>
                                        <option value="straordinario" {{ old('tipo_conto_principale', $stabile->tipo_conto_principale ?? '') == 'straordinario' ? 'selected' : '' }}>Straordinario</option>
                                        <option value="misto" {{ old('tipo_conto_principale', $stabile->tipo_conto_principale ?? '') == 'misto' ? 'selected' : '' }}>Misto</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tabelle Millesimali -->
                <div id="tabelle-millesimali" class="netgescon-tab-content hidden">
                    <div class="space-y-6">
                        <div class="flex justify-between items-center">
                            <h4 class="text-lg font-semibold text-gray-900">
                                <i class="fas fa-table text-blue-600 mr-2"></i>
                                Tabelle Millesimali
                            </h4>
                            <button type="button" onclick="aggiungiTabella()" 
                                    class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center space-x-2">
                                <i class="fas fa-plus"></i>
                                <span>Aggiungi Tabella</span>
                            </button>
                        </div>

                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <p class="text-sm text-blue-800">
                                <i class="fas fa-info-circle mr-2"></i>
                                Le tabelle millesimali definiscono le quote di partecipazione alle spese comuni. 
                                Puoi configurare tabelle diverse per diversi tipi di spese.
                            </p>
                        </div>

                        <!-- Tabella Generale -->
                        <div class="bg-white border border-gray-200 rounded-lg p-6">
                            <h5 class="text-md font-semibold text-gray-800 mb-4">Tabella Generale</h5>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Nome Tabella <span class="text-red-500">*</span></label>
                                    <input type="text" name="nome_tabella_generale"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                           placeholder="Tabella Generale"
                                           value="{{ old('nome_tabella_generale', $stabile->nome_tabella_generale ?? 'Tabella Generale') }}">
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Tipologia <span class="text-red-500">*</span></label>
                                    <select name="tipologia_tabella_generale" 
                                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                        <option value="generale" selected>Generale</option>
                                        <option value="specifica">Specifica</option>
                                        <option value="personalizzata">Personalizzata</option>
                                    </select>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Metodo Calcolo <span class="text-red-500">*</span></label>
                                    <select name="metodo_calcolo_generale" 
                                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                        <option value="superficie_commerciale" selected>Superficie Commerciale</option>
                                        <option value="superficie_reale">Superficie Reale</option>
                                        <option value="vani_catastali">Vani Catastali</option>
                                        <option value="valore_catastale">Valore Catastale</option>
                                    </select>
                                </div>
                            </div>

                            <div class="mt-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Data Approvazione</label>
                                <input type="date" name="data_approvazione_generale"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                       value="{{ old('data_approvazione_generale', $stabile->data_approvazione_generale ?? '') }}">
                            </div>

                            <div class="mt-4">
                                <label class="flex items-center">
                                    <input type="checkbox" name="tabella_principale" value="1" 
                                           class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
                                           {{ old('tabella_principale', $stabile->tabella_principale ?? true) ? 'checked' : '' }}>
                                    <span class="ml-2 text-sm text-gray-600">Tabella principale</span>
                                </label>
                            </div>

                            <div class="mt-4">
                                <label class="flex items-center">
                                    <input type="checkbox" name="attiva" value="1" 
                                           class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
                                           {{ old('attiva', $stabile->attiva ?? true) ? 'checked' : '' }}>
                                    <span class="ml-2 text-sm text-gray-600">Attiva</span>
                                </label>
                            </div>

                            <div class="mt-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Descrizione/Note</label>
                                <textarea name="descrizione_tabella_generale" rows="3"
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                          placeholder="Descrizione della tabella e criteri di calcolo utilizzati">{{ old('descrizione_tabella_generale', $stabile->descrizione_tabella_generale ?? '') }}</textarea>
                            </div>
                        </div>
                    </div>
                </div>

                @if(isset($stabile))
                    <!-- Unità Immobiliari (Solo in modalità edit) -->
                    <div id="unita-immobiliari" class="netgescon-tab-content hidden">
                        <div class="space-y-6">
                            <div class="flex justify-between items-center">
                                <h4 class="text-lg font-semibold text-gray-900">
                                    <i class="fas fa-home text-blue-600 mr-2"></i>
                                    Unità Immobiliari
                                </h4>
                                <button type="button" 
                                        class="netgescon-btn netgescon-btn-primary">
                                    <i class="fas fa-plus mr-2"></i>
                                    Nuova Unità
                                </button>
                            </div>

                            <div class="loading" style="display: none;">
                                <div class="text-center py-8">
                                    <i class="fas fa-spinner fa-spin text-3xl text-blue-600"></i>
                                    <p class="text-gray-600 mt-2">Caricamento unità immobiliari...</p>
                                </div>
                            </div>

                            <div class="ajax-content">
                                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                                    <p class="text-sm text-blue-800">
                                        <i class="fas fa-info-circle mr-2"></i>
                                        Clicca su questa tab per caricare dinamicamente l'elenco delle unità immobiliari di questo stabile.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Gestione Documentale -->
                    <div id="gestione-documentale" class="netgescon-tab-content hidden">
                        @include('admin.stabili.tabs.gestione-documentale')
                    </div>
                @endif
            </div>

            <!-- Form Actions -->
            <div class="flex justify-between items-center bg-gray-50 px-6 py-4 border-t">
                <a href="{{ route('admin.stabili.index') }}" 
                   class="netgescon-btn netgescon-btn-secondary">
                    <i class="fas fa-times mr-2"></i>
                    Annulla
                </a>
                
                <div class="space-x-3">
                    @if(isset($stabile))
                        <a href="{{ route('admin.stabili.show', $stabile) }}" 
                           class="netgescon-btn netgescon-btn-secondary">
                            <i class="fas fa-eye mr-2"></i>
                            Visualizza
                        </a>
                    @endif
                    <button type="submit" class="netgescon-btn netgescon-btn-primary">
                        <i class="fas fa-save mr-2"></i>
                        {{ isset($stabile) ? 'Aggiorna Stabile' : 'Crea Stabile' }}
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Script per gestione tabs e funzionalità -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const tabButtons = document.querySelectorAll('.netgescon-tab-btn');
    const tabContents = document.querySelectorAll('.netgescon-tab-content');

    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const targetTab = this.getAttribute('data-tab');

            // Rimuovi classe active da tutti i bottoni
            tabButtons.forEach(btn => {
                btn.classList.remove('active');
            });

            // Aggiungi classe active al bottone cliccato
            this.classList.add('active');

            // Nascondi tutti i contenuti dei tab
            tabContents.forEach(content => {
                content.classList.remove('active');
                content.classList.add('hidden');
            });

            // Mostra il contenuto del tab selezionato
            const targetContent = document.getElementById(targetTab);
            if (targetContent) {
                targetContent.classList.add('active');
                targetContent.classList.remove('hidden');

                // Carica contenuto dinamico per tab edit-only
                @if(isset($stabile))
                if (targetTab === 'unita-immobiliari' && !targetContent.dataset.loaded) {
                    loadUnitaImmobiliari({{ $stabile->id }});
                    targetContent.dataset.loaded = 'true';
                } else if (targetTab === 'gestione-documentale' && !targetContent.dataset.loaded) {
                    loadDocumentiCollegati({{ $stabile->id }});
                    targetContent.dataset.loaded = 'true';
                }
                @endif
            }
        });
    });

    // Inizializza i calcoli per le palazzine
    aggiornaUnitaPalazzina(0);
    aggiornaTotaleGenerale();
});

let contatorePalazzine = 1;

function aggiornaUnitaPalazzina(index) {
    const palazzina = document.querySelector(`.palazzina-item[data-index="${index}"]`);
    if (!palazzina) return;
    
    const scale = parseInt(palazzina.querySelector(`input[name="palazzine[${index}][numero_scale]"]`).value) || 0;
    const piani = parseInt(palazzina.querySelector(`input[name="palazzine[${index}][numero_piani]"]`).value) || 0;
    const unitaPiano = parseInt(palazzina.querySelector(`input[name="palazzine[${index}][unita_per_piano]"]`).value) || 0;
    
    const totale = scale * piani * unitaPiano;
    const spanTotale = document.getElementById(`unita-palazzina-${index}`);
    if (spanTotale) {
        spanTotale.textContent = totale;
    }
    
    aggiornaTotaleGenerale();
}

function aggiornaTotaleGenerale() {
    let totaleGenerale = 0;
    document.querySelectorAll('.palazzina-item').forEach((palazzina, index) => {
        const spanTotale = document.getElementById(`unita-palazzina-${index}`);
        if (spanTotale) {
            totaleGenerale += parseInt(spanTotale.textContent) || 0;
        }
    });
    
    const spanGenerale = document.getElementById('totale-generale-unita');
    if (spanGenerale) {
        spanGenerale.textContent = totaleGenerale;
    }
}

function aggiungiPalazzina() {
    const container = document.getElementById('palazzine-container');
    const template = container.querySelector('.palazzina-item');
    const nuovaPalazzina = template.cloneNode(true);
    
    // Aggiorna l'indice
    nuovaPalazzina.setAttribute('data-index', contatorePalazzine);
    
    // Aggiorna il titolo
    nuovaPalazzina.querySelector('h5').textContent = `Palazzina ${contatorePalazzine + 1}`;
    
    // Aggiorna i nomi dei campi
    const inputs = nuovaPalazzina.querySelectorAll('input, textarea, select');
    inputs.forEach(input => {
        if (input.name) {
            input.name = input.name.replace(/\[\d+\]/, `[${contatorePalazzine}]`);
        }
        if (input.onchange) {
            input.setAttribute('onchange', `aggiornaUnitaPalazzina(${contatorePalazzine})`);
        }
    });
    
    // Aggiorna gli ID
    const spanTotale = nuovaPalazzina.querySelector('[id^="unita-palazzina-"]');
    if (spanTotale) {
        spanTotale.id = `unita-palazzina-${contatorePalazzine}`;
    }
    
    // Aggiorna il bottone rimuovi
    const btnRimuovi = nuovaPalazzina.querySelector('button[onclick^="rimuoviPalazzina"]');
    if (btnRimuovi) {
        btnRimuovi.setAttribute('onclick', `rimuoviPalazzina(${contatorePalazzine})`);
        btnRimuovi.classList.remove('hidden');
    }
    
    // Resetta i valori
    nuovaPalazzina.querySelectorAll('input[type="text"], textarea').forEach(input => {
        if (input.name.includes('[nome]')) {
            input.value = `Palazzina ${String.fromCharCode(65 + contatorePalazzine)}`;
        } else if (input.name.includes('[codice]')) {
            input.value = String.fromCharCode(65 + contatorePalazzine);
        } else {
            input.value = '';
        }
    });
    
    container.appendChild(nuovaPalazzina);
    contatorePalazzine++;
    
    // Aggiorna il calcolo
    aggiornaUnitaPalazzina(contatorePalazzine - 1);
}

function rimuoviPalazzina(index) {
    const palazzina = document.querySelector(`.palazzina-item[data-index="${index}"]`);
    if (palazzina && document.querySelectorAll('.palazzina-item').length > 1) {
        palazzina.remove();
        aggiornaTotaleGenerale();
    }
}

function aggiungiTabella() {
    alert('Funzionalità aggiungi tabella in sviluppo');
}

@if(isset($stabile))
// Funzioni AJAX per caricamento contenuto dinamico
function loadUnitaImmobiliari(stabileId) {
    const container = document.getElementById('unita-immobiliari');
    const loadingDiv = container.querySelector('.loading');
    const contentDiv = container.querySelector('.ajax-content');
    
    if (loadingDiv) loadingDiv.style.display = 'block';
    
    fetch(`/admin/stabili/${stabileId}/unita-immobiliari`)
        .then(response => response.text())
        .then(html => {
            if (contentDiv) {
                contentDiv.innerHTML = html;
                if (loadingDiv) loadingDiv.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Errore caricamento unità immobiliari:', error);
            if (contentDiv) {
                contentDiv.innerHTML = '<div class="text-red-600 p-4">Errore nel caricamento dei dati</div>';
            }
            if (loadingDiv) loadingDiv.style.display = 'none';
        });
}

function loadDocumentiCollegati(stabileId) {
    const container = document.getElementById('gestione-documentale');
    const loadingDiv = container.querySelector('.loading');
    const contentDiv = container.querySelector('.ajax-content');
    
    if (loadingDiv) loadingDiv.style.display = 'block';
    
    fetch(`/admin/stabili/${stabileId}/documenti`)
        .then(response => response.text())
        .then(html => {
            if (contentDiv) {
                contentDiv.innerHTML = html;
                if (loadingDiv) loadingDiv.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Errore caricamento documenti:', error);
            if (contentDiv) {
                contentDiv.innerHTML = '<div class="text-red-600 p-4">Errore nel caricamento dei documenti</div>';
            }
            if (loadingDiv) loadingDiv.style.display = 'none';
        });
}
@endif
</script>
@endsection
