<!-- Tab Gestione Documentale Avanzata -->
<div class="space-y-6">
    <!-- Header con controlli -->
    <div class="flex justify-between items-center">
        <div>
            <h4 class="text-xl font-semibold text-gray-900">
                <i class="fas fa-folder-open mr-2 text-purple-600"></i>
                Gestione Documentale
            </h4>
            <p class="text-sm text-gray-600 mt-1">
                Sistema avanzato di archiviazione con tagging, OCR e collegamento spese
            </p>
        </div>
        <div class="space-x-2">
            <button type="button" 
                    class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg transition-colors"
                    onclick="nuovoDocumento()">
                <i class="fas fa-plus mr-2"></i>
                Carica Documento
            </button>
            <button type="button" 
                    class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors"
                    onclick="scansioneMassiva()">
                <i class="fas fa-scan mr-2"></i>
                Scansione OCR
            </button>
            <button type="button" 
                    class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition-colors"
                    onclick="collegaSpese()">
                <i class="fas fa-link mr-2"></i>
                Collega Spese
            </button>
        </div>
    </div>

    <!-- Filtri e Ricerca Avanzata -->
    <div class="bg-white border border-gray-200 rounded-lg p-4">
        <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-search mr-2"></i>Ricerca Globale
                </label>
                <input type="text" id="ricerca-globale" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                       placeholder="Cerca in contenuti, nomi, tag..."
                       onkeyup="ricercaGlobale(this.value)">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-file-alt mr-2"></i>Tipologia
                </label>
                <select id="filtro-tipologia" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                        onchange="applicaFiltri()">
                    <option value="">Tutte le tipologie</option>
                    <option value="fattura">📄 Fatture</option>
                    <option value="preventivo">💰 Preventivi</option>
                    <option value="contratto">📋 Contratti</option>
                    <option value="verbale">📝 Verbali</option>
                    <option value="comunicazione">📢 Comunicazioni</option>
                    <option value="delibera">⚖️ Delibere</option>
                    <option value="relazione_tecnica">🔧 Relazioni Tecniche</option>
                    <option value="altro">📎 Altro</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-tags mr-2"></i>Tag/Categoria
                </label>
                <select id="filtro-tag" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                        onchange="applicaFiltri()">
                    <option value="">Tutti i tag</option>
                    <option value="spese_ordinarie">🏠 Spese Ordinarie</option>
                    <option value="spese_straordinarie">⚡ Spese Straordinarie</option>
                    <option value="riscaldamento">🔥 Riscaldamento</option>
                    <option value="acqua">💧 Acqua</option>
                    <option value="manutenzione">🔧 Manutenzione</option>
                    <option value="amministrazione">📊 Amministrazione</option>
                    <option value="legale">⚖️ Legale</option>
                    <option value="emergenza">🚨 Emergenza</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-calendar mr-2"></i>Periodo
                </label>
                <select id="filtro-periodo" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                        onchange="applicaFiltri()">
                    <option value="">Tutto</option>
                    <option value="oggi">Oggi</option>
                    <option value="settimana">Questa settimana</option>
                    <option value="mese" selected>Questo mese</option>
                    <option value="trimestre">Ultimo trimestre</option>
                    <option value="anno">Quest'anno</option>
                    <option value="personalizzato">Personalizzato</option>
                </select>
            </div>
            <div class="flex items-end">
                <button type="button" 
                        class="w-full bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg transition-colors"
                        onclick="applicaFiltri()">
                    <i class="fas fa-filter mr-2"></i>
                    Applica Filtri
                </button>
            </div>
        </div>
    </div>

    <!-- Statistiche Rapide -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 border border-purple-200 rounded-lg p-4">
            <div class="flex items-center justify-between">
                <div>
                    <h5 class="text-lg font-semibold text-purple-900">📄 Documenti</h5>
                    <p class="text-2xl font-bold text-purple-900 mt-1">{{ $stabile->documenti?->count() ?? 0 }}</p>
                    <p class="text-sm text-purple-700">Totali archiviati</p>
                </div>
                <i class="fas fa-file-alt text-3xl text-purple-600"></i>
            </div>
        </div>

        <div class="bg-gradient-to-br from-blue-50 to-blue-100 border border-blue-200 rounded-lg p-4">
            <div class="flex items-center justify-between">
                <div>
                    <h5 class="text-lg font-semibold text-blue-900">💰 Con Spese</h5>
                    <p class="text-2xl font-bold text-blue-900 mt-1">{{ $stabile->documenti?->whereNotNull('importo_collegato')?->count() ?? 0 }}</p>
                    <p class="text-sm text-blue-700">Collegati al budget</p>
                </div>
                <i class="fas fa-euro-sign text-3xl text-blue-600"></i>
            </div>
        </div>

        <div class="bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-lg p-4">
            <div class="flex items-center justify-between">
                <div>
                    <h5 class="text-lg font-semibold text-green-900">🔍 Con OCR</h5>
                    <p class="text-2xl font-bold text-green-900 mt-1">{{ $stabile->documenti?->whereNotNull('contenuto_ocr')?->count() ?? 0 }}</p>
                    <p class="text-sm text-green-700">Ricercabili</p>
                </div>
                <i class="fas fa-search text-3xl text-green-600"></i>
            </div>
        </div>

        <div class="bg-gradient-to-br from-orange-50 to-orange-100 border border-orange-200 rounded-lg p-4">
            <div class="flex items-center justify-between">
                <div>
                    <h5 class="text-lg font-semibold text-orange-900">📊 Dimensione</h5>
                    <p class="text-2xl font-bold text-orange-900 mt-1">{{ number_format(($stabile->documenti?->sum('dimensione_file') ?? 0) / 1024 / 1024, 1) }}</p>
                    <p class="text-sm text-orange-700">MB utilizzati</p>
                </div>
                <i class="fas fa-hdd text-3xl text-orange-600"></i>
            </div>
        </div>
    </div>

    <!-- Lista Documenti -->
    <div id="lista-documenti" class="space-y-4">
        @php
            $documenti = \App\Models\Documento::where('stabile_id', $stabile->id)
                                             ->where('is_demo', true)
                                             ->orderBy('created_at', 'desc')
                                             ->get();
        @endphp
        
        @forelse($documenti as $documento)
            <div class="bg-white border border-gray-200 rounded-lg overflow-hidden documento-item" 
                 data-tipologia="{{ $documento->tipologia ?? $documento->tipo_documento ?? 'altro' }}" 
                 data-categoria="{{ $documento->categoria_spesa }}"
                 data-data="{{ $documento->data_documento?->format('Y-m-d') ?? '' }}"
                 data-urgente="{{ $documento->urgente ? 'true' : 'false' }}"
                 data-approvato="{{ $documento->approvato ? 'true' : 'false' }}">>
                
                <div class="bg-gray-50 px-6 py-4 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <div class="flex items-center space-x-4">
                            <!-- Icona tipo documento -->
                            <div class="flex-shrink-0">
                            @switch($documento->tipologia ?? $documento->tipo_documento ?? 'altro')
                                    @case('fattura')
                                        <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-file-invoice text-red-600 text-xl"></i>
                                        </div>
                                        @break
                                    @case('preventivo')
                                        <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-calculator text-yellow-600 text-xl"></i>
                                        </div>
                                        @break
                                    @case('contratto')
                                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-handshake text-blue-600 text-xl"></i>
                                        </div>
                                        @break
                                    @case('verbale')
                                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-clipboard-list text-green-600 text-xl"></i>
                                        </div>
                                        @break
                                    @default
                                        <div class="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-file text-gray-600 text-xl"></i>
                                        </div>
                                @endswitch
                            </div>
                            
                            <div class="flex-1">
                                <h5 class="text-lg font-semibold text-gray-900">{{ $documento->nome ?? $documento->titolo ?? 'Documento' }}</h5>
                                <div class="flex items-center space-x-4 text-sm text-gray-600 mt-1">
                                    <span>
                                        <i class="fas fa-tag mr-1"></i>
                                        {{ ucfirst(str_replace('_', ' ', $documento->tipologia ?? 'altro')) }}
                                    </span>
                                    <span>
                                        <i class="fas fa-calendar mr-1"></i>
                                        {{ $documento->data_documento?->format('d/m/Y') ?? $documento->created_at?->format('d/m/Y') ?? 'N/D' }}
                                    </span>
                                    <span>
                                        <i class="fas fa-user mr-1"></i>
                                        {{ $documento->fornitore ?? $documento->mittente ?? 'N/D' }}
                                    </span>
                                    @if($documento->importo_collegato)
                                        <span class="text-green-600 font-medium">
                                            <i class="fas fa-euro-sign mr-1"></i>
                                            {{ number_format($documento->importo_collegato, 2) }}€
                                        </span>
                                    @endif
                                </div>
                                
                                <!-- Tag/Etichette -->
                                @if($documento->tags)
                                    <div class="flex flex-wrap gap-1 mt-2">
                                        @foreach(explode(',', $documento->tags) as $tag)
                                            <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                                                {{ trim($tag) }}
                                            </span>
                                        @endforeach
                                    </div>
                                @endif
                            </div>
                        </div>
                        
                        <div class="flex items-center space-x-2">
                            <!-- Indicatori speciali -->
                            @if($documento->contenuto_ocr)
                                <span class="px-2 py-1 bg-green-100 text-green-800 text-xs font-medium rounded" title="Ricercabile con OCR">
                                    🔍 OCR
                                </span>
                            @endif
                            @if($documento->importo_collegato)
                                <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded" title="Collegato a spese">
                                    💰 Spesa
                                </span>
                            @endif
                            @if($documento->urgente)
                                <span class="px-2 py-1 bg-red-100 text-red-800 text-xs font-medium rounded" title="Documento urgente">
                                    🚨 Urgente
                                </span>
                            @endif
                            
                            <!-- Azioni -->
                            <button type="button" 
                                    class="text-blue-600 hover:text-blue-800 text-sm font-medium"
                                    onclick="visualizzaDocumento({{ $documento->id }})">
                                <i class="fas fa-eye mr-1"></i>Visualizza
                            </button>
                            <button type="button" 
                                    class="text-green-600 hover:text-green-800 text-sm font-medium"
                                    onclick="scaricaDocumento({{ $documento->id }})">
                                <i class="fas fa-download mr-1"></i>Scarica
                            </button>
                            <button type="button" 
                                    class="text-purple-600 hover:text-purple-800 text-sm font-medium"
                                    onclick="modificaDocumento({{ $documento->id }})">
                                <i class="fas fa-edit mr-1"></i>Modifica
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Dettagli espandibili -->
                <div id="dettagli-doc-{{ $documento->id }}" class="hidden p-6">
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- Informazioni Documento -->
                        <div>
                            <h6 class="text-sm font-medium text-gray-700 mb-3">
                                <i class="fas fa-info-circle mr-2"></i>Informazioni Documento
                            </h6>
                            <div class="space-y-2 text-sm">
                                <div><span class="font-medium">Formato:</span> {{ strtoupper($documento->estensione ?? 'PDF') }}</div>
                                <div><span class="font-medium">Dimensione:</span> {{ number_format(($documento->dimensione_file ?? 0) / 1024, 1) }} KB</div>
                                <div><span class="font-medium">Caricato:</span> {{ $documento->created_at?->format('d/m/Y H:i') ?? 'N/D' }}</div>
                                @if($documento->data_scadenza)
                                    <div><span class="font-medium">Scadenza:</span> 
                                        <span class="{{ $documento->data_scadenza->isPast() ? 'text-red-600 font-bold' : 'text-green-600' }}">
                                            {{ $documento->data_scadenza->format('d/m/Y') }}
                                        </span>
                                    </div>
                                @endif
                            </div>
                        </div>

                        <!-- Collegamento Spese -->
                        <div>
                            <h6 class="text-sm font-medium text-gray-700 mb-3">
                                <i class="fas fa-link mr-2"></i>Collegamento Spese
                            </h6>
                            @if($documento->importo_collegato)
                                <div class="bg-blue-50 rounded-lg p-3">
                                    <div class="flex items-center justify-between">
                                        <span class="text-sm font-medium">Importo:</span>
                                        <span class="text-lg font-bold text-blue-600">{{ number_format($documento->importo_collegato, 2) }}€</span>
                                    </div>
                                    @if($documento->categoria_spesa)
                                        <div class="text-xs text-gray-600 mt-1">Categoria: {{ $documento->categoria_spesa }}</div>
                                    @endif
                                    <button type="button" 
                                            class="mt-2 text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700"
                                            onclick="visualizzaPrevisione({{ $documento->id }})">
                                        📊 Vedi Impatto Previsione
                                    </button>
                                </div>
                            @else
                                <div class="bg-yellow-50 rounded-lg p-3">
                                    <p class="text-sm text-yellow-700 mb-2">Documento non collegato a spese</p>
                                    <button type="button" 
                                            class="text-xs bg-yellow-600 text-white px-2 py-1 rounded hover:bg-yellow-700"
                                            onclick="collegaSpesa({{ $documento->id }})">
                                        🔗 Collega Spesa
                                    </button>
                                </div>
                            @endif
                        </div>

                        <!-- Contenuto OCR -->
                        <div>
                            <h6 class="text-sm font-medium text-gray-700 mb-3">
                                <i class="fas fa-search mr-2"></i>Contenuto Ricercabile
                            </h6>
                            @if($documento->contenuto_ocr)
                                <div class="bg-green-50 rounded-lg p-3">
                                    <div class="text-xs text-gray-600 max-h-20 overflow-y-auto">
                                        {{ Str::limit($documento->contenuto_ocr, 200) }}
                                    </div>
                                    <button type="button" 
                                            class="mt-2 text-xs bg-green-600 text-white px-2 py-1 rounded hover:bg-green-700"
                                            onclick="visualizzaOCR({{ $documento->id }})">
                                        📄 Testo Completo
                                    </button>
                                </div>
                            @else
                                <div class="bg-gray-50 rounded-lg p-3">
                                    <p class="text-sm text-gray-600 mb-2">OCR non elaborato</p>
                                    <button type="button" 
                                            class="text-xs bg-purple-600 text-white px-2 py-1 rounded hover:bg-purple-700"
                                            onclick="avviaOCR({{ $documento->id }})">
                                        🔍 Elabora OCR
                                    </button>
                                </div>
                            @endif
                        </div>
                    </div>

                    <!-- Note e Commenti -->
                    @if($documento->note || $documento->descrizione)
                        <div class="mt-6 pt-6 border-t border-gray-200">
                            <h6 class="text-sm font-medium text-gray-700 mb-3">
                                <i class="fas fa-sticky-note mr-2"></i>Note e Descrizioni
                            </h6>
                            <div class="bg-gray-50 rounded-lg p-3 text-sm text-gray-700">
                                {{ $documento->note ?? $documento->descrizione }}
                            </div>
                        </div>
                    @endif
                </div>
            </div>
        @empty
            <div class="bg-purple-50 border border-purple-200 rounded-lg p-8 text-center">
                <i class="fas fa-folder-open text-purple-600 text-4xl mb-4"></i>
                <h5 class="text-lg font-medium text-purple-800 mb-2">Nessun Documento Archiviato</h5>
                <p class="text-purple-700 mb-4">
                    Inizia caricando il primo documento per attivare la gestione documentale avanzata.
                </p>
                <button type="button" 
                        class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-purple-600 hover:bg-purple-700"
                        onclick="nuovoDocumento()">
                    <i class="fas fa-plus mr-2"></i>
                    Carica Primo Documento
                </button>
            </div>
        @endforelse
    </div>
</div>

<!-- Modal Caricamento Documento -->
<div id="modal-nuovo-documento" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="fixed inset-0 bg-black bg-opacity-50"></div>
        <div class="relative bg-white rounded-lg max-w-3xl w-full p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-upload mr-2"></i>Carica Nuovo Documento
            </h3>
            
            <form id="form-nuovo-documento" enctype="multipart/form-data">
                <div class="space-y-4">
                    <!-- Upload File -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">File Documento</label>
                        <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                            <input type="file" name="file_documento" id="file_documento" 
                                   class="hidden" 
                                   accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx"
                                   onchange="mostraFileSelezionato(this)">
                            <div id="drop-zone" onclick="document.getElementById('file_documento').click()">
                                <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                                <p class="text-gray-600">Clicca per selezionare o trascina il file qui</p>
                                <p class="text-xs text-gray-500 mt-2">PDF, DOC, XLS, JPG, PNG (max 10MB)</p>
                            </div>
                            <div id="file-selected" class="hidden">
                                <i class="fas fa-file text-green-600 text-2xl mb-2"></i>
                                <p id="nome-file" class="text-green-600 font-medium"></p>
                            </div>
                        </div>
                    </div>

                    <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">Nome/Titolo</label>
                            <input type="text" name="nome" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                                   placeholder="es: Fattura Manutenzione Caldaia">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Tipologia</label>
                            <select name="tipologia" required
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500">
                                <option value="">Seleziona tipologia</option>
                                <option value="fattura">📄 Fattura</option>
                                <option value="preventivo">💰 Preventivo</option>
                                <option value="contratto">📋 Contratto</option>
                                <option value="verbale">📝 Verbale</option>
                                <option value="comunicazione">📢 Comunicazione</option>
                                <option value="delibera">⚖️ Delibera</option>
                                <option value="relazione_tecnica">🔧 Relazione Tecnica</option>
                                <option value="altro">📎 Altro</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Data Documento</label>
                            <input type="date" name="data_documento" value="{{ date('Y-m-d') }}"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Fornitore/Mittente</label>
                            <input type="text" name="fornitore"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                                   placeholder="es: Ditta XYZ">
                        </div>
                    </div>

                    <!-- Collegamento Spese -->
                    <div class="border border-blue-200 rounded-lg p-4 bg-blue-50">
                        <h5 class="font-medium text-blue-900 mb-3">💰 Collegamento Spese e Previsioni</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">Importo</label>
                                <input type="number" name="importo_collegato" step="0.01"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                       placeholder="0.00">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Categoria Spesa</label>
                                <select name="categoria_spesa"
                                        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="">Non specificata</option>
                                    <option value="spese_ordinarie">🏠 Spese Ordinarie</option>
                                    <option value="spese_straordinarie">⚡ Spese Straordinarie</option>
                                    <option value="riscaldamento">🔥 Riscaldamento</option>
                                    <option value="acqua">💧 Acqua</option>
                                    <option value="manutenzione">🔧 Manutenzione</option>
                                    <option value="amministrazione">📊 Amministrazione</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Data Scadenza</label>
                                <input type="date" name="data_scadenza"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                    </div>

                    <!-- Tag e Note -->
                    <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">Tag (separati da virgola)</label>
                            <input type="text" name="tags"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                                   placeholder="urgente, manutenzione, caldaia">
                        </div>
                        <div class="flex items-center">
                            <input type="checkbox" name="elabora_ocr" id="elabora_ocr" class="mr-2">
                            <label for="elabora_ocr" class="text-sm text-gray-700">
                                🔍 Elabora automaticamente OCR per ricerca
                            </label>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Note/Descrizione</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-purple-500"
                                  placeholder="Note aggiuntive sul documento..."></textarea>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" 
                            class="px-4 py-2 text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300"
                            onclick="chiudiModal('modal-nuovo-documento')">
                        Annulla
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
                        <i class="fas fa-save mr-2"></i>Carica e Salva
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Funzioni JavaScript per la gestione documentale

function nuovoDocumento() {
    document.getElementById('modal-nuovo-documento').classList.remove('hidden');
}

function chiudiModal(modalId) {
    document.getElementById(modalId).classList.add('hidden');
}

function mostraFileSelezionato(input) {
    const file = input.files[0];
    if (file) {
        document.getElementById('drop-zone').classList.add('hidden');
        document.getElementById('file-selected').classList.remove('hidden');
        document.getElementById('nome-file').textContent = file.name + ' (' + Math.round(file.size/1024) + ' KB)';
        
        // Auto-compila il nome se non presente
        const nomeInput = document.querySelector('input[name="nome"]');
        if (!nomeInput.value) {
            nomeInput.value = file.name.replace(/\.[^/.]+$/, "");
        }
    }
}

function ricercaGlobale(termine) {
    clearTimeout(window.ricercaTimeout);
    window.ricercaTimeout = setTimeout(() => {
        const documenti = document.querySelectorAll('.documento-item');
        
        documenti.forEach(doc => {
            const testo = doc.textContent.toLowerCase();
            const mostra = !termine || testo.includes(termine.toLowerCase());
            doc.style.display = mostra ? 'block' : 'none';
        });
    }, 300);
}

function applicaFiltri() {
    const tipologia = document.getElementById('filtro-tipologia').value;
    const tag = document.getElementById('filtro-tag').value;
    const periodo = document.getElementById('filtro-periodo').value;
    
    const documenti = document.querySelectorAll('.documento-item');
    
    documenti.forEach(doc => {
        let mostra = true;
        
        if (tipologia && doc.dataset.tipologia !== tipologia) {
            mostra = false;
        }
        
        if (tag && !doc.textContent.toLowerCase().includes(tag)) {
            mostra = false;
        }
        
        if (periodo && periodo !== '') {
            // Implementare logica filtro periodo
            const dataDoc = new Date(doc.dataset.data);
            const oggi = new Date();
            
            switch(periodo) {
                case 'oggi':
                    if (dataDoc.toDateString() !== oggi.toDateString()) mostra = false;
                    break;
                case 'settimana':
                    const settimanaFa = new Date(oggi.getTime() - 7 * 24 * 60 * 60 * 1000);
                    if (dataDoc < settimanaFa) mostra = false;
                    break;
                case 'mese':
                    if (dataDoc.getMonth() !== oggi.getMonth() || dataDoc.getFullYear() !== oggi.getFullYear()) mostra = false;
                    break;
            }
        }
        
        doc.style.display = mostra ? 'block' : 'none';
    });
}

function visualizzaDocumento(id) {
    const dettagli = document.getElementById(`dettagli-doc-${id}`);
    if (dettagli) {
        dettagli.classList.toggle('hidden');
    }
}

function scaricaDocumento(id) {
    // Implementare download
    alert(`Download documento ID: ${id} - Funzione in sviluppo`);
}

function modificaDocumento(id) {
    // Implementare modifica
    alert(`Modifica documento ID: ${id} - Funzione in sviluppo`);
}

function collegaSpesa(id) {
    // Implementare collegamento spesa
    alert(`Collegamento spesa per documento ID: ${id} - Funzione in sviluppo`);
}

function visualizzaPrevisione(id) {
    // Implementare visualizzazione impatto previsione cassa
    alert(`Impatto previsione documento ID: ${id} - Funzione in sviluppo`);
}

function avviaOCR(id) {
    // Implementare elaborazione OCR
    alert(`Elaborazione OCR documento ID: ${id} - Funzione in sviluppo`);
}

function visualizzaOCR(id) {
    // Implementare visualizzazione testo OCR completo
    alert(`Visualizzazione OCR completo documento ID: ${id} - Funzione in sviluppo`);
}

function scansioneMassiva() {
    alert('Scansione OCR massiva in sviluppo.\n\nCaratteristiche:\n- Elaborazione batch\n- Riconoscimento automatico tipologie\n- Estrazione dati strutturati\n- Collegamento automatico spese');
}

function collegaSpese() {
    alert('Collegamento spese automatico in sviluppo.\n\nCaratteristiche:\n- Riconoscimento importi\n- Categorizzazione automatica\n- Aggiornamento previsioni cassa\n- Report impatto budget');
}

// Form submission
document.getElementById('form-nuovo-documento').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    @if(isset($stabile))
        formData.append('stabile_id', {{ $stabile->id }});
    @endif
    
    // Per ora simuliamo il caricamento
    alert('Caricamento documento in sviluppo.\n\nParametri ricevuti:\n' + 
          'Nome: ' + formData.get('nome') + '\n' +
          'Tipologia: ' + formData.get('tipologia') + '\n' +
          'Importo: ' + (formData.get('importo_collegato') || 'N/D') + '€\n' +
          'OCR: ' + (formData.get('elabora_ocr') ? 'Sì' : 'No'));
    
    chiudiModal('modal-nuovo-documento');
});

// Drag and drop support
document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('drop-zone');
    
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, unhighlight, false);
    });
    
    function highlight(e) {
        dropZone.classList.add('border-purple-500', 'bg-purple-50');
    }
    
    function unhighlight(e) {
        dropZone.classList.remove('border-purple-500', 'bg-purple-50');
    }
    
    dropZone.addEventListener('drop', handleDrop, false);
    
    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        
        document.getElementById('file_documento').files = files;
        mostraFileSelezionato(document.getElementById('file_documento'));
    }
});
</script>
