<?php include('include/headscript.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);
// Recupera l'id utente loggato
$iduserlogin = $_SESSION['iduserlogin'];
// Recupera l'id della casa dall'URL
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;

// Recupera lo sharing_type e le sezioni condivise per questa casa
$querySharing = $conn->prepare("
    SELECT sharing_type, shared_sections, iduser
    FROM home_sharing 
    WHERE idhome = ? AND idshareduser = ? AND status = 'accepted'
");
$querySharing->bind_param('ii', $idhome, $iduserlogin);
$querySharing->execute();
$resultSharing = $querySharing->get_result();
$sharingData = $resultSharing->fetch_assoc();

if (!$sharingData) {
    die("Accesso negato o condivisione non trovata.");
}

$sharingType = $sharingData['sharing_type'];
$sharingIdUser = $sharingData['iduser'];
$sharedSections = json_decode($sharingData['shared_sections'], true);

// Recupera i dettagli della casa
$queryHome = $conn->prepare("SELECT * FROM home WHERE idhome = ? AND iduser = ?");
$queryHome->bind_param('ii', $idhome, $sharingIdUser);
$queryHome->execute();
$resultHome = $queryHome->get_result();
$homeData = $resultHome->fetch_assoc();

// Imposta lo slug predefinito o usa quello passato via GET
$docpage = isset($_GET['docpage']) ? $_GET['docpage'] : 'legal';

// Recupera le pagine disponibili nella tabella 'pages'
$queryPages = $conn->query("SELECT * FROM pages ORDER BY namepages");
$pages = [];
while ($row = $queryPages->fetch_assoc()) {
    $pages[] = $row;
}
?>

<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Documenti Condivisi della Casa</title>

    <!-- Bootstrap 4 CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/dripicons/2.0.0/webfont.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />
    <!-- Custom CSS -->
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">
    <!-- Dropzone CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" />
    <!-- Select2 CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet">

    <style>
        /* Stili uniformati con la prima pagina */
        .section-header {
            background-color: #f8f9fa;
            border: 1px solid #007bff;
            color: #007bff;
            font-size: 1.2rem;
            font-weight: bold;
            padding: 15px 20px;
            text-align: left;
            width: 100%;
        }

        .section-header:hover {
            background-color: #007bff;
            color: #fff;
        }

        .accordion-button {
            background-color: #322999;
            color: white;
            font-size: 1.2rem;
            font-weight: bold;
            text-align: left;
            border: 1px solid #007bff;
            border-radius: 0 !important;
            box-shadow: none !important;
        }

        .accordion-button:hover {
            background-color: #007bff;
            color: white;
        }

        .accordion-button i {
            font-size: 1.5rem;
            color: #fff562;
            margin-right: 10px;
        }

        .accordion-body {
            padding: 20px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
        }

        .dropzone {
            background-color: #f0f8ff;
            border: 2px dashed #007bff;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }

        .dropzone:hover {
            background-color: #e6f5ff;
        }

        .dropzone-container {
            padding: 10px;
            background-color: #f9f9f9;
            border: 1px dashed #007bff;
            border-radius: 8px;
            display: none;
        }

        .input-group {
            max-width: 400px;
            margin: 0 auto;
        }

        #documentSearch {
            border-radius: 0.25rem 0 0 0.25rem;
        }

        #searchResults {
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 0.25rem;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

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

        @media (max-width: 767.98px) {
            .input-group {
                max-width: 100%;
                margin-top: 10px;
            }

            #pageSelectDropdown,
            #documentSearch {
                width: 100% !important;
            }
        }

        .btn-warning {
            background-color: #ffca2c;
            /* Un giallo più brillante */
            border-color: #ffca2c;
            color: #212529;
            /* Testo scuro per contrasto */
        }

        .btn-warning:hover {
            background-color: #e0b026;
            /* Giallo più scuro al passaggio del mouse */
            border-color: #e0b026;
            color: #212529;
        }
    </style>
</head>

<body class="fixed-left">
    <div id="wrapper">
        <?php include('include/navigationbar.php'); ?>
        <div class="content-page">
            <div class="content">
                <?php include('include/topbar.php'); ?>
                <br>
                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <!-- Dettagli della Casa -->
                        <div class="row align-items-center">
                            <div class="col-sm-8">
                                <h4 class="page-title m-0">Documenti Condivisi 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 class="col-sm-4 text-right">
                                <button onclick="history.back()" class="btn btn-dark">
                                    <i class="fas fa-arrow-left"></i> Torna indietro
                                </button>
                                <a href="download-shared-documents.php?idhome=<?php echo $idhome; ?>" class="btn btn-warning" id="downloadZipBtn">
                                    <i class="fas fa-file-archive"></i> Scarica Zip
                                </a>
                            </div>
                        </div>

                        <div class="row mb-4">
                            <div class="col-12 col-md-6 text-center text-md-start">
                                <label for="pageSelectDropdown" class="fw-bold d-block mb-2">Seleziona Categoria:</label>
                                <select id="pageSelectDropdown" class="form-control w-100 w-md-auto">
                                    <?php foreach ($pages as $page) { ?>
                                        <option value="<?php echo htmlspecialchars($page['slug']); ?>"
                                            <?php echo ($docpage === $page['slug']) ? 'selected' : ''; ?>>
                                            <?php echo ucfirst(htmlspecialchars($page['namepages'])); ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-6 text-center text-md-end mt-3 mt-md-0">
                                <div class="input-group w-100 w-md-75 mx-auto mx-md-0">
                                    <input type="text" id="documentSearch" class="form-control" placeholder="Cerca sezione o documento..." autocomplete="off">
                                    <div id="searchResults" class="list-group dropdown-menu show" style="position: absolute; width: 100%; max-height: 200px; overflow-y: auto; z-index: 1000; display: none;"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Contenitore per i documenti dinamici -->
                        <div id="documentSections" class="accordion"></div>
                    </div><!-- container -->
                </div><!-- Page content Wrapper -->
            </div><!-- content -->
            <?php include('include/footer.php'); ?>
        </div><!-- End Right content here -->
    </div><!-- END wrapper -->

    <!-- Librerie -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/md5-js@0.0.3/md5.min.js"></script>

    <script>
        $(document).ready(function() {
            // Inizializza Select2
            $("#pageSelectDropdown").select2({
                placeholder: "Seleziona una categoria...",
                allowClear: true,
                theme: "classic",
                width: 'resolve'
            });

            // Caricamento iniziale dei documenti per lo slug predefinito
            let idhome = <?php echo $idhome; ?>;
            loadDocuments('<?php echo $docpage; ?>');

            // Gestione del cambio del dropdown
            $("#pageSelectDropdown").on("change", function() {
                const slug = $(this).val();
                loadDocuments(slug);
            });

            // Carica tutti i documenti e le sezioni condivise per la ricerca
            let allDocuments = [];
            <?php
            $allDocumentsQuery = $conn->query("
                SELECT d.document_id, d.document_name, p.slug, s.section_name 
                FROM documents d 
                LEFT JOIN sections s ON d.idsections = s.idsections 
                LEFT JOIN pages p ON d.page_id = p.idpages 
                WHERE d.idsections IN (" . implode(',', array_map('intval', $sharedSections)) . ")
                ORDER BY s.section_name, d.document_name
            ");
            while ($doc = $allDocumentsQuery->fetch_assoc()) {
                echo "allDocuments.push({
                    id: '{$doc['document_id']}',
                    name: '" . addslashes(htmlspecialchars($doc['document_name'])) . "',
                    section: '" . addslashes(htmlspecialchars($doc['section_name'])) . "',
                    slug: '" . addslashes(htmlspecialchars($doc['slug'])) . "'
                });\n";
            }
            ?>

            // Gestione della ricerca dinamica
            $('#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)}">${result.name} (Sezione: ${result.section})</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');
                        $('#pageSelectDropdown').val(slug).trigger('change');
                        loadDocuments(slug, sectionId);
                        $('#documentSearch').val('');
                        $('#searchResults').hide();
                    });
                }
            });

            $(document).on('click', function(e) {
                if (!$(e.target).closest('.input-group, #searchResults').length) {
                    $('#searchResults').hide();
                }
            });

            function loadDocuments(slug, targetSectionId = null) {
                $.ajax({
                    url: 'get-shared-documents.php', // Assumiamo un file PHP per i documenti condivisi
                    method: 'GET',
                    data: {
                        slug: slug,
                        idhome: idhome
                    },
                    dataType: 'json',
                    success: function(response) {
                        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 Condivisi per la Casa: ${homeName}`);
                        $('p.mb-0 strong').text(`Indirizzo: ${homeAddress}`);

                        $('#documentSections').empty();
                        let html = '';
                        for (let sectionName in documents) {
                            html += `
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="heading-${md5(sectionName)}">
                                    <button class="accordion-button collapsed section-header full-width" type="button" data-toggle="collapse" data-target="#collapse-${md5(sectionName)}" aria-expanded="false" aria-controls="collapse-${md5(sectionName)}">
                                        <i class="fas fa-door-open"></i> ${sectionName}
                                    </button>
                                </h2>
                                <div id="collapse-${md5(sectionName)}" class="accordion-collapse collapse" aria-labelledby="heading-${md5(sectionName)}" data-parent="#documentSections">
                                    <div class="accordion-body">
                            `;

                            documents[sectionName].forEach(document => {
                                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>` : ''}
                                        </div>
                                        ${['add-documents', 'full-control'].includes('<?php echo $sharingType; ?>') ? `
                                            <button class="btn btn-sm btn-outline-primary toggle-dropzone" data-target="#dropzone-${document.document_id}">
                                                <i class="fas fa-plus"></i>
                                            </button>` : ''}
                                    </div>
                                    ${['add-documents', 'full-control'].includes('<?php echo $sharingType; ?>') ? `
                                    <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>` : ''}
                                    <h6 class="mt-4">Documenti già caricati:</h6>
                                    ${(loadedDocuments[document.document_id] || []).length > 0 ? `
                                        <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>${'<?php echo $sharingType; ?>' === 'full-control' ? `<button class="btn btn-danger btn-sm delete-document" data-id="${doc.id}" data-file="${doc.filename}">Elimina</button>` : ''}</td>
                                                    </tr>
                                                `).join('')}
                                            </tbody>
                                        </table>
                                    ` : '<p class="text-muted">Nessun documento caricato</p>'}
                                </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
                                    }, 500);
                                }
                            }, 1000);
                        }

                        // Inizializza Dropzone per i documenti
                        for (let sectionName in documents) {
                            documents[sectionName].forEach(document => {
                                if (['add-documents', 'full-control'].includes('<?php echo $sharingType; ?>')) {
                                    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) {
                                                    let parsedResponse = typeof response === "string" ? JSON.parse(response) : response;
                                                    if (parsedResponse.success) {
                                                        let tableId = `#table-${document.document_id} tbody`;
                                                        let row = `
                                                        <tr>
                                                            <td><a href="homedocuments/${parsedResponse.fileName}" target="_blank">${parsedResponse.fileName}</a></td>
                                                            <td>${parsedResponse.uploadDate}</td>
                                                            <td>${'<?php echo $sharingType; ?>' === 'full-control' ? `<button class="btn btn-danger btn-sm delete-document" data-id="${parsedResponse.documentId}" data-file="${parsedResponse.fileName}">Elimina</button>` : ''}</td>
                                                        </tr>`;
                                                        $(tableId).append(row);
                                                    } else {
                                                        Swal.fire({
                                                            icon: "error",
                                                            title: "Errore",
                                                            text: parsedResponse.message || "Errore nel caricamento",
                                                        });
                                                    }
                                                });
                                                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);
                                            }
                                        });
                                    }
                                }
                            });
                        }

                        // 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');
                                }
                            });
                        });

                        // Gestione eliminazione documenti
                        $(document).on("click", ".delete-document", function() {
                            const documentId = $(this).data("id");
                            const fileName = $(this).data("file");
                            const $row = $(this).closest("tr");

                            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) {
                                            const parsedResponse = typeof response === "string" ? JSON.parse(response) : response;
                                            if (parsedResponse.success) {
                                                $row.remove();
                                                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.",
                                                });
                                            }
                                        },
                                        error: function() {
                                            Swal.fire({
                                                icon: "error",
                                                title: "Errore",
                                                text: "Si è verificato un problema con la richiesta.",
                                            });
                                        },
                                    });
                                }
                            });
                        });
                    },
                    error: function(xhr, status, error) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Errore',
                            text: 'Impossibile caricare i documenti: ' + error
                        });
                    }
                });
            }
        });
    </script>
</body>

</html>