<?php
// Assicurati che idhome sia passato
if (!isset($idhome) || $idhome <= 0) {
    die("Errore: ID immobile non valido.");
}

// Recupera i dettagli della casa
$stmt = $pdo->prepare("SELECT name, address, zip, city, country FROM home WHERE idhome = ? AND iduser = ?");
$stmt->execute([$idhome, $iduserlogin]);
$homeData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$homeData) {
    die("Errore: Casa non trovata o accesso non autorizzato.");
}

// Recupera le pagine disponibili nella tabella 'pages'
$stmt = $pdo->query("SELECT * FROM pages ORDER BY namepages");
$pages = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $pages[] = $row;
}

// Imposta lo slug predefinito
$docpage = isset($_GET['docpage']) ? $_GET['docpage'] : 'legal';

// Recupera tutti i tag disponibili
$stmt = $pdo->query("SELECT tag_id, tag_name FROM tags ORDER BY tag_name");
$allTags = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- Contenuto del tab Documenti -->
<div class="tab-pane fade show active" id="documenti" role="tabpanel" aria-labelledby="documenti-tab">
    <div class="card">
        <div class="card-body">
            <!-- Dettagli della Casa -->
            <div class="row align-items-center mb-4">
                <div class="col-sm-8">
                    <h4 class="page-title m-0">Documenti per la Casa: <?php echo htmlspecialchars($homeData['name']); ?></h4>
                    <p class="mb-0"><strong>Indirizzo:</strong> <?php echo htmlspecialchars($homeData['address']) . ', ' . htmlspecialchars($homeData['city']) . ' ' . htmlspecialchars($homeData['zip']); ?></p>
                </div>
            </div>

            <?php
            function getCategoryIcon($index)
            {
                $icons = [
                    'fas fa-balance-scale', // Icona per categoria 0
                    'fas fa-file-alt',      // Icona per categoria 1
                    'fas fa-home',          // Icona per categoria 2
                    'fas fa-building',      // Icona per categoria 3
                    'fas fa-lock',          // Icona per categoria 4
                ];
                return $icons[$index % count($icons)] ?? 'fas fa-folder';
            }
            ?>

            <!-- Sezione filtri -->
            <div class="filter-section mb-4 p-3 bg-light rounded shadow-sm position-relative">
                <div class="row align-items-center">
                    <!-- Contenitore per le icone delle categorie -->
                    <div class="col-12 mb-3">
                        <div class="category-icons-container">
                            <?php
                            $stmt = $pdo->query("SELECT * FROM pages ORDER BY namepages");
                            $pages = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            foreach ($pages as $index => $page) {
                                $slug = htmlspecialchars($page['slug']);
                                $name = ucfirst(htmlspecialchars($page['namepages']));
                                $iconClass = getCategoryIcon($index);
                                echo "<div class='category-icon' data-slug='{$slug}' data-index='{$index}'>
                                    <i class='{$iconClass}'></i>
                                    <div class='category-name'>{$name}</div>
                                  </div>";
                            }
                            ?>
                        </div>
                        <!-- Contenitore per le sotto-icone delle sezioni con preloader -->
                        <div class="section-icons-wrapper position-relative">
                            <div class="section-icons-container" style="display: none;"></div>
                            <div class="preloader" style="display: none;">
                                <div class="preloader-inner"></div>
                            </div>
                        </div>
                    </div>
                    <!-- Campo di ricerca per nome/sezione, tag e checkbox -->
                    <div class="col-12">
                        <div class="row">
                            <!-- Campo di ricerca per nome/sezione -->
                            <div class="col-md-6 position-relative mt-3">
                                <label for="documentSearch" class="form-label mb-1 fw-bold">Cerca per nome o sezione:</label>
                                <input type="text" id="documentSearch" class="form-control w-100" placeholder="Sezione o documento..." autocomplete="off">
                                <div id="searchResults" class="list-group dropdown-menu show w-100" style="position: absolute; max-height: 200px; overflow-y: auto; z-index: 1000; display: none;"></div>
                            </div>
                            <!-- Dropdown per i tag -->
                            <div class="col-md-6 position-relative mt-3">
                                <label class="form-label mb-1 fw-bold">Filtra per tag:</label>
                                <div class="dropdown">
                                    <button class="btn btn-outline-secondary dropdown-toggle w-100" type="button" id="tagDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                        Seleziona tag...
                                    </button>
                                    <div class="dropdown-menu w-100" aria-labelledby="tagDropdown">
                                        <?php foreach ($allTags as $tag): ?>
                                            <a class="dropdown-item tag-option" href="#" data-tag-id="<?php echo $tag['tag_id']; ?>" data-tag-name="<?php echo htmlspecialchars($tag['tag_name']); ?>">
                                                <?php echo htmlspecialchars($tag['tag_name']); ?>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <!-- Contenitore per i badge selezionati -->
                                <div id="selectedTags" class="d-flex flex-wrap gap-2 mt-2"></div>
                            </div>
                        </div>
                        <!-- Checkbox -->
                        <div class="form-check form-switch mt-2">
                            <input class="form-check-input" type="checkbox" id="showOnlyRequired">
                            <label class="form-check-label" for="showOnlyRequired">
                                <i class="fas fa-filter me-1"></i> Solo obbligatori
                            </label>
                        </div>
                    </div>
                </div>
                <!-- Preloader per i documenti -->
                <div class="document-preloader" style="display: none;">
                    <div class="preloader-inner"></div>
                </div>
            </div>
            <!-- Contenitore per i documenti dinamici -->
            <div id="documentSections" class="accordion"></div>
        </div>
    </div>
</div>

<style>
    /* Stile per la sezione filtri */
    .filter-section {
        background-color: #f8f9fa;
        border: 1px solid #e0e0e0;
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    }

    /* Stile per il contenitore delle icone delle categorie */
    .category-icons-container {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin-bottom: 10px;
    }

    /* Stile per le icone delle categorie */
    .category-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        padding: 10px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        background-color: #fff;
        transition: all 0.3s ease;
        min-width: 80px;
        max-width: 120px;
        text-align: center;
    }

    .category-icon:hover,
    .category-icon.active {
        border-color: #007bff;
        background-color: #e6f5ff;
    }

    .category-icon i {
        font-size: 1.5rem;
        color: #007bff;
        margin-bottom: 5px;
    }

    .category-name {
        font-size: 0.85rem;
        color: #333;
        word-wrap: break-word;
        overflow-wrap: break-word;
        text-align: center;
        padding: 0 5px;
        min-height: 2.5em;
    }

    /* Stile per il contenitore delle sotto-icone delle sezioni */
    .section-icons-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
        padding-top: 10px;
        border-top: 1px solid #e0e0e0;
    }

    .section-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        padding: 8px;
        border: 2px solid #e0e0e0;
        border-radius: 6px;
        background-color: #fff;
        transition: all 0.3s ease;
        min-width: 70px;
        max-width: 100px;
        text-align: center;
    }

    .section-icon:hover,
    .section-icon.active {
        border-color: #0056b3;
        background-color: #cce5ff;
    }

    .section-icon i {
        font-size: 1.2rem;
        color: #0056b3;
        margin-bottom: 3px;
    }

    /* Mostra sempre il nome della sezione */
    .section-name {
        font-size: 0.8rem;
        color: #333;
        word-wrap: break-word;
        overflow-wrap: break-word;
        text-align: center;
        padding: 0 5px;
        min-height: 2em;
        display: block;
    }

    /* Stile per il campo di ricerca */
    .form-control {
        border-radius: 6px;
        font-size: 0.95rem;
        padding: 8px 12px;
        transition: border-color 0.3s ease;
    }

    .form-control:focus {
        border-color: #007bff;
        box-shadow: 0 0 5px rgba(0, 123, 255, 0.2);
    }

    /* Stile per i risultati della ricerca */
    #searchResults {
        border-radius: 6px;
        border: 1px solid #ddd;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }

    #searchResults .list-group-item {
        font-size: 0.9rem;
        padding: 8px 12px;
    }

    #searchResults .list-group-item:hover {
        background-color: #f1f3f5;
    }

    /* Stile per il dropdown dei tag */
    .dropdown-menu {
        max-height: 200px;
        overflow-y: auto;
    }

    .tag-option:hover {
        background-color: #f1f3f5;
        cursor: pointer;
    }

    /* Stile per i badge selezionati */
    #selectedTags .tag-badge {
        background-color: #e6f0fa;
        /* Colore chiaro per i badge selezionati */
        color: #2c3e50;
        font-size: 0.9rem;
        padding: 0.4em 0.8em;
        border-radius: 10px;
        display: flex;
        align-items: center;
        margin-bottom: 5px;
    }

    #selectedTags .tag-badge .remove-tag {
        font-size: 0.7rem;
        margin-left: 5px;
        cursor: pointer;
        color: #dc3545;
    }

    /* Stile per il titolo del documento */
    .document-title {
        font-weight: bold;
        font-size: 1.1rem;
        color: #2c3e50;
    }

    /* Stile per il preloader */
    .preloader,
    .document-preloader {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.8);
        z-index: 10;
    }

    .preloader-inner {
        width: 50px;
        height: 50px;
        border: 5px solid #f3f3f3;
        border-top: 5px solid #007bff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    /* Responsive */
    @media (max-width: 767.98px) {
        .filter-section {
            padding: 10px;
        }

        .category-icons-container,
        .section-icons-container {
            justify-content: center;
        }

        .category-icon,
        .section-icon {
            min-width: 70px;
            max-width: 90px;
        }

        .category-name,
        .section-name {
            font-size: 0.75rem;
        }

        .document-title {
            font-size: 1rem;
        }

        .tag-badge {
            font-size: 0.8rem;
            padding: 0.3em 0.6em;
        }
    }
</style>

<script>
    $(document).ready(function() {
        let idhome = <?php echo $idhome; ?>;
        let currentCategory = '<?php echo $docpage; ?>';
        let currentSection = null;
        let selectedTags = []; // Array per tenere traccia dei tag selezionati

        // Caricamento iniziale: non carichiamo documenti finché non selezioniamo una categoria o cerchiamo

        // Gestione del clic sulle icone delle categorie
        $('.category-icon').on('click', function() {
            const slug = $(this).data('slug');
            if (currentCategory === slug) return;

            currentCategory = slug;
            currentSection = null;
            $('.category-icon').removeClass('active');
            $(this).addClass('active');
            $('.section-icons-container').hide().empty();
            $('#documentSections').empty();
            $('.preloader').show();
            loadSections(slug);
        });

        // Gestione del clic sulle icone delle sezioni
        $(document).on('click', '.section-icon', function() {
            const sectionId = $(this).data('section-id');
            const sectionName = $(this).find('.section-name').text();
            if (currentSection === sectionId) return;

            currentSection = sectionId;
            $('.section-icon').removeClass('active');
            $(this).addClass('active');
            $('.document-preloader').show();
            loadDocuments(currentCategory, sectionId, sectionName);
        });

        // Gestione del checkbox "Solo obbligatori"
        $("#showOnlyRequired").on('change', function() {
            if (currentSection) {
                const sectionName = $('.section-icon.active .section-name').text();
                $('.document-preloader').show();
                loadDocuments(currentCategory, currentSection, sectionName);
            }
        });

        // Carica le sezioni per una categoria
        function loadSections(slug) {
            $.ajax({
                url: 'get-sections.php',
                method: 'GET',
                data: {
                    slug: slug,
                    idhome: idhome
                },
                dataType: 'json',
                success: function(response) {
                    $('.preloader').hide();
                    if (response.error) {
                        console.error(response.error);
                        return;
                    }
                    const sections = response.sections || [];
                    let html = '';
                    sections.forEach(section => {
                        html += `<div class='section-icon' data-section-id='${md5(section.section_name)}'>
                                <i class='fas fa-folder'></i>
                                <div class='section-name'>${section.section_name}</div>
                             </div>`;
                    });
                    $('.section-icons-container').html(html).slideDown();
                },
                error: function(xhr, status, error) {
                    $('.preloader').hide();
                    console.error('Errore nel caricamento delle sezioni:', error);
                }
            });
        }

        // Carica tutti i documenti e le sezioni per la ricerca
        let allDocuments = [];
        <?php
        $stmt = $pdo->query("
            SELECT d.document_id, d.document_name, p.slug, s.section_name, GROUP_CONCAT(t.tag_name) AS tags
            FROM documents d 
            LEFT JOIN sections s ON d.idsections = s.idsections 
            LEFT JOIN pages p ON d.page_id = p.idpages 
            LEFT JOIN document_tags dt ON d.document_id = dt.document_id
            LEFT JOIN tags t ON dt.tag_id = t.tag_id
            GROUP BY d.document_id, d.document_name, p.slug, s.section_name
            ORDER BY s.section_name, d.document_name
        ");
        while ($doc = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $tags = $doc['tags'] ? addslashes(htmlspecialchars($doc['tags'])) : '';
            echo "allDocuments.push({
                id: '{$doc['document_id']}',
                name: '" . addslashes(htmlspecialchars($doc['document_name'])) . "',
                section: '" . addslashes(htmlspecialchars($doc['section_name'])) . "',
                slug: '" . addslashes(htmlspecialchars($doc['slug'])) . "',
                tags: '{$tags}'
            });\n";
        }
        ?>

        // Gestione della ricerca dinamica per nome/sezione
        $('#documentSearch').on('input', function() {
            const searchTerm = $(this).val().toLowerCase().trim();
            $('#searchResults').empty().hide();

            if (searchTerm === '') {
                return;
            }

            const results = allDocuments.filter(item =>
                item.name.toLowerCase().includes(searchTerm) ||
                item.section.toLowerCase().includes(searchTerm)
            );

            if (results.length > 0) {
                let html = '';
                results.forEach(result => {
                    html += `<a href="#" class="list-group-item list-group-item-action" data-slug="${result.slug}" data-section="${md5(result.section)}" data-name="${result.name}">
                        ${result.name} (Sezione: ${result.section}${result.tags ? ', Tag: ' + result.tags : ''})
                    </a>`;
                });
                $('#searchResults').html(html).show();

                $('#searchResults .list-group-item').on('click', function(e) {
                    e.preventDefault();
                    const slug = $(this).data('slug');
                    const sectionId = $(this).data('section');
                    const documentName = $(this).data('name');

                    currentCategory = slug;
                    currentSection = sectionId;
                    $('.category-icon').removeClass('active');
                    $('.category-icon[data-slug="' + slug + '"]').addClass('active');
                    $('.section-icons-container').hide().empty();
                    $('#documentSections').empty();
                    $('.document-preloader').show();

                    // Carica direttamente i documenti senza passare per le sezioni
                    loadDocuments(slug, sectionId, null, documentName);

                    $('#documentSearch').val('');
                    $('#searchResults').hide();
                });
            }
        });

        // Gestione del dropdown dei tag
        $('.tag-option').on('click', function(e) {
            e.preventDefault();
            const tagId = $(this).data('tag-id');
            const tagName = $(this).data('tag-name');

            if (!selectedTags.some(t => t.id === tagId)) {
                selectedTags.push({
                    id: tagId,
                    name: tagName
                });
                updateSelectedTags();
                if (currentSection) {
                    const sectionName = $('.section-icon.active .section-name').text();
                    $('.document-preloader').show();
                    loadDocuments(currentCategory, currentSection, sectionName);
                }
            }
        });

        // Funzione per aggiornare i badge dei tag selezionati
        function updateSelectedTags() {
            $('#selectedTags').empty();
            selectedTags.forEach(tag => {
                $('#selectedTags').append(`
                    <span class="tag-badge">
                        ${tag.name}
                        <span class="remove-tag" data-tag-id="${tag.id}">&times;</span>
                    </span>
                `);
            });
            $('.remove-tag').on('click', function(e) {
                e.preventDefault();
                const tagId = $(this).data('tag-id');
                selectedTags = selectedTags.filter(t => t.id !== tagId);
                updateSelectedTags();
                if (currentSection) {
                    const sectionName = $('.section-icon.active .section-name').text();
                    $('.document-preloader').show();
                    loadDocuments(currentCategory, currentSection, sectionName);
                }
            });
        }

        // Chiudi i risultati della ricerca se clicchi fuori
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.input-group, #searchResults').length) {
                $('#searchResults').hide();
            }
        });

        function loadDocuments(slug, targetSectionId = null, sectionName = null, searchName = null) {
            const showOnlyRequired = $("#showOnlyRequired").is(":checked");
            const tagIds = selectedTags.map(t => t.id);

            $.ajax({
                url: 'get-documents.php',
                method: 'GET',
                data: {
                    slug: slug,
                    idhome: idhome,
                    showOnlyRequired: showOnlyRequired,
                    sectionId: targetSectionId ? targetSectionId : null,
                    tags: tagIds.length > 0 ? tagIds.join(',') : null,
                    searchName: searchName ? searchName : null
                },
                dataType: 'json',
                success: function(response) {
                    $('.document-preloader').hide();
                    if (response.error) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Errore',
                            text: response.error
                        });
                        return;
                    }

                    const homeName = response.homeName || 'Nome non disponibile';
                    const homeAddress = response.homeAddress || 'Indirizzo non disponibile';
                    const documents = response.documents || {};
                    const loadedDocuments = response.loadedDocuments || {};

                    $('.page-title').text(`Documenti per la Casa: ${homeName}`);
                    $('p.mb-0 strong').text(`Indirizzo: ${homeAddress}`);

                    $('#documentSections').empty();
                    let html = '';
                    let sectionCount = 0;

                    for (let sectionKey in documents) {
                        if (sectionCount >= 100) {
                            console.error('Troppi loop nelle sezioni, possibile errore nei dati');
                            break;
                        }
                        sectionCount++;

                        const displaySectionName = sectionName || sectionKey;

                        html += `
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="heading-${md5(sectionKey)}"></h2>
                        <div id="collapse-${md5(sectionKey)}" class="accordion-collapse collapse" aria-labelledby="heading-${md5(sectionKey)}" data-parent="#documentSections">
                            <div class="accordion-body">
                    `;

                        let docCount = 0;
                        (documents[sectionKey] || []).forEach(document => {
                            if (docCount >= 100) {
                                console.error('Troppi loop nei documenti, possibile errore nei dati');
                                return;
                            }
                            docCount++;

                            html += `
                        <div class="card card-body mb-4">
                            <div class="document-header d-flex justify-content-between align-items-center p-3 mb-3" style="background-color: #e8f5e9; border-radius: 8px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
                                <div>
                                    <span class="document-title fw-bold">${document.document_name || 'Documento senza nome'}</span>
                                    ${document.is_required ? '<span class="badge bg-danger ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Obbligatorio</span>' : ''}
                                    ${document.max_documents > 0 ? `<span class="badge bg-info ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Max: ${document.max_documents}</span>` : ''}
                                    ${document.tags ? `<span class="badge bg-secondary ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Tag: ${document.tags}</span>` : ''}
                                </div>
                                <button class="btn btn-sm btn-outline-primary toggle-dropzone" data-target="#dropzone-${document.document_id}">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                            <div class="dropzone-container collapse" id="dropzone-${document.document_id}">
                                <div class="dropzone mb-3" id="dropzone-area-${document.document_id}">
                                    <div class="dz-message">
                                        <i class="fas fa-cloud-upload-alt"></i><br>
                                        Trascina qui i documenti o clicca per caricarli
                                    </div>
                                </div>
                                <div class="text-center mt-3">
                                    <label class="btn btn-outline-primary btn-sm">
                                        <i class="fas fa-camera"></i> Scatta una foto
                                        <input type="file" accept="image/*" capture="camera" id="cameraInput-${document.document_id}" class="d-none" onchange="uploadFromCamera(this, '${document.document_id}')">
                                    </label>
                                </div>
                            </div>
                            <div class="loaded-documents-section" id="loaded-documents-${document.document_id}">
                                ${(loadedDocuments[document.document_id] || []).length > 0 ? `
                                    <h6 class="mt-4">Documenti già caricati:</h6>
                                    <table class="table table-bordered document-list-table" id="table-${document.document_id}">
                                        <thead>
                                            <tr>
                                                <th>Nome Documento</th>
                                                <th>Data Caricamento</th>
                                                <th>Azioni</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${loadedDocuments[document.document_id].map(doc => `
                                                <tr>
                                                    <td><a href="homedocuments/${doc.filename}" target="_blank">${doc.filename}</a></td>
                                                    <td>${doc.created_at}</td>
                                                    <td><button class="btn btn-danger btn-sm delete-document" data-id="${doc.id}" data-file="${doc.filename}">Elimina</button></td>
                                                </tr>
                                            `).join('')}
                                        </tbody>
                                    </table>
                                ` : ''}
                            </div>
                        </div>
                    `;
                        });

                        html += `
                            </div>
                        </div>
                    </div>
                `;
                    }
                    $('#documentSections').html(html);

                    if (targetSectionId) {
                        setTimeout(() => {
                            const collapseElement = $(`#collapse-${targetSectionId}`);
                            if (collapseElement.length) {
                                $('.accordion-collapse.collapse').collapse('hide');
                                collapseElement.collapse('show');
                                $('html, body').animate({
                                    scrollTop: collapseElement.offset().top - 100
                                }, 100);
                            }
                        }, 100);
                    }

                    // Rinizializza Dropzone per ogni documento
                    for (let sectionName in documents) {
                        (documents[sectionName] || []).forEach(document => {
                            if (!Dropzone.instances.some(dz => dz.element.id === `dropzone-area-${document.document_id}`)) {
                                new Dropzone(`#dropzone-area-${document.document_id}`, {
                                    url: "upload-document.php",
                                    paramName: "file",
                                    maxFiles: document.max_documents || 1,
                                    maxFilesize: 5,
                                    addRemoveLinks: true,
                                    acceptedFiles: "image/*,application/pdf",
                                    dictDefaultMessage: "Trascina qui i file o clicca per caricarli",
                                    dictRemoveFile: "Rimuovi",
                                    previewTemplate: `
                <div class="dz-preview dz-file-preview">
                    <div class="dz-image"><img data-dz-thumbnail /></div>
                    <div class="dz-details">
                        <div class="dz-filename"><span data-dz-name></span></div>
                        <div class="dz-size"><span data-dz-size></span></div>
                    </div>
                    <div class="dz-progress">
                        <span class="dz-upload" data-dz-uploadprogress></span>
                    </div>
                    <div class="dz-error-message"><span data-dz-errormessage></span></div>
                    <div class="dz-success-mark">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="dz-error-mark">
                        <i class="fas fa-times-circle"></i>
                    </div>
                </div>
            `,
                                    init: function() {
                                        this.on("success", function(file, response) {
                                            try {
                                                let parsedResponse = typeof response === "string" ? JSON.parse(response) : response;

                                                if (parsedResponse.success) {
                                                    updateDocumentTable(document.document_id, parsedResponse);
                                                    Swal.fire({
                                                        icon: "success",
                                                        title: "Caricamento completato",
                                                        text: "Il documento è stato caricato con successo.",
                                                        timer: 1500,
                                                        showConfirmButton: false
                                                    });
                                                } else {
                                                    Swal.fire({
                                                        icon: "error",
                                                        title: "Errore",
                                                        text: parsedResponse.message || "Errore nel caricamento",
                                                    });
                                                }
                                            } catch (error) {
                                                console.error("Errore nel parsing della risposta:", error);
                                                Swal.fire({
                                                    icon: "error",
                                                    title: "Errore",
                                                    text: "Risposta dal server non valida.",
                                                });
                                            }
                                            this.removeFile(file);
                                        });

                                        this.on("error", function(file, errorMessage) {
                                            Swal.fire({
                                                icon: "error",
                                                title: "Errore",
                                                text: errorMessage || "Si è verificato un problema.",
                                            });
                                            this.removeFile(file);
                                        });
                                    },
                                    sending: function(file, xhr, formData) {
                                        formData.append("idhome", idhome);
                                        formData.append("document_id", document.document_id);
                                    }
                                });
                            }
                        });
                    }

                    // Rinizializza il toggle Dropzone
                    document.querySelectorAll('.toggle-dropzone').forEach(button => {
                        button.addEventListener('click', function() {
                            const target = document.querySelector(this.dataset.target);
                            const icon = this.querySelector('i');

                            if (target.classList.contains('show')) {
                                target.classList.remove('show');
                                target.style.display = 'none';
                                icon.classList.remove('fa-minus');
                                icon.classList.add('fa-plus');
                            } else {
                                target.classList.add('show');
                                target.style.display = 'block';
                                icon.classList.remove('fa-plus');
                                icon.classList.add('fa-minus');
                            }
                        });
                    });

                    // Rinizializza la gestione dei documenti eliminati
                    $(document).on("click", ".delete-document", function() {
                        const documentId = $(this).data("id");
                        const fileName = $(this).data("file");
                        const $row = $(this).closest("tr");
                        const $table = $row.closest("table");
                        const $section = $table.closest('.loaded-documents-section');

                        Swal.fire({
                            title: "Sei sicuro?",
                            text: "Questa azione eliminerà il documento in modo permanente.",
                            icon: "warning",
                            showCancelButton: true,
                            confirmButtonColor: "#d33",
                            cancelButtonColor: "#3085d6",
                            confirmButtonText: "Sì, elimina",
                            cancelButtonText: "Annulla",
                        }).then((result) => {
                            if (result.isConfirmed) {
                                $.ajax({
                                    url: "delete-document.php",
                                    type: "POST",
                                    data: {
                                        document_id: documentId,
                                        file_name: fileName,
                                    },
                                    success: function(response) {
                                        try {
                                            const parsedResponse = typeof response === "string" ? JSON.parse(response) : response;

                                            if (parsedResponse.success) {
                                                $row.remove();
                                                if ($table.find("tbody tr").length === 0) {
                                                    $section.empty();
                                                }
                                                Swal.fire({
                                                    icon: "success",
                                                    title: "Eliminato",
                                                    text: "Documento eliminato con successo.",
                                                    timer: 1500,
                                                    showConfirmButton: false,
                                                });
                                            } else {
                                                Swal.fire({
                                                    icon: "error",
                                                    title: "Errore",
                                                    text: parsedResponse.message || "Impossibile eliminare il documento.",
                                                });
                                            }
                                        } catch (error) {
                                            console.error("Errore durante l'eliminazione:", error);
                                            Swal.fire({
                                                icon: "error",
                                                title: "Errore",
                                                text: "Risposta dal server non valida.",
                                            });
                                        }
                                    },
                                    error: function() {
                                        Swal.fire({
                                            icon: "error",
                                            title: "Errore",
                                            text: "Si è verificato un problema con la richiesta.",
                                        });
                                    },
                                });
                            }
                        });
                    });

                    // Funzione per aggiornare dinamicamente la tabella dei documenti
                    function updateDocumentTable(documentId, parsedResponse) {
                        const sectionId = `#loaded-documents-${documentId}`;
                        const $section = $(sectionId);

                        if (!$section.length) {
                            console.error('Sezione non trovata per documentId:', documentId);
                            return;
                        }

                        let $table = $section.find(`#table-${documentId}`);
                        if ($table.length === 0) {
                            const tableHtml = `
                            <h6 class="mt-4">Documenti già caricati:</h6>
                            <table class="table table-bordered document-list-table" id="table-${documentId}">
                                <thead>
                                    <tr>
                                        <th>Nome Documento</th>
                                        <th>Data Caricamento</th>
                                        <th>Azioni</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><a href="homedocuments/${parsedResponse.fileName}" target="_blank">${parsedResponse.fileName}</a></td>
                                        <td>${parsedResponse.uploadDate}</td>
                                        <td><button class="btn btn-danger btn-sm delete-document" data-id="${parsedResponse.documentId}" data-file="${parsedResponse.fileName}">Elimina</button></td>
                                    </tr>
                                </tbody>
                            </table>
                        `;
                            $section.html(tableHtml);
                        } else {
                            const row = `
                            <tr>
                                <td><a href="homedocuments/${parsedResponse.fileName}" target="_blank">${parsedResponse.fileName}</a></td>
                                <td>${parsedResponse.uploadDate}</td>
                                <td><button class="btn btn-danger btn-sm delete-document" data-id="${parsedResponse.documentId}" data-file="${parsedResponse.fileName}">Elimina</button></td>
                            </tr>`;
                            $table.find("tbody").append(row);
                        }
                    }

                    // Funzione per caricare un file dalla fotocamera
                    window.uploadFromCamera = function(input, documentId) {
                        if (input.files && input.files[0]) {
                            let formData = new FormData();
                            formData.append("file", input.files[0]);
                            formData.append("idhome", idhome);
                            formData.append("document_id", documentId);

                            $.ajax({
                                url: "upload-document.php",
                                type: "POST",
                                data: formData,
                                processData: false,
                                contentType: false,
                                success: function(response) {
                                    try {
                                        let parsedResponse = typeof response === "string" ? JSON.parse(response) : response;

                                        if (parsedResponse.success) {
                                            updateDocumentTable(documentId, parsedResponse);
                                            Swal.fire({
                                                icon: "success",
                                                title: "Caricamento completato",
                                                text: "La foto è stata caricata con successo.",
                                                timer: 1500,
                                                showConfirmButton: false
                                            });
                                        } else {
                                            Swal.fire({
                                                icon: "error",
                                                title: "Errore",
                                                text: parsedResponse.message || "Errore nel caricamento",
                                            });
                                        }
                                    } catch (error) {
                                        console.error("Errore nel parsing della risposta:", error);
                                        Swal.fire({
                                            icon: "error",
                                            title: "Errore",
                                            text: "Risposta dal server non valida.",
                                        });
                                    }
                                },
                                error: function() {
                                    Swal.fire({
                                        icon: "error",
                                        title: "Errore",
                                        text: "Si è verificato un problema con il caricamento.",
                                    });
                                }
                            });
                        }
                    };
                },
                error: function(xhr, status, error) {
                    $('.document-preloader').hide();
                    Swal.fire({
                        icon: 'error',
                        title: 'Errore',
                        text: 'Impossibile caricare i documenti: ' + error
                    });
                }
            });
        }
    });
</script>