@extends('layouts.adminlte')
@section('title', 'Documenti')
@section('page_title', 'Gestione Documenti')

@php
$canWriteDocumenti = Auth::user()->canManage('documenti');
$canDeleteDocumenti = Auth::user()->canDelete('documenti');
@endphp

@section('content')
<div class="card card-primary card-outline">
    <div class="card-header">
        <h3 class="card-title">
            <i class="fas fa-file mr-2"></i>Elenco Documenti
        </h3>
        @if($canWriteDocumenti)
        <button type="button" class="btn btn-sm btn-success float-right" onclick="$('#uploadModal').modal('show')">
            <i class="fas fa-plus mr-1"></i> Nuovo Documento
        </button>
        @endif
    </div>
    <div class="card-body p-0">
        <form id="massForm" method="POST">
            @csrf
            <input type="hidden" name="_method" id="formMethod" value="POST">
            @if($canDeleteDocumenti)
            <div class="p-3 bg-light border-bottom d-flex align-items-center flex-wrap gap-2">
                <span class="font-weight-bold mr-2">Azioni di massa:</span>
                <button type="button" class="btn btn-sm btn-danger" onclick="massAction('delete')">
                    <i class="fas fa-trash mr-1"></i> Elimina selezionati
                </button>
                @if($canWriteDocumenti)
                <button type="button" class="btn btn-sm btn-warning" onclick="$('#associateModal').modal('show')">
                    <i class="fas fa-link mr-1"></i> Associa a...
                </button>
                <button type="button" class="btn btn-sm btn-info" onclick="$('#updateModal').modal('show')">
                    <i class="fas fa-edit mr-1"></i> Cambia tipo/contesto
                </button>
                @endif
                <span class="ml-auto text-muted small" id="selectedCount">0 selezionati</span>
            </div>
            @endif

            <table class="table table-bordered table-hover table-striped mb-0">
                <thead class="thead-light">
                    <tr>
                        <th style="width: 40px;">
                            @if($canDeleteDocumenti)
                            <input type="checkbox" id="selectAll" onchange="toggleAll(this)">
                            @endif
                        </th>
                        <th style="width: 200px;">Nome</th>
                        <th style="width: 180px;">Nome File</th>
                        <th style="width: 100px;">Tipologia</th>
                        <th style="width: 100px;">Visibilità</th>
                        <th>Riferimento</th>
                        <th style="width: 130px;">Data Inserimento</th>
                        <th style="width: 120px;">Inserito da</th>
                        <th style="width: 130px;">Azioni</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($documenti as $documento)
                    <tr>
                        <td>
                            @if($canDeleteDocumenti)
                            <input type="checkbox" name="ids[]" value="{{ $documento->id }}" class="doc-checkbox" onchange="updateCount()">
                            @endif
                        </td>
                        <td>
                            <i class="fas fa-file text-secondary mr-1"></i>
                            {{ $documento->nome_file }}
                        </td>
                        <td class="small text-muted">{{ $documento->file_path }}</td>
                        <td>
                            <span class="badge badge-{{ $documento->tipologia === 'avatar' ? 'primary' : ($documento->tipologia === 'galleria' ? 'success' : 'secondary') }}">
                                {{ ucfirst($documento->tipologia) }}
                            </span>
                        </td>
                        <td>
                            @switch($documento->visibilita)
                                @case('individuo')
                                    <span class="badge badge-info">Individuo</span>
                                    @break
                                @case('gruppo')
                                    <span class="badge badge-success">Gruppo</span>
                                    @break
                                @case('evento')
                                    <span class="badge badge-warning">Evento</span>
                                    @break
                                @case('pubblico')
                                    <span class="badge badge-light">Pubblico</span>
                                    @break
                                @case('associazione')
                                    <span class="badge badge-dark">Associazione</span>
                                    @break
                                @case('federazione')
                                    <span class="badge badge-purple">Federazione</span>
                                    @break
                                @default
                                    <span class="text-muted">-</span>
                            @endswitch
                        </td>
                        <td>
                            @if($documento->target)
                                @if($documento->target instanceof \App\Models\Individuo)
                                    <a href="/individui/{{ $documento->target->id }}">
                                        <i class="fas fa-user text-info mr-1"></i>
                                        {{ $documento->target->cognome }} {{ $documento->target->nome }}
                                    </a>
                                @elseif($documento->target instanceof \App\Models\Gruppo)
                                    <a href="/gruppi/{{ $documento->target->id }}">
                                        <i class="fas fa-folder text-warning mr-1"></i>
                                        {{ $documento->target->nome }}
                                    </a>
                                @elseif($documento->target instanceof \App\Models\Evento)
                                    <a href="/eventi/{{ $documento->target->id }}">
                                        <i class="fas fa-calendar text-primary mr-1"></i>
                                        {{ $documento->target->nome_evento }}
                                    </a>
                                @endif
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>{{ $documento->created_at->format('d/m/Y H:i') }}</td>
                        <td>
                            @if($documento->user)
                                {{ $documento->user->name }}
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            @if($documento->file_path)
                                <button type="button" class="btn btn-xs btn-primary" onclick="previewDoc({{ $documento->id }}, '{{ $documento->mime_type }}')" title="Anteprima">
                                    <i class="fas fa-eye"></i>
                                </button>
                            @endif
                            @if($canWriteDocumenti)
                            <a href="/documenti/{{ $documento->id }}/edit" class="btn btn-xs btn-warning" title="Modifica">
                                <i class="fas fa-edit"></i>
                            </a>
                            @endif
                            @if($canDeleteDocumenti)
                            <form action="/documenti/{{ $documento->id }}" method="POST" class="d-inline">
                                @csrf @method('DELETE')
                                <button type="button" class="btn btn-xs btn-danger" onclick="deleteDocumento({{ $documento->id }}, '{{ e($documento->nome_file) }}')" title="Elimina">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="text-center text-muted py-4">
                            <i class="fas fa-file fa-2x mb-2"></i>
                            <p class="mb-0">Nessun documento presente</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </form>

        <div class="p-3 border-top">
            {{ $documenti->links() }}
        </div>
    </div>
</div>

<div class="modal fade" id="associateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-link mr-2"></i>Associa a</h5>
                <button type="button" class="close" onclick="$('#associateModal').modal('hide')">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="associateForm" method="POST" action="/documenti/mass-associate">
                    @csrf
                    <div class="form-group">
                        <label>Tipo collegamento</label>
                        <select name="target_type" class="form-control" required onchange="loadTargets(this.value)">
                            <option value="">Seleziona...</option>
                            <option value="individuo">Individuo</option>
                            <option value="gruppo">Gruppo</option>
                            <option value="evento">Evento</option>
                            <option value="mailing">Mailing List</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Riferimento</label>
                        <select name="target_id" class="form-control" required id="targetSelect">
                            <option value="">Seleziona prima il tipo...</option>
                        </select>
                    </div>
                    <input type="hidden" name="ids" id="associateIds">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="$('#associateModal').modal('hide')">Annulla</button>
                <button type="button" class="btn btn-primary" onclick="submitAssociate()">Associa</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="updateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-edit mr-2"></i>Cambia tipo/contesto</h5>
                <button type="button" class="close" onclick="$('#updateModal').modal('hide')">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="updateForm" method="POST" action="/documenti/mass-update">
                    @csrf
                    <div class="form-group">
                        <label>Nuova tipologia</label>
                        <select name="tipologia" class="form-control">
                            <option value="">Non modificare</option>
                            @foreach($tipologie as $tip)
                                <option value="{{ $tip->nome }}">{{ $tip->descrizione ?? ucfirst($tip->nome) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Nuovo contesto</label>
                        <select name="visibilita" class="form-control">
                            <option value="">Non modificare</option>
                            <option value="pubblico">Pubblico</option>
                            <option value="individuo">Individuo</option>
                            <option value="gruppo">Gruppo</option>
                            <option value="evento">Evento</option>
                            <option value="associazione">Associazione</option>
                            <option value="federazione">Federazione</option>
                            <option value="mailing">Mailing List</option>
                        </select>
                    </div>
                    <input type="hidden" name="ids" id="updateIds">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="$('#updateModal').modal('hide')">Annulla</button>
                <button type="button" class="btn btn-primary" onclick="submitUpdate()">Aggiorna</button>
            </div>
        </div>
    </div>
</div>

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

<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-upload mr-2"></i>Carica Nuovo Documento</h5>
                <button type="button" class="close" onclick="$('#uploadModal').modal('hide')">
                    <span>&times;</span>
                </button>
            </div>
            <form action="/documenti" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="form-group">
                        <label>Nome *</label>
                        <input type="text" name="nome_file" class="form-control" placeholder="Nome del documento" required>
                    </div>
                    <div class="form-group">
                        <label>Tipologia *</label>
                        <select name="tipologia" class="form-control" required>
                            @foreach($tipologie as $tip)
                                <option value="{{ $tip->nome }}">{{ $tip->descrizione ?? ucfirst($tip->nome) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Visibilità *</label>
                        <select name="visibilita" class="form-control" required id="uploadVisibilita" onchange="loadUploadTargets()">
                            <option value="">Seleziona...</option>
                            <option value="pubblico">Pubblico</option>
                            <option value="individuo">Individuo</option>
                            <option value="gruppo">Gruppo</option>
                        </select>
                    </div>
                    <div class="form-group" id="uploadTargetGroup" style="display:none;">
                        <label>Riferimento</label>
                        <select name="visibilita_target_id" class="form-control" id="uploadTargetId">
                            <option value="">Seleziona...</option>
                        </select>
                        <input type="hidden" name="visibilita_target_type" id="uploadTargetType">
                    </div>
                    <div class="form-group">
                        <label>File *</label>
                        <input type="file" name="file" class="form-control" required>
                        <small class="text-muted">Max 10MB</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="$('#uploadModal').modal('hide')">Annulla</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-upload mr-1"></i> Carica
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteConfirmModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle mr-2"></i>Conferma Eliminazione</h5>
                <button type="button" class="close text-white" onclick="$('#deleteConfirmModal').modal('hide')">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p id="deleteConfirmMessage"></p>
                <div id="deleteConfirmLinks" class="mt-3"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="$('#deleteConfirmModal').modal('hide')">Annulla</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                    <i class="fas fa-trash mr-1"></i> Elimina comunque
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="massDeleteConfirmModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle mr-2"></i>Conferma Eliminazione Multipla</h5>
                <button type="button" class="close text-white" onclick="$('#massDeleteConfirmModal').modal('hide')">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Stai per eliminare <strong id="massDeleteCount">0</strong> documenti.</p>
                <div id="massDeleteLinks" class="mt-3"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="$('#massDeleteConfirmModal').modal('hide')">Annulla</button>
                <button type="button" class="btn btn-danger" id="confirmMassDeleteBtn">
                    <i class="fas fa-trash mr-1"></i> Elimina comunque
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
const individui = @json($individui->map(fn($i) => ['id' => $i->id, 'label' => $i->cognome . ' ' . $i->nome]));
const gruppi = @json($gruppi->map(fn($g) => ['id' => $g->id, 'label' => $g->nome]));
const eventi = @json($eventi->map(fn($e) => ['id' => $e->id, 'label' => $e->nome_evento]));
const mailingLists = @json($mailingLists ?? []);

function toggleAll(source) {
    document.querySelectorAll('.doc-checkbox').forEach(cb => cb.checked = source.checked);
    updateCount();
}

function updateCount() {
    const count = document.querySelectorAll('.doc-checkbox:checked').length;
    document.getElementById('selectedCount').textContent = count + ' selezionati';
}

function getSelectedIds() {
    return Array.from(document.querySelectorAll('.doc-checkbox:checked')).map(cb => cb.value);
}

let pendingMassDeleteIds = [];

function massAction(action) {
    const ids = getSelectedIds();
    if (ids.length === 0) {
        alert('Seleziona almeno un documento');
        return;
    }
    
    if (action === 'delete') {
        fetch('/documenti/check-links', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            body: JSON.stringify({ ids: ids })
        })
        .then(response => response.json())
        .then(data => {
            pendingMassDeleteIds = ids;
            document.getElementById('massDeleteCount').textContent = ids.length;
            
            if (data.linked_count > 0) {
                let linksHtml = '<div class="alert alert-warning mb-0"><p><strong>Attenzione:</strong> ' + data.linked_count + ' documento(i) sono collegati a elementi nel database:</p><ul class="mb-0">';
                data.links.forEach(function(link) {
                    if (link.url) {
                        linksHtml += '<li><a href="' + link.url + '" target="_blank">' + link.name + '</a></li>';
                    } else {
                        linksHtml += '<li>' + link.name + '</li>';
                    }
                });
                linksHtml += '</ul></div>';
                document.getElementById('massDeleteLinks').innerHTML = linksHtml;
            } else {
                document.getElementById('massDeleteLinks').innerHTML = '<div class="alert alert-info mb-0">Nessun documento risulta collegato.</div>';
            }
            
            document.getElementById('confirmMassDeleteBtn').onclick = function() { performMassDelete(); };
            $('#massDeleteConfirmModal').modal('show');
        })
        .catch(error => {
            alert('Errore controllo collegamenti: ' + error.message);
        });
    }
}

function performMassDelete() {
    const ids = pendingMassDeleteIds;
    $('#massDeleteConfirmModal').modal('hide');
    
    fetch('/documenti/mass-destroy', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'ids=' + ids.join(',')
    })
    .then(response => {
        if (response.redirected) {
            window.location.href = response.url;
        } else {
            window.location.reload();
        }
    })
    .catch(error => {
        alert('Errore: ' + error.message);
    });
}

function deleteDocumento(id, nomeFile) {
    fetch('/documenti/' + id + '/check-links', {
        method: 'GET',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.has_links) {
            let linksHtml = '<div class="alert alert-warning mb-0"><p class="mb-2"><strong>Attenzione:</strong> Questo documento è collegato a:</p><ul class="mb-0">';
            data.links.forEach(function(link) {
                if (link.url) {
                    linksHtml += '<li><a href="' + link.url + '" target="_blank">' + link.name + '</a></li>';
                } else {
                    linksHtml += '<li>' + link.name + '</li>';
                }
            });
            linksHtml += '</ul></div>';
            document.getElementById('deleteConfirmLinks').innerHTML = linksHtml;
            document.getElementById('deleteConfirmMessage').textContent = 'Eliminare il documento "' + nomeFile + '"?';
            document.getElementById('confirmDeleteBtn').onclick = function() { performDelete(id); };
            $('#deleteConfirmModal').modal('show');
        } else {
            if (confirm('Eliminare il documento "' + nomeFile + '"?')) {
                performDelete(id);
            }
        }
    })
    .catch(error => {
        alert('Errore: ' + error.message);
    });
}

function performDelete(id) {
    fetch('/documenti/' + id, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: '_method=DELETE'
    })
    .then(response => {
        if (response.redirected) {
            window.location.href = response.url;
        } else {
            window.location.reload();
        }
    })
    .catch(error => {
        alert('Errore: ' + error.message);
    });
}

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

function loadUploadTargets() {
    const visibilita = document.getElementById('uploadVisibilita').value;
    const group = document.getElementById('uploadTargetGroup');
    const select = document.getElementById('uploadTargetId');
    const type = document.getElementById('uploadTargetType');

    if (visibilita === 'pubblico') {
        group.style.display = 'none';
        select.innerHTML = '<option value="">Seleziona...</option>';
        type.value = '';
        return;
    }

    group.style.display = 'block';
    let data = [];
    if (visibilita === 'individuo') {
        data = individui;
        type.value = 'individuo';
    } else if (visibilita === 'gruppo') {
        data = gruppi;
        type.value = 'gruppo';
    }

    select.innerHTML = '<option value="">Seleziona...</option>';
    data.forEach(item => {
        const opt = document.createElement('option');
        opt.value = item.id;
        opt.textContent = item.label;
        select.appendChild(opt);
    });
}

function loadTargets(type) {
    const select = document.getElementById('targetSelect');
    select.innerHTML = '<option value="">Caricamento...</option>';
    
    let data = [];
    if (type === 'individuo') data = individui;
    else if (type === 'gruppo') data = gruppi;
    else if (type === 'evento') data = eventi;
    else if (type === 'mailing') data = mailingLists;
    
    select.innerHTML = '<option value="">Seleziona...</option>';
    data.forEach(item => {
        const opt = document.createElement('option');
        opt.value = item.id;
        opt.textContent = item.label;
        select.appendChild(opt);
    });
}

function submitAssociate() {
    const ids = getSelectedIds();
    if (ids.length === 0) {
        alert('Seleziona almeno un documento');
        return;
    }
    const targetType = document.querySelector('#associateForm select[name="target_type"]').value;
    const targetId = document.getElementById('targetSelect').value;
    if (!targetType || !targetId) {
        alert('Seleziona tipo e riferimento');
        return;
    }
    document.getElementById('associateIds').value = ids.join(',');
    document.getElementById('associateForm').submit();
}

function submitUpdate() {
    const ids = getSelectedIds();
    console.log('Selected IDs:', ids);
    if (ids.length === 0) {
        alert('Seleziona almeno un documento');
        return;
    }
    const tipologia = document.querySelector('#updateForm select[name="tipologia"]').value;
    const visibilita = document.querySelector('#updateForm select[name="visibilita"]').value;
    console.log('Tipologia:', tipologia, 'Visibilita:', visibilita);
    if (!tipologia && !visibilita) {
        alert('Seleziona almeno una tipologia o un contesto da modificare');
        return;
    }
    document.getElementById('updateIds').value = ids.join(',');
    console.log('Form submitting with IDs:', document.getElementById('updateIds').value);
    document.getElementById('updateForm').submit();
}
</script>
@endsection