update shared homes and documents section

This commit is contained in:
Claudio 2025-03-05 11:57:26 +01:00
parent ef9afb0357
commit 9bfa037c51
6 changed files with 1970 additions and 464 deletions

View File

@ -21,51 +21,8 @@ $queryHome->execute();
$resultHome = $queryHome->get_result();
$homeData = $resultHome->fetch_assoc();
if (!isset($_GET['docpage'])) {
$docpage = "legal"; // Slug predefinito
} else {
$docpage = $_GET['docpage']; // Slug passato via GET
}
// Recupera il `page_id` corrispondente allo slug
$queryPageId = $conn->prepare("SELECT idpages FROM pages WHERE slug = ?");
$queryPageId->bind_param('s', $docpage);
$queryPageId->execute();
$resultPageId = $queryPageId->get_result();
$pageData = $resultPageId->fetch_assoc();
if ($pageData) {
$page_id = $pageData['idpages']; // Page ID trovato
} else {
die("Errore: Pagina non valida."); // Slug non trovato
}
// Recupera i documenti associati al `page_id`, con le sezioni
$queryDocuments = $conn->prepare("
SELECT d.*, s.section_name AS section_name
FROM documents d
LEFT JOIN sections s ON d.idsections = s.idsections
WHERE d.page_id = ?
ORDER BY s.section_name, d.document_name
");
$queryDocuments->bind_param('i', $page_id);
$queryDocuments->execute();
$resultDocuments = $queryDocuments->get_result();
$documents = [];
while ($row = $resultDocuments->fetch_assoc()) {
$documents[$row['section_name']][] = $row;
}
// Recupera i documenti già caricati per questa casa
$queryLoadedDocuments = $conn->prepare("SELECT * FROM doc_storage WHERE idhome = ?");
$queryLoadedDocuments->bind_param('i', $idhome);
$queryLoadedDocuments->execute();
$resultLoadedDocuments = $queryLoadedDocuments->get_result();
$loadedDocuments = [];
while ($row = $resultLoadedDocuments->fetch_assoc()) {
$loadedDocuments[$row['document_id']][] = $row;
if (!$homeData) {
die("Errore: Casa non trovata o accesso non autorizzato.");
}
// Recupera le pagine disponibili nella tabella 'documents'
@ -74,8 +31,10 @@ $pages = [];
while ($row = $queryPages->fetch_assoc()) {
$pages[] = $row;
}
?>
// Imposta lo slug predefinito o usa quello passato via GET
$docpage = isset($_GET['docpage']) ? $_GET['docpage'] : 'legal';
?>
<!DOCTYPE html>
<html lang="it">
@ -98,9 +57,6 @@ while ($row = $queryPages->fetch_assoc()) {
<!-- Dropzone CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" />
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Select2 CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet">
@ -252,6 +208,51 @@ while ($row = $queryPages->fetch_assoc()) {
display: none;
/* Nasconde inizialmente l'area */
}
/* Stile per il gruppo input su desktop */
.input-group {
max-width: 400px;
/* Limita la larghezza totale su desktop */
margin: 0 auto;
/* Centra orizzontalmente su mobile */
}
#documentSearch {
border-radius: 0.25rem 0 0 0.25rem;
/* Arrotonda solo l'angolo sinistro */
}
/* Stile per i risultati della ricerca */
#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 {
cursor: pointer;
}
#searchResults .list-group-item:hover {
background-color: #f8f9fa;
}
/* Su tablet e mobile, allinea tutto al centro e separa in due righe */
@media (max-width: 767.98px) {
.input-group {
max-width: 100%;
/* Usa tutta la larghezza su mobile */
margin-top: 10px;
/* Spazio sopra il campo di ricerca */
}
#pageSelectDropdown,
#documentSearch {
width: 100% !important;
/* Usa tutta la larghezza su mobile */
}
}
</style>
</head>
@ -278,106 +279,27 @@ while ($row = $queryPages->fetch_assoc()) {
</div>
<div class="row mb-4">
<div class="col-12 text-center">
<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-50 mx-auto">
<select id="pageSelectDropdown" class="form-control w-100 w-md-auto">
<?php foreach ($pages as $page) { ?>
<option value="?docpage=<?php echo htmlspecialchars($page['slug']); ?>&idhome=<?php echo htmlspecialchars($idhome); ?>"
<option value="<?php echo htmlspecialchars($page['slug']); ?>"
<?php echo ($docpage === $page['slug']) ? 'selected' : ''; ?>>
<?php echo ucfirst(htmlspecialchars($page['namepages'])); ?>
</option>
<?php } ?>
</select>
</div>
</div>
<!-- Sezioni per documenti -->
<div class="accordion" id="documentSections">
<?php foreach ($documents as $sectionName => $sectionDocuments) { ?>
<div class="accordion-item">
<!-- Header della sezione -->
<h2 class="accordion-header" id="heading-<?php echo md5($sectionName); ?>">
<button class="accordion-button collapsed section-header full-width" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-<?php echo md5($sectionName); ?>" aria-expanded="false" aria-controls="collapse-<?php echo md5($sectionName); ?>">
<i class="fas fa-door-open"></i> <?php echo htmlspecialchars($sectionName); ?>
</button>
</h2>
<!-- Corpo della sezione -->
<div id="collapse-<?php echo md5($sectionName); ?>" class="accordion-collapse collapse" aria-labelledby="heading-<?php echo md5($sectionName); ?>" data-bs-parent="#documentSections">
<div class="accordion-body">
<?php foreach ($sectionDocuments as $document) { ?>
<div class="card card-body mb-4">
<!-- Titolo del documento -->
<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"><?php echo htmlspecialchars($document['document_name']); ?></span>
<?php if ($document['is_required']) { ?>
<span class="badge bg-danger ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Obbligatorio</span>
<?php } ?>
<?php if ($document['max_documents'] > 0) { ?>
<span class="badge bg-info ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Max: <?php echo $document['max_documents']; ?></span>
<?php } ?>
</div>
<button class="btn btn-sm btn-outline-primary toggle-dropzone" data-target="#dropzone-<?php echo $document['document_id']; ?>">
<i class="fas fa-plus"></i> <!-- Icona per il toggle -->
</button>
</div>
<!-- Area Drag & Drop per il caricamento -->
<div class="dropzone-container collapse" id="dropzone-<?php echo $document['document_id']; ?>">
<div class="dropzone mb-3" id="dropzone-area-<?php echo $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-<?php echo $document['document_id']; ?>" class="d-none" onchange="uploadFromCamera(this, '<?php echo $document['document_id']; ?>')">
</label>
</div>
</div>
<!-- Tabella dei documenti già caricati -->
<h6 class="mt-4">Documenti già caricati:</h6>
<?php if (isset($loadedDocuments[$document['document_id']]) && count($loadedDocuments[$document['document_id']]) > 0) { ?>
<!-- Mostra la tabella se ci sono documenti caricati -->
<table class="table table-bordered document-list-table" id="table-<?php echo $document['document_id']; ?>">
<thead>
<tr>
<th>Nome Documento</th>
<th>Data Caricamento</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($loadedDocuments[$document['document_id']] as $loadedDoc) { ?>
<tr>
<td><a href="homedocuments/<?php echo $loadedDoc['filename']; ?>" target="_blank"><?php echo htmlspecialchars($loadedDoc['filename']); ?></a></td>
<td><?php echo htmlspecialchars($loadedDoc['created_at']); ?></td>
<td><button class="btn btn-danger btn-sm delete-document" data-id="<?php echo $loadedDoc['id']; ?>" data-file="<?php echo $loadedDoc['filename']; ?>">Elimina</button></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<!-- Mostra il messaggio se non ci sono documenti caricati -->
<p class="text-muted">Nessun documento caricato</p>
<?php } ?>
</div>
<?php } ?>
</div>
</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>
<?php } ?>
</div>
</div>
<!-- Contenitore per i documenti dinamici -->
<div id="documentSections" class="accordion"></div>
</div><!-- container -->
</div><!-- Page content Wrapper -->
</div><!-- content -->
@ -385,265 +307,494 @@ while ($row = $queryPages->fetch_assoc()) {
</div><!-- End Right content here -->
</div><!-- END wrapper -->
<!-- jQuery -->
<!-- Includi le librerie una sola volta -->
<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>
<!-- Plugin Dropzone -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.js"></script>
<script>
Dropzone.autoDiscover = false;
// Inizializza Dropzone per ciascun documento
<?php foreach ($documents as $section => $sectionDocuments) { ?>
<?php foreach ($sectionDocuments as $document) { ?>
let dropzone_<?php echo $document['document_id']; ?> = new Dropzone("#dropzone-area-<?php echo $document['document_id']; ?>", {
url: "upload-document.php",
paramName: "file",
maxFiles: <?php echo $document['max_documents']; ?>,
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) {
let tableId = "#table-<?php echo $document['document_id']; ?> tbody";
let 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>`;
$(tableId).append(row);
} 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.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", "<?php echo $idhome; ?>");
formData.append("document_id", "<?php echo $document['document_id']; ?>");
}
});
<?php } ?>
<?php } ?>
// Funzione per caricare un file dalla fotocamera
function uploadFromCamera(input, documentId) {
if (input.files && input.files[0]) {
let formData = new FormData();
formData.append("file", input.files[0]);
formData.append("idhome", "<?php echo $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) {
let tableId = "#table-" + documentId + " tbody";
let 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>`;
$(tableId).append(row);
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.",
});
}
});
}
}
</script>
<script>
$(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) {
try {
const parsedResponse = typeof response === "string" ? JSON.parse(response) : response;
if (parsedResponse.success) {
$row.remove(); // Rimuovi la riga dalla tabella
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.",
});
},
});
}
});
});
</script>
<script>
// Gestione del toggle dell'area 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');
}
});
});
</script>
<!-- Select2 JS -->
<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> <!-- Bootstrap 4 -->
<script src="https://cdn.jsdelivr.net/npm/md5-js@0.0.3/md5.min.js"></script>
<script>
$(document).ready(function() {
// Inizializza Select2 con uno stile migliore
// Inizializza Select2
$("#pageSelectDropdown").select2({
placeholder: "Seleziona una categoria...",
allowClear: true,
theme: "classic",
width: 'resolve' // Adatta il dropdown
width: 'resolve'
});
// Cambia pagina automaticamente al cambio di selezione
// Caricamento iniziale dei documenti per lo slug predefinito
let idhome = <?php echo $idhome; ?>;
loadDocuments('<?php echo $docpage; ?>');
// Gestione del cambio del dropdown senza ricaricare la pagina
$("#pageSelectDropdown").on("change", function() {
window.location.href = $(this).val();
const slug = $(this).val();
loadDocuments(slug);
});
// Carica tutti i documenti e le sezioni da tutte le pagine 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
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();
// Gestione del click sui risultati
$('#searchResults .list-group-item').on('click', function(e) {
e.preventDefault();
const slug = $(this).data('slug');
const sectionId = $(this).data('section');
console.log('Cliccato risultato:', {
slug,
sectionId
}); // Debug
// Aggiorna il dropdown e carica i documenti
$('#pageSelectDropdown').val(slug).trigger('change');
loadDocuments(slug, sectionId);
// Resetta il campo di ricerca e nasconde i risultati
$('#documentSearch').val('');
$('#searchResults').hide();
});
}
});
// 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) {
console.log('Caricamento documenti per slug:', slug, 'e idhome:', idhome, 'targetSectionId:', targetSectionId); // Debug
$.ajax({
url: 'get-documents.php',
method: 'GET',
data: {
slug: slug,
idhome: idhome
},
dataType: 'json', // Specifica che ci aspettiamo JSON
success: function(response) {
console.log('Risposta AJAX:', response); // Debug della risposta
if (response.error) {
Swal.fire({
icon: 'error',
title: 'Errore',
text: response.error
});
return;
}
// Verifica la struttura della risposta con valori di fallback
const homeName = response.homeName || 'Nome non disponibile';
const homeAddress = response.homeAddress || 'Indirizzo non disponibile';
const documents = response.documents || {};
const loadedDocuments = response.loadedDocuments || {};
// Aggiorna i dettagli della casa
$('.page-title').text(`Documenti per la Casa: ${homeName}`);
$('p.mb-0 strong').text(`Indirizzo: ${homeAddress}`);
// Svuota e ricrea le sezioni dei documenti
$('#documentSections').empty();
let html = '';
let sectionCount = 0; // Contatore per evitare loop infiniti
for (let sectionName in documents) {
if (sectionCount >= 100) { // Limite massimo per sicurezza
console.error('Troppi loop nelle sezioni, possibile errore nei dati');
break;
}
sectionCount++;
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">
`;
let docCount = 0; // Contatore per i documenti
(documents[sectionName] || []).forEach(document => {
if (docCount >= 100) { // Limite massimo per sicurezza
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>` : ''}
</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>
<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><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);
// Se c'è un targetSectionId, espandi solo quella sezione
if (targetSectionId) {
setTimeout(() => {
const collapseElement = $(`#collapse-${targetSectionId}`);
console.log('Tentativo di espandere sezione:', targetSectionId, 'Elemento trovato:', collapseElement.length); // Debug dettagliato
if (collapseElement.length) {
// Collassa tutte le sezioni prima di espandere quella specifica
$('.accordion-collapse.collapse').collapse('hide');
// Espandi solo la sezione corrispondente
collapseElement.collapse('show');
// Scorri alla sezione
$('html, body').animate({
scrollTop: collapseElement.offset().top - 100
}, 500);
} else {
console.error('Sezione non trovata con ID:', targetSectionId);
Swal.fire({
icon: 'warning',
title: 'Attenzione',
text: 'La sezione cercata non è stata trovata.'
});
}
}, 1000); // Aumenta il ritardo a 1000ms per garantire il rendering completo
}
// 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, // Default a 1 se non specificato
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) {
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><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",
});
}
} catch (error) {
console.error("Errore nel parsing della risposta:", error);
Swal.fire({
icon: "error",
title: "Errore",
text: "Risposta dal server non valida.",
});
}
});
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");
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();
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 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) {
let tableId = `#table-${documentId} tbody`;
let 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>`;
$(tableId).append(row);
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) {
console.error('Errore AJAX:', error, xhr.responseText); // Debug dettagliato
Swal.fire({
icon: 'error',
title: 'Errore',
text: 'Impossibile caricare i documenti: ' + error
});
}
});
}
});
</script>
</body>
</html>

View File

@ -0,0 +1,649 @@
<?php include('include/headscript.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>
<?php
// 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 i dettagli della casa
$queryHome = $conn->prepare("SELECT * FROM home WHERE idhome = ? AND iduser = ?");
$queryHome->bind_param('ii', $idhome, $iduserlogin);
$queryHome->execute();
$resultHome = $queryHome->get_result();
$homeData = $resultHome->fetch_assoc();
if (!isset($_GET['docpage'])) {
$docpage = "legal"; // Slug predefinito
} else {
$docpage = $_GET['docpage']; // Slug passato via GET
}
// Recupera il `page_id` corrispondente allo slug
$queryPageId = $conn->prepare("SELECT idpages FROM pages WHERE slug = ?");
$queryPageId->bind_param('s', $docpage);
$queryPageId->execute();
$resultPageId = $queryPageId->get_result();
$pageData = $resultPageId->fetch_assoc();
if ($pageData) {
$page_id = $pageData['idpages']; // Page ID trovato
} else {
die("Errore: Pagina non valida."); // Slug non trovato
}
// Recupera i documenti associati al `page_id`, con le sezioni
$queryDocuments = $conn->prepare("
SELECT d.*, s.section_name AS section_name
FROM documents d
LEFT JOIN sections s ON d.idsections = s.idsections
WHERE d.page_id = ?
ORDER BY s.section_name, d.document_name
");
$queryDocuments->bind_param('i', $page_id);
$queryDocuments->execute();
$resultDocuments = $queryDocuments->get_result();
$documents = [];
while ($row = $resultDocuments->fetch_assoc()) {
$documents[$row['section_name']][] = $row;
}
// Recupera i documenti già caricati per questa casa
$queryLoadedDocuments = $conn->prepare("SELECT * FROM doc_storage WHERE idhome = ?");
$queryLoadedDocuments->bind_param('i', $idhome);
$queryLoadedDocuments->execute();
$resultLoadedDocuments = $queryLoadedDocuments->get_result();
$loadedDocuments = [];
while ($row = $resultLoadedDocuments->fetch_assoc()) {
$loadedDocuments[$row['document_id']][] = $row;
}
// Recupera le pagine disponibili nella tabella 'documents'
$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 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" />
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Select2 CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet">
<style>
/* Personalizza la riga della sezione */
.section-header {
background-color: #f8f9fa;
/* Sfondo chiaro */
border: 1px solid #007bff;
/* Bordo blu */
color: #007bff;
/* Testo blu */
font-size: 1.2rem;
/* Dimensione del font */
font-weight: bold;
/* Grassetto */
padding: 15px 20px;
/* Padding */
text-align: left;
/* Allinea il testo a sinistra */
width: 100%;
/* A tutta larghezza */
}
.section-header:hover {
background-color: #007bff;
/* Sfondo blu al passaggio del mouse */
color: #fff;
/* Testo bianco al passaggio del mouse */
}
.accordion-button {
border-radius: 0 !important;
/* Rimuove gli angoli arrotondati */
box-shadow: none !important;
/* Rimuove l'ombra */
}
/* Icona accanto al titolo */
.section-header i {
font-size: 1.5rem;
/* Dimensione dell'icona */
margin-right: 10px;
/* Spaziatura a destra dell'icona */
}
.section-title {
font-size: 1.25rem;
font-weight: bold;
color: #333;
margin-bottom: 20px;
}
.document-title {
font-size: 1.1rem;
font-weight: 500;
margin-bottom: 10px;
}
.dropzone {
background-color: #f0f8ff;
border: 2px dashed #007bff;
padding: 20px;
border-radius: 10px;
text-align: center;
transition: background-color 0.3s ease;
}
.dropzone:hover {
background-color: #e6f5ff;
}
.dropzone .dz-message {
font-size: 1.1rem;
font-weight: 500;
color: #007bff;
}
.dropzone .dz-message i {
font-size: 3rem;
margin-bottom: 10px;
color: #007bff;
}
.document-list-table th,
.document-list-table td {
text-align: center;
vertical-align: middle;
}
.section-separator {
border-top: 2px solid #ddd;
margin: 40px 0;
}
.btn {
margin-right: 5px;
}
.btn.active {
background-color: #007bff;
color: #fff;
}
/* Stile per l'intestazione della sezione */
.accordion-button {
background-color: #322999;
color: white;
font-size: 1.2rem;
font-weight: bold;
text-align: left;
border: 1px solid #007bff;
}
.accordion-button:hover {
background-color: #007bff;
color: white;
}
.accordion-button i {
font-size: 1.5rem;
color: #fff562;
}
.accordion-body {
padding: 20px;
background-color: #f9f9f9;
border: 1px solid #ddd;
}
.card-body {
margin-bottom: 20px;
padding: 15px;
background-color: #ffffff;
border: 1px solid #ddd;
border-radius: 5px;
}
.toggle-dropzone {
transition: all 0.3s ease;
font-size: 0.9rem;
}
.dropzone-container {
padding: 10px;
background-color: #f9f9f9;
border: 1px dashed #007bff;
border-radius: 8px;
display: none;
/* Nasconde inizialmente l'area */
}
</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 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>
</div>
</div>
<div class="row mb-4">
<div class="col-12 text-center">
<label for="pageSelectDropdown" class="fw-bold d-block mb-2">Seleziona Categoria:</label>
<select id="pageSelectDropdown" class="form-control w-50 mx-auto">
<?php foreach ($pages as $page) { ?>
<option value="?docpage=<?php echo htmlspecialchars($page['slug']); ?>&idhome=<?php echo htmlspecialchars($idhome); ?>"
<?php echo ($docpage === $page['slug']) ? 'selected' : ''; ?>>
<?php echo ucfirst(htmlspecialchars($page['namepages'])); ?>
</option>
<?php } ?>
</select>
</div>
</div>
<!-- Sezioni per documenti -->
<div class="accordion" id="documentSections">
<?php foreach ($documents as $sectionName => $sectionDocuments) { ?>
<div class="accordion-item">
<!-- Header della sezione -->
<h2 class="accordion-header" id="heading-<?php echo md5($sectionName); ?>">
<button class="accordion-button collapsed section-header full-width" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-<?php echo md5($sectionName); ?>" aria-expanded="false" aria-controls="collapse-<?php echo md5($sectionName); ?>">
<i class="fas fa-door-open"></i> <?php echo htmlspecialchars($sectionName); ?>
</button>
</h2>
<!-- Corpo della sezione -->
<div id="collapse-<?php echo md5($sectionName); ?>" class="accordion-collapse collapse" aria-labelledby="heading-<?php echo md5($sectionName); ?>" data-bs-parent="#documentSections">
<div class="accordion-body">
<?php foreach ($sectionDocuments as $document) { ?>
<div class="card card-body mb-4">
<!-- Titolo del documento -->
<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"><?php echo htmlspecialchars($document['document_name']); ?></span>
<?php if ($document['is_required']) { ?>
<span class="badge bg-danger ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Obbligatorio</span>
<?php } ?>
<?php if ($document['max_documents'] > 0) { ?>
<span class="badge bg-info ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Max: <?php echo $document['max_documents']; ?></span>
<?php } ?>
</div>
<button class="btn btn-sm btn-outline-primary toggle-dropzone" data-target="#dropzone-<?php echo $document['document_id']; ?>">
<i class="fas fa-plus"></i> <!-- Icona per il toggle -->
</button>
</div>
<!-- Area Drag & Drop per il caricamento -->
<div class="dropzone-container collapse" id="dropzone-<?php echo $document['document_id']; ?>">
<div class="dropzone mb-3" id="dropzone-area-<?php echo $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-<?php echo $document['document_id']; ?>" class="d-none" onchange="uploadFromCamera(this, '<?php echo $document['document_id']; ?>')">
</label>
</div>
</div>
<!-- Tabella dei documenti già caricati -->
<h6 class="mt-4">Documenti già caricati:</h6>
<?php if (isset($loadedDocuments[$document['document_id']]) && count($loadedDocuments[$document['document_id']]) > 0) { ?>
<!-- Mostra la tabella se ci sono documenti caricati -->
<table class="table table-bordered document-list-table" id="table-<?php echo $document['document_id']; ?>">
<thead>
<tr>
<th>Nome Documento</th>
<th>Data Caricamento</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($loadedDocuments[$document['document_id']] as $loadedDoc) { ?>
<tr>
<td><a href="homedocuments/<?php echo $loadedDoc['filename']; ?>" target="_blank"><?php echo htmlspecialchars($loadedDoc['filename']); ?></a></td>
<td><?php echo htmlspecialchars($loadedDoc['created_at']); ?></td>
<td><button class="btn btn-danger btn-sm delete-document" data-id="<?php echo $loadedDoc['id']; ?>" data-file="<?php echo $loadedDoc['filename']; ?>">Elimina</button></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<!-- Mostra il messaggio se non ci sono documenti caricati -->
<p class="text-muted">Nessun documento caricato</p>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
</div>
<?php } ?>
</div>
</div><!-- container -->
</div><!-- Page content Wrapper -->
</div><!-- content -->
<?php include('include/footer.php'); ?>
</div><!-- End Right content here -->
</div><!-- END wrapper -->
<!-- jQuery -->
<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>
<!-- Plugin Dropzone -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.js"></script>
<script>
Dropzone.autoDiscover = false;
// Inizializza Dropzone per ciascun documento
<?php foreach ($documents as $section => $sectionDocuments) { ?>
<?php foreach ($sectionDocuments as $document) { ?>
let dropzone_<?php echo $document['document_id']; ?> = new Dropzone("#dropzone-area-<?php echo $document['document_id']; ?>", {
url: "upload-document.php",
paramName: "file",
maxFiles: <?php echo $document['max_documents']; ?>,
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) {
let tableId = "#table-<?php echo $document['document_id']; ?> tbody";
let 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>`;
$(tableId).append(row);
} 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.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", "<?php echo $idhome; ?>");
formData.append("document_id", "<?php echo $document['document_id']; ?>");
}
});
<?php } ?>
<?php } ?>
// Funzione per caricare un file dalla fotocamera
function uploadFromCamera(input, documentId) {
if (input.files && input.files[0]) {
let formData = new FormData();
formData.append("file", input.files[0]);
formData.append("idhome", "<?php echo $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) {
let tableId = "#table-" + documentId + " tbody";
let 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>`;
$(tableId).append(row);
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.",
});
}
});
}
}
</script>
<script>
$(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) {
try {
const parsedResponse = typeof response === "string" ? JSON.parse(response) : response;
if (parsedResponse.success) {
$row.remove(); // Rimuovi la riga dalla tabella
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.",
});
},
});
}
});
});
</script>
<script>
// Gestione del toggle dell'area 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');
}
});
});
</script>
<!-- Select2 JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
$(document).ready(function() {
// Inizializza Select2 con uno stile migliore
$("#pageSelectDropdown").select2({
placeholder: "Seleziona una categoria...",
allowClear: true,
theme: "classic",
width: 'resolve' // Adatta il dropdown
});
// Cambia pagina automaticamente al cambio di selezione
$("#pageSelectDropdown").on("change", function() {
window.location.href = $(this).val();
});
});
</script>
</body>
</html>

View File

@ -0,0 +1,83 @@
<?php
include('include/headscript.php');
// 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 slug dalla richiesta
$docpage = isset($_GET['slug']) ? $_GET['slug'] : 'legal';
// Recupera i dettagli della casa (per verifica accesso)
$queryHome = $conn->prepare("SELECT * FROM home WHERE idhome = ? AND iduser = ?");
$queryHome->bind_param('ii', $idhome, $iduserlogin);
$queryHome->execute();
$resultHome = $queryHome->get_result();
$homeData = $resultHome->fetch_assoc();
if (!$homeData) {
header('HTTP/1.1 400 Bad Request');
die(json_encode(['error' => 'Casa non trovata o accesso non autorizzato']));
}
// Recupera il `page_id` corrispondente allo slug
$queryPageId = $conn->prepare("SELECT idpages FROM pages WHERE slug = ?");
$queryPageId->bind_param('s', $docpage);
$queryPageId->execute();
$resultPageId = $queryPageId->get_result();
$pageData = $resultPageId->fetch_assoc();
if (!$pageData) {
header('HTTP/1.1 400 Bad Request');
die(json_encode(['error' => 'Pagina non valida']));
}
$page_id = $pageData['idpages'];
// Recupera i documenti associati al `page_id`, con le sezioni
$queryDocuments = $conn->prepare("
SELECT d.*, s.section_name AS section_name
FROM documents d
LEFT JOIN sections s ON d.idsections = s.idsections
WHERE d.page_id = ?
ORDER BY s.section_name, d.document_name
");
$queryDocuments->bind_param('i', $page_id);
$queryDocuments->execute();
$resultDocuments = $queryDocuments->get_result();
$documents = [];
while ($row = $resultDocuments->fetch_assoc()) {
$documents[$row['section_name']][] = $row;
}
// Recupera i documenti già caricati per questa casa
$queryLoadedDocuments = $conn->prepare("SELECT * FROM doc_storage WHERE idhome = ?");
$queryLoadedDocuments->bind_param('i', $idhome);
$queryLoadedDocuments->execute();
$resultLoadedDocuments = $queryLoadedDocuments->get_result();
$loadedDocuments = [];
while ($row = $resultLoadedDocuments->fetch_assoc()) {
$loadedDocuments[$row['document_id']][] = $row;
}
// Prepara la risposta JSON
$response = [
'homeName' => $homeData['name'] ?? '',
'homeAddress' => ($homeData['address'] ?? '') . ', ' . ($homeData['city'] ?? '') . ' ' . ($homeData['zip'] ?? ''),
'documents' => $documents,
'loadedDocuments' => $loadedDocuments
];
// Imposta l'header per indicare JSON
header('Content-Type: application/json');
// Evita output extra
echo json_encode($response, JSON_PRETTY_PRINT);
exit;

View File

@ -4,6 +4,10 @@
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);
// Recupera l'id utente loggato e la sua email
$iduserlogin = $_SESSION['iduserlogin'];
$emailuser = $_SESSION['emailuser'];
// Verifica se si sta aggiungendo una nuova casa o aggiornando una esistente
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;
$isNew = ($idhome == 0);
@ -20,9 +24,44 @@ if ($isNew) {
exit(); // Assicurati di uscire per evitare che il codice continui
}
// Se esiste già l'idhome, carica i dati della casa
$query = $conn->prepare("SELECT * FROM home WHERE idhome = ? AND iduser = ?");
$query->bind_param("ii", $idhome, $iduserlogin);
// Determina l'iduser corretto per l'immobile, controllando sia il proprietario che le condivisioni
$ownerId = null;
$queryOwner = $conn->prepare("SELECT iduser FROM home WHERE idhome = ?");
$queryOwner->bind_param("i", $idhome);
$queryOwner->execute();
$resultOwner = $queryOwner->get_result();
if ($resultOwner->num_rows > 0) {
$ownerData = $resultOwner->fetch_assoc();
$ownerId = $ownerData['iduser'];
}
// Verifica se l'utente ha accesso diretto (è il proprietario) o tramite condivisione
$hasAccess = false;
if ($ownerId == $iduserlogin) {
$hasAccess = true; // Utente è il proprietario
} else {
// Controlla se l'utente ha accesso tramite home_sharing
$querySharing = $conn->prepare("
SELECT * FROM home_sharing
WHERE idhome = ?
AND (idshareduser = ? OR shared_email = ?)
AND status = 'accepted'
");
$querySharing->bind_param("iis", $idhome, $iduserlogin, $emailuser);
$querySharing->execute();
$resultSharing = $querySharing->get_result();
$hasAccess = ($resultSharing->num_rows > 0);
}
// Se l'utente non ha accesso, reindirizza o mostra un errore
if (!$hasAccess) {
header("Location: access-denied.php"); // O una pagina di errore personalizzata
exit();
}
// Carica i dati della casa per l'utente con accesso
$query = $conn->prepare("SELECT * FROM home WHERE idhome = ?");
$query->bind_param("i", $idhome);
$query->execute();
$result = $query->get_result();
$homeData = $result->fetch_assoc();

View File

@ -15,20 +15,31 @@ SELECT
h.address,
h.zip,
h.city,
h.country,
h.country,
h.mainphoto,
hs.sharing_type,
hs.expiration_date,
au.first_name,
au.last_name,
COUNT(ho.owner_id) AS owner_count
COUNT(ho.owner_id) AS owner_count,
SUM(ho.ownership_percentage) AS total_ownership,
GROUP_CONCAT(
CASE
WHEN po.owner_type = 'individual'
THEN CONCAT(po.first_name, ' ', po.last_name, ' (', ho.ownership_percentage, '%)')
ELSE CONCAT(po.company_name, ' (', ho.ownership_percentage, '%)')
END
SEPARATOR '\n'
) AS owner_names
FROM home_sharing hs
LEFT JOIN home h ON hs.idhome = h.idhome
LEFT JOIN auth_users au ON hs.iduser = au.id
LEFT JOIN home_owners ho ON hs.idhome = ho.home_id
LEFT JOIN property_owners po ON ho.owner_id = po.owner_id
WHERE
(hs.idshareduser = ? OR hs.shared_email = ?)
AND hs.status = 'accepted'
GROUP BY
GROUP BY
hs.idhome,
h.name,
h.address,
@ -65,6 +76,199 @@ $result = $stmt->get_result();
<!-- Custom CSS -->
<link href="assets/css/style.css" rel="stylesheet" type="text/css">
<link href="assets/css/icons.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdn.materialdesignicons.com/5.4.55/css/materialdesignicons.min.css">
<style>
/* Stili copiati dalla prima pagina */
.button-menu-mobile {
display: inline-block !important;
}
@media (min-width: 992px) {
.button-menu-mobile {
background-color: transparent;
border: none;
padding: 0;
width: auto;
height: auto;
}
.button-menu-mobile i.ion-close {
display: none;
}
.button-menu-mobile i.mdi-menu {
display: inline-block;
}
}
@media (max-width: 991.98px) {
.button-menu-mobile {
background-color: #ff5e5e;
border-radius: 50%;
width: 50px;
height: 50px;
}
.button-menu-mobile i.ion-close {
display: inline-block;
}
.button-menu-mobile i.mdi-menu {
display: none;
}
}
.btn-main {
background-color: rgb(96, 93, 175);
color: #fff;
border: none;
}
.btn-main:hover {
background-color: #364fc7;
}
.btn-secondary {
background-color: rgb(21, 190, 86);
color: #212529;
border: none;
}
.btn-secondary:hover {
background-color: #868e96;
}
.btn-info-light {
background-color: #ffd43b;
color: #212529;
border: none;
}
.btn-info-light:hover {
background-color: #fcc419;
}
.equal-height {
display: flex;
flex-direction: column;
height: 100%;
}
.equal-height .flex-fill {
flex: 1;
}
#gridView .card {
border-radius: 10px;
overflow: hidden;
transition: transform 0.2s ease-in-out;
}
#gridView .card:hover {
transform: scale(1.03);
}
.card-img-top {
height: 180px;
object-fit: cover;
}
.action-menu {
position: absolute;
top: 10px;
right: 10px;
display: none;
}
.box-home:hover .action-menu {
display: block;
}
.action-toggle {
border: none;
background: rgba(255, 255, 255, 0.9);
padding: 6px 10px;
width: 32px;
height: 32px;
border-radius: 5px;
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.action-toggle:hover {
background: rgba(230, 230, 230, 1);
}
.dropdown-menu {
font-size: 14px;
min-width: 180px;
}
.dropdown-item i {
margin-right: 8px;
}
.img-thumbnail {
border-radius: 5px;
}
td i.fas {
margin-right: 5px;
}
.action-container {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
.owner-btn {
font-size: 14px;
padding: 4px 10px;
}
.box-home .action-menu {
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.box-home:hover .action-menu {
opacity: 1;
}
/* Posiziona il dropdown fuori dalla tabella se necessario */
.table-responsive .dropdown-menu {
position: absolute;
z-index: 1000;
/* Assicurati che sia sopra altri elementi */
}
/* Evita che il dropdown venga tagliato dal table-responsive */
.table-responsive {
overflow: visible;
/* Disattiva l'overflow visibile */
}
/* Classe personalizzata per il dropdown delle azioni */
.dropdown-actions .dropdown-menu {
min-width: 180px;
font-size: 14px;
}
/* Assicurati che il dropdown non sia nascosto dal contenitore della tabella */
.dropdown-menu-right {
right: 0;
left: auto;
}
</style>
</head>
<body class="fixed-left">
@ -90,85 +294,171 @@ $result = $stmt->get_result();
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table id="sharedHomesTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Nome</th>
<th>Indirizzo</th>
<th>CAP</th>
<th>Città</th>
<th>Nazione</th>
<th>Condiviso da</th>
<th>Proprietari</th>
<th>Data Scadenza</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php while ($row = $result->fetch_assoc()) { ?>
<div class="row mb-3">
<div class="col-12 d-flex justify-content-start align-items-center gap-3">
<button id="toggleViewBtn" class="btn btn-info ms-2">
<i class="fas fa-th-large"></i> Vista Griglia
</button>
</div>
</div>
<!-- Table View -->
<div id="tableView" style="display: none;">
<div class="row">
<div class="col-xl-12">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table id="sharedHomesTable" class="table table-bordered table-striped">
<thead>
<tr>
<td><?php echo htmlspecialchars($row['name']); ?></td>
<td><?php echo htmlspecialchars($row['address']); ?></td>
<td><?php echo htmlspecialchars($row['zip']); ?></td>
<td><?php echo htmlspecialchars($row['city']); ?></td>
<td><?php echo htmlspecialchars($row['country']); ?></td>
<td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></td>
<td>
<?php if ($row['owner_count'] == 0) { ?>
<!-- Pulsante rosso per nessun proprietario -->
<a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn btn-danger btn-sm" title="Nessun Proprietario">
<i class="fas fa-user-times"></i> <!-- Icona per nessun proprietario -->
</a>
<?php } else { ?>
<!-- Pulsante verde con il numero dei proprietari -->
<a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn btn-success btn-sm" title="<?php echo $row['owner_count']; ?> Proprietari">
<i class="fas fa-user-check"></i> <!-- Icona per proprietari presenti -->
</a>
<?php } ?>
</td>
<td>
<?php echo $row['expiration_date'] ? htmlspecialchars($row['expiration_date']) : 'Nessuna'; ?>
</td>
<td>
<!-- Pulsante per modificare i dettagli della casa -->
<a href="manage-home.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-info btn-sm" title="Dettagli">
<i class="fas fa-info-circle"></i>
</a>
<!-- Pulsante per visualizzare i dettagli -->
<a href="documents-home-shared.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-primary btn-sm" title="Documenti">
<i class="fas fa-folder-open"></i>
</a>
<!-- Pulsante per scaricare zip -->
<a href="download-zip.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-warning btn-sm" title="Scarica ZIP">
<i class="fas fa-file-archive"></i>
</a>
<!-- Pulsante per scaricare report -->
<a href="download-report.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-danger btn-sm" title="Scarica Report">
<i class="fas fa-file-alt"></i>
</a>
</td>
<th>Foto</th>
<th>Nome</th>
<th>Città / Nazione</th>
<th>Indirizzo</th>
<th>Proprietari</th>
<th>Condiviso da</th>
<th>Data Scadenza</th>
<th>Azioni</th>
</tr>
<?php } ?>
</tbody>
</table>
</div><!-- end table-responsive -->
<tr>
<th></th>
<th><input type="text" placeholder="Cerca Nome" class="form-control form-control-sm"></th>
<th><input type="text" placeholder="Cerca Città" class="form-control form-control-sm"></th>
<th><input type="text" placeholder="Cerca Indirizzo" class="form-control form-control-sm"></th>
<th><input type="text" placeholder="Cerca Proprietari" class="form-control form-control-sm"></th>
<th><input type="text" placeholder="Cerca Condiviso da" class="form-control form-control-sm"></th>
<th><input type="text" placeholder="Cerca Scadenza" class="form-control form-control-sm"></th>
<th></th>
</tr>
</thead>
<tbody>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td>
<img src="mainphoto/<?php echo htmlspecialchars($row['mainphoto'] ?? 'default.jpg'); ?>"
class="img-thumbnail open-photo"
style="width: 80px; height: 80px; object-fit: cover; cursor: pointer;"
alt="<?php echo htmlspecialchars($row['name']); ?>"
data-toggle="modal" data-target="#photoModal"
data-src="mainphoto/<?php echo htmlspecialchars($row['mainphoto'] ?? 'default.jpg'); ?>">
</td>
<td><?php echo htmlspecialchars($row['name']); ?></td>
<td><?php echo htmlspecialchars($row['city']); ?>, <?php echo htmlspecialchars($row['country']); ?></td>
<td><?php echo htmlspecialchars($row['address']); ?></td>
<td>
<?php echo nl2br(htmlspecialchars($row['owner_names'])); ?>
<br>
<?php
if ($row['owner_count'] == 0) {
$btn_class = "btn-danger";
$btn_text = '<i class="fas fa-user-times"></i> Assegna Proprietario';
} elseif ($row['total_ownership'] < 100) {
$btn_class = "btn-warning";
$btn_text = '<i class="fas fa-user-edit"></i> ' . $row['owner_count'] . ' (' . htmlspecialchars($row['total_ownership']) . '%)';
} else {
$btn_class = "btn-success";
$btn_text = '<i class="fas fa-user-check"></i> ' . $row['owner_count'];
}
?>
<a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn <?php echo $btn_class; ?> btn-sm mt-1">
<?php echo $btn_text; ?>
</a>
</td>
<td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></td>
<td><?php echo $row['expiration_date'] ? htmlspecialchars($row['expiration_date']) : 'Nessuna'; ?></td>
<td class="text-nowrap">
<div class="dropdown dropdown-actions">
<!-- Aggiungiamo la classe dropdown-actions per il posizionamento -->
<button class="btn btn-light btn-sm dropdown-toggle action-toggle" type="button" data-toggle="dropdown" aria-expanded="false">
<i class="fas fa-ellipsis-v"></i>
</button>
<ul class="dropdown-menu dropdown-menu-right">
<li><a class="dropdown-item" href="manage-home.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-info-circle"></i> Dettagli
</a></li>
<li><a class="dropdown-item" href="documents-home-shared.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-folder-open"></i> Documenti
</a></li>
<li><a class="dropdown-item" href="download-zip.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-file-archive"></i> Scarica ZIP
</a></li>
<li><a class="dropdown-item" href="download-report.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-file-alt"></i> Scarica Report
</a></li>
</ul>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="mb-3">
<button onclick="history.back()" class="btn btn-dark">
<i class="fas fa-arrow-left"></i> Torna indietro
</button>
</div>
</div>
</div>
<!-- Grid View -->
<div id="gridView" style="display: block;">
<div class="row">
<?php
$result->data_seek(0); // Ripristina i dati per la griglia
while ($row = $result->fetch_assoc()) { ?>
<div class="col-md-3 col-sm-6 mb-4">
<div class="card shadow-sm border-0 position-relative box-home">
<img src="mainphoto/<?php echo htmlspecialchars($row['mainphoto'] ?? 'default.jpg'); ?>"
class="card-img-top"
alt="<?php echo htmlspecialchars($row['name']); ?>">
<div class="action-container">
<?php
if ($row['owner_count'] == 0) {
$btn_class = "btn-danger";
} elseif ($row['total_ownership'] < 100) {
$btn_class = "btn-warning";
} else {
$btn_class = "btn-success";
}
?>
<a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn <?php echo $btn_class; ?> btn-sm owner-btn">
<i class="fas fa-user"></i> <?php echo htmlspecialchars($row['owner_count']); ?>
</a>
<div class="dropdown action-menu">
<button class="btn btn-light btn-sm action-toggle" data-toggle="dropdown">
<i class="fas fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="manage-home.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-info-circle"></i> Dettagli
</a>
<a class="dropdown-item" href="documents-home-shared.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-folder-open"></i> Documenti
</a>
<a class="dropdown-item" href="download-zip.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-file-archive"></i> Scarica ZIP
</a>
<a class="dropdown-item" href="download-report.php?idhome=<?php echo $row['idhome']; ?>">
<i class="fas fa-file-alt"></i> Scarica Report
</a>
</div>
</div>
</div>
<div class="card-body text-center">
<h5 class="card-title"><?php echo htmlspecialchars($row['name']); ?></h5>
<p class="card-text"><?php echo htmlspecialchars($row['address']); ?> - <?php echo htmlspecialchars($row['city']); ?></p>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<div class="mb-3">
<button onclick="history.back()" class="btn btn-dark">
<i class="fas fa-arrow-left"></i> Torna indietro
</button>
</div>
</div><!-- container -->
</div><!-- Page content Wrapper -->
</div><!-- content -->
@ -180,14 +470,111 @@ $result = $stmt->get_result();
<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="assets/js/popper.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/modernizr.min.js"></script>
<script src="assets/js/detect.js"></script>
<script src="assets/js/fastclick.js"></script>
<script src="assets/js/jquery.slimscroll.js"></script>
<script src="assets/js/jquery.blockUI.js"></script>
<script src="assets/js/waves.js"></script>
<script src="assets/js/jquery.nicescroll.js"></script>
<script src="assets/js/jquery.scrollTo.min.js"></script>
<script src="assets/js/app.js"></script>
<script>
$(document).ready(function() {
// Inizializza DataTables
$('#sharedHomesTable').DataTable({
order: [
[0, 'asc']
] // Ordina per nome
var table = $('#sharedHomesTable').DataTable({
responsive: true,
autoWidth: false,
initComplete: function() {
// Aggiusta il posizionamento dei dropdown dopo l'inizializzazione
this.api().columns().every(function() {
var column = this;
$('input', column.header()).on('keyup change', function() {
if (column.search() !== this.value) {
column.search(this.value).draw();
}
});
});
}
});
$("#tableView").hide();
$("#gridView").show();
$("#toggleViewBtn").html('<i class="fas fa-list"></i> Vista Elenco');
$("#toggleViewBtn").click(function() {
if ($("#tableView").is(":visible")) {
$("#tableView").hide();
$("#gridView").show();
$("#toggleViewBtn").html('<i class="fas fa-list"></i> Vista Elenco');
} else {
$("#gridView").hide();
$("#tableView").show();
setTimeout(function() {
table.columns.adjust().draw();
$('#sharedHomesTable').css('width', '100%');
}, 200);
$("#toggleViewBtn").html('<i class="fas fa-th-large"></i> Vista Griglia');
}
});
// Gestione manuale dei dropdown per evitare conflitti e posizionamento corretto
$('.action-toggle').on('click', function(e) {
e.preventDefault();
var $dropdown = $(this).siblings('.dropdown-menu');
$('.dropdown-menu').not($dropdown).removeClass('show'); // Chiude gli altri dropdown aperti
$dropdown.toggleClass('show');
// Posiziona il dropdown fuori dalla tabella se necessario
if ($dropdown.hasClass('show')) {
var dropdownTop = $(this).offset().top + $(this).outerHeight();
var dropdownLeft = $(this).offset().left;
$dropdown.css({
'position': 'absolute',
'top': dropdownTop + 'px',
'left': dropdownLeft + 'px',
'z-index': 1000
});
}
});
// Chiude il dropdown se si clicca fuori
$(document).on('click', function(e) {
if (!$(e.target).closest('.dropdown').length) {
$('.dropdown-menu').removeClass('show');
}
});
// Chiude il dropdown quando si seleziona un'opzione
$('.dropdown-menu a').on('click', function() {
$(this).closest('.dropdown-menu').removeClass('show');
});
});
</script>
<!-- Modal per visualizzazione dell'immagine -->
<div class="modal fade" id="photoModal" tabindex="-1" role="dialog" aria-labelledby="photoModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="photoModalLabel">Foto Immobile</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-center">
<img id="modalPhoto" src="" class="img-fluid rounded" alt="Immagine immobile">
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$(".open-photo").on("click", function() {
let imgSrc = $(this).attr("data-src");
$("#modalPhoto").attr("src", imgSrc);
});
});
</script>

View File

@ -0,0 +1,197 @@
<?php include('include/headscript.php'); ?>
<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);
// Recupera l'id utente loggato e la sua email
$iduserlogin = $_SESSION['iduserlogin'];
$emailuser = $_SESSION['emailuser'];
// Query per ottenere gli immobili condivisi con l'utente loggato
$sql = "
SELECT
hs.idhome,
h.name,
h.address,
h.zip,
h.city,
h.country,
hs.sharing_type,
hs.expiration_date,
au.first_name,
au.last_name,
COUNT(ho.owner_id) AS owner_count
FROM home_sharing hs
LEFT JOIN home h ON hs.idhome = h.idhome
LEFT JOIN auth_users au ON hs.iduser = au.id
LEFT JOIN home_owners ho ON hs.idhome = ho.home_id
WHERE
(hs.idshareduser = ? OR hs.shared_email = ?)
AND hs.status = 'accepted'
GROUP BY
hs.idhome,
h.name,
h.address,
h.zip,
h.city,
h.country,
hs.sharing_type,
hs.expiration_date,
au.first_name,
au.last_name;
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('is', $iduserlogin, $emailuser);
$stmt->execute();
$result = $stmt->get_result();
?>
<!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>Immobili Condivisi</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" />
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Custom CSS -->
<link href="assets/css/style.css" rel="stylesheet" type="text/css">
</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'); ?>
<div class="page-content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="page-title-box">
<div class="btn-group float-right">
<ol class="breadcrumb hide-phone p-0 m-0">
<li class="breadcrumb-item"><a href="#">CasaDoc</a></li>
<li class="breadcrumb-item active">Immobili Condivisi</li>
</ol>
</div>
<h4 class="page-title">Immobili Condivisi</h4>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table id="sharedHomesTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Nome</th>
<th>Indirizzo</th>
<th>CAP</th>
<th>Città</th>
<th>Nazione</th>
<th>Condiviso da</th>
<th>Proprietari</th>
<th>Data Scadenza</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo htmlspecialchars($row['name']); ?></td>
<td><?php echo htmlspecialchars($row['address']); ?></td>
<td><?php echo htmlspecialchars($row['zip']); ?></td>
<td><?php echo htmlspecialchars($row['city']); ?></td>
<td><?php echo htmlspecialchars($row['country']); ?></td>
<td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></td>
<td>
<?php if ($row['owner_count'] == 0) { ?>
<!-- Pulsante rosso per nessun proprietario -->
<a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn btn-danger btn-sm" title="Nessun Proprietario">
<i class="fas fa-user-times"></i> <!-- Icona per nessun proprietario -->
</a>
<?php } else { ?>
<!-- Pulsante verde con il numero dei proprietari -->
<a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn btn-success btn-sm" title="<?php echo $row['owner_count']; ?> Proprietari">
<i class="fas fa-user-check"></i> <!-- Icona per proprietari presenti -->
</a>
<?php } ?>
</td>
<td>
<?php echo $row['expiration_date'] ? htmlspecialchars($row['expiration_date']) : 'Nessuna'; ?>
</td>
<td>
<!-- Pulsante per modificare i dettagli della casa -->
<a href="manage-home.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-info btn-sm" title="Dettagli">
<i class="fas fa-info-circle"></i>
</a>
<!-- Pulsante per visualizzare i dettagli -->
<a href="documents-home-shared.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-primary btn-sm" title="Documenti">
<i class="fas fa-folder-open"></i>
</a>
<!-- Pulsante per scaricare zip -->
<a href="download-zip.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-warning btn-sm" title="Scarica ZIP">
<i class="fas fa-file-archive"></i>
</a>
<!-- Pulsante per scaricare report -->
<a href="download-report.php?idhome=<?php echo $row['idhome']; ?>" class="btn btn-danger btn-sm" title="Scarica Report">
<i class="fas fa-file-alt"></i>
</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div><!-- end table-responsive -->
</div>
</div>
<div class="mb-3">
<button onclick="history.back()" class="btn btn-dark">
<i class="fas fa-arrow-left"></i> Torna indietro
</button>
</div>
</div>
</div>
</div><!-- container -->
</div><!-- Page content Wrapper -->
</div><!-- content -->
<?php include('include/footer.php'); ?>
</div><!-- End Right content here -->
</div><!-- END wrapper -->
<!-- jQuery -->
<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>
$(document).ready(function() {
// Inizializza DataTables
$('#sharedHomesTable').DataTable({
order: [
[0, 'asc']
] // Ordina per nome
});
});
</script>
</body>
</html>