update document page

This commit is contained in:
2025-04-22 08:05:22 +02:00
parent b63606a48c
commit 1da7ee5208
21 changed files with 6480 additions and 2970 deletions
+375
View File
@@ -0,0 +1,375 @@
<?php
global $idhome, $isNew, $homeData, $namedb, $addressdb, $countrydb, $citydb, $zipdb, $commentdb, $latitudedb, $longitudedb, $fulladdressdb,
$cadastral_municipalitydb, $cadastral_sectiondb, $cadastral_sheetdb, $cadastral_particledb, $cadastral_subdb, $cadastral_categorydb,
$cadastral_classdb, $cadastral_surfacedb, $cadastral_renditadb;
require_once dirname(__DIR__) . '/class/db-functions.php';
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
?>
<style>
/* Stile per l'overlay dello spinner */
.loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 9999;
display: none;
}
.loading-overlay .spinner-custom {
width: 4rem;
height: 4rem;
border: 4px solid #fff;
border-top: 4px solid #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.loading-overlay .spinner-text {
color: #fff;
font-size: 1.2rem;
margin-top: 1rem;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<div class="card card-body">
<!-- Overlay dello spinner -->
<div id="loading-overlay" class="loading-overlay">
<div class="spinner-custom"></div>
<div class="spinner-text">Salvataggio Dati...</div>
</div>
<h4 class="card-title font-20 mt-0"><?php echo $isNew ? "Aggiungi una nuova casa" : "Modifica la tua casa"; ?></h4>
<!-- Tasto Salva in cima -->
<div class="d-flex justify-content-between align-items-center mb-3">
<button type="button" id="save-form-btn" class="btn btn-primary">
<i class="fas fa-save"></i> Salva Modifiche
</button>
<div id="save-message" class="alert d-none" role="alert"></div>
</div>
<form id="home-form">
<input type="hidden" name="idhome" value="<?php echo $idhome; ?>">
<!-- Sezione Dati Principali -->
<h4 class="mt-4">Dati Principali</h4>
<div class="form-group">
<label>Nome</label>
<input type="text" value="<?php echo htmlspecialchars($namedb); ?>" id="name" name="name" class="form-control" required>
</div>
<div class="form-group">
<label>Nota</label>
<textarea id="comment" name="comment" rows="4" class="form-control"><?php echo htmlspecialchars($commentdb); ?></textarea>
</div>
<h4 class="mt-4">Indirizzo</h4>
<div class="form-group">
<label>Indirizzo Completo</label>
<input type="text" value="<?php echo htmlspecialchars($fulladdressdb); ?>" id="fulladdress" name="fulladdress" class="form-control">
</div>
<!-- Sezione Mappa e Foto -->
<div class="row mt-4">
<div class="col-md-6 mb-3">
<h5>Geolocalizzazione</h5>
<div id="map" style="height: 200px; width: 100%; border-radius: 8px; border: 1px solid #ddd;"></div>
</div>
<div class="col-md-6 mb-3">
<h5>Foto dell'immobile</h5>
<div class="form-group">
<label for="photo">Carica Foto</label>
<input type="file" id="photo" name="photo" class="form-control" accept="image/*">
<small class="text-muted">Carica un'unica foto, verrà sovrascritta se ne scegli un'altra.</small>
</div>
<div class="form-group">
<img id="photo-preview" src="<?php echo !empty($homeData['mainphoto']) ? 'mainphoto/' . $homeData['mainphoto'] : 'assets/images/no-image.jpg'; ?>" alt="Anteprima Foto" style="max-width: 100%; height: 200px; object-fit: cover; border-radius: 8px; border: 1px solid #ddd;">
</div>
</div>
</div>
<!-- Sezione Dati Catastali -->
<h4 class="mt-4">Dati Catastali (opzionali)</h4>
<p class="text-muted mb-3">Questi campi non sono obbligatori e possono essere lasciati vuoti.</p>
<h5>Identificativi Catastali</h5>
<div class="row">
<div class="col-md-6 form-group">
<label>Comune Catastale</label>
<input type="text" id="cadastral_municipality" name="cadastral_municipality" value="<?php echo htmlspecialchars($cadastral_municipalitydb); ?>" class="form-control">
</div>
<div class="col-md-6 form-group">
<label>Sezione Catastale</label>
<input type="text" id="cadastral_section" name="cadastral_section" value="<?php echo htmlspecialchars($cadastral_sectiondb); ?>" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label>Foglio Catastale</label>
<input type="text" id="cadastral_sheet" name="cadastral_sheet" value="<?php echo htmlspecialchars($cadastral_sheetdb); ?>" class="form-control">
</div>
<div class="col-md-6 form-group">
<label>Particella Catastale</label>
<input type="text" id="cadastral_particle" name="cadastral_particle" value="<?php echo htmlspecialchars($cadastral_particledb); ?>" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label>Subalterno Catastale</label>
<input type="text" id="cadastral_sub" name="cadastral_sub" value="<?php echo htmlspecialchars($cadastral_subdb); ?>" class="form-control">
</div>
</div>
<h5 class="mt-3">Caratteristiche Catastali</h5>
<div class="row">
<div class="col-md-6 form-group">
<label>Categoria Catastale</label>
<input type="text" id="cadastral_category" name="cadastral_category" value="<?php echo htmlspecialchars($cadastral_categorydb); ?>" class="form-control">
</div>
<div class="col-md-6 form-group">
<label>Classe Catastale</label>
<input type="text" id="cadastral_class" name="cadastral_class" value="<?php echo htmlspecialchars($cadastral_classdb); ?>" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label>Superficie Catastale ()</label>
<input type="number" step="0.01" id="cadastral_surface" name="cadastral_surface" value="<?php echo htmlspecialchars($cadastral_surfacedb); ?>" class="form-control">
</div>
<div class="col-md-6 form-group">
<label>Rendita Catastale ()</label>
<input type="text" id="cadastral_rendita" name="cadastral_rendita" value="<?php echo htmlspecialchars($cadastral_renditadb); ?>" class="form-control">
</div>
</div>
<!-- Sezione Dettagli Indirizzo -->
<h4 class="mt-4">Dettagli Indirizzo</h4>
<div class="row">
<div class="col-md-6 form-group">
<label>CAP</label>
<input type="text" id="zip" name="zip" value="<?php echo htmlspecialchars($zipdb); ?>" class="form-control" readonly>
</div>
<div class="col-md-6 form-group">
<label>Città</label>
<input type="text" id="city" name="city" value="<?php echo htmlspecialchars($citydb); ?>" class="form-control" readonly>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label>Nazione</label>
<input type="text" id="country" name="country" value="<?php echo htmlspecialchars($countrydb); ?>" class="form-control" readonly>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label>Latitudine</label>
<input type="text" id="latitude" name="latitude" value="<?php echo htmlspecialchars($latitudedb); ?>" class="form-control" readonly>
</div>
<div class="col-md-6 form-group">
<label>Longitudine</label>
<input type="text" id="longitude" name="longitude" value="<?php echo htmlspecialchars($longitudedb); ?>" class="form-control" readonly>
</div>
</div>
</form>
</div>
<script>
// Gestione caricamento foto
document.getElementById('photo').addEventListener('change', function(event) {
let file = event.target.files[0];
if (!file) return;
const loadingOverlay = document.getElementById('loading-overlay');
loadingOverlay.style.display = 'flex';
let formData = new FormData();
formData.append("photo", file);
formData.append("idhome", <?php echo $idhome; ?>);
let xhr = new XMLHttpRequest();
xhr.open("POST", "save-home.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
loadingOverlay.style.display = 'none';
let response = JSON.parse(xhr.responseText);
if (response.success) {
document.getElementById('photo-preview').src = "mainphoto/" + response.filename;
showSaveMessage("Foto caricata con successo!", "success");
} else {
showSaveMessage("Errore nel caricamento della foto: " + response.message, "danger");
}
}
};
xhr.send(formData);
});
// Funzione per mostrare il messaggio di salvataggio
function showSaveMessage(message, type) {
const saveMessage = document.getElementById('save-message');
saveMessage.className = `alert alert-${type} d-block`;
saveMessage.textContent = message;
setTimeout(() => {
saveMessage.className = 'alert d-none';
}, 3000);
}
// Gestione tasto Salva con spinner
document.getElementById('save-form-btn').addEventListener('click', function() {
const loadingOverlay = document.getElementById('loading-overlay');
loadingOverlay.style.display = 'flex';
this.disabled = true;
const form = document.getElementById('home-form');
const fields = [
'name', 'comment', 'fulladdress',
'cadastral_municipality', 'cadastral_section', 'cadastral_sheet', 'cadastral_particle', 'cadastral_sub',
'cadastral_category', 'cadastral_class', 'cadastral_surface', 'cadastral_rendita',
'latitude', 'longitude', 'zip', 'city', 'country', 'address'
];
// Raccogli i dati del form
let params = `idhome=${encodeURIComponent(<?php echo $idhome; ?>)}`;
fields.forEach(field => {
const value = document.getElementById(field)?.value || '';
params += `&${field}=${encodeURIComponent(value)}`;
});
// Invia i dati tramite AJAX
const xhr = new XMLHttpRequest();
xhr.open("POST", "save-home.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
loadingOverlay.style.display = 'none';
document.getElementById('save-form-btn').disabled = false;
if (xhr.status === 200) {
let response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
showSaveMessage("Errore: Risposta non valida dal server.", "danger");
return;
}
if (response.success) {
showSaveMessage("Modifiche salvate con successo!", "success");
} else {
showSaveMessage("Errore durante il salvataggio: " + response.message, "danger");
}
} else {
showSaveMessage("Errore di connessione: " + xhr.statusText, "danger");
}
}
};
xhr.send(params);
});
// Gestione mappa
let map, marker, autocomplete;
function initAutocomplete() {
const latitude = parseFloat(document.getElementById('latitude').value);
const longitude = parseFloat(document.getElementById('longitude').value);
const defaultLocation = {
lat: 41.9028,
lng: 12.4964
};
const location = !isNaN(latitude) && !isNaN(longitude) ? {
lat: latitude,
lng: longitude
} : defaultLocation;
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 14
});
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function() {
const position = marker.getPosition();
document.getElementById('latitude').value = position.lat();
document.getElementById('longitude').value = position.lng();
});
autocomplete = new google.maps.places.Autocomplete(document.getElementById('fulladdress'), {
types: ['geocode']
});
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
const place = autocomplete.getPlace();
if (!place.geometry) {
console.error("Errore: Il luogo selezionato non contiene informazioni di geolocalizzazione.");
return;
}
const location = place.geometry.location;
if (document.getElementById('latitude')) {
document.getElementById('latitude').value = location.lat();
}
if (document.getElementById('longitude')) {
document.getElementById('longitude').value = location.lng();
}
const addressComponents = place.address_components;
let zip = "",
city = "",
country = "",
address = "";
addressComponents.forEach(component => {
const types = component.types;
if (types.includes("postal_code")) zip = component.long_name;
if (types.includes("locality")) city = component.long_name;
if (types.includes("country")) country = component.long_name;
if (types.includes("street_number") || types.includes("route")) {
address += component.long_name + " ";
}
});
if (document.getElementById('zip')) {
document.getElementById('zip').value = zip;
}
if (document.getElementById('city')) {
document.getElementById('city').value = city;
}
if (document.getElementById('country')) {
document.getElementById('country').value = country;
}
if (document.getElementById('address')) {
document.getElementById('address').value = address.trim();
}
map.setCenter(location);
marker.setPosition(location);
}
</script>
+697
View File
@@ -0,0 +1,697 @@
<?php
// Assicurati che idhome sia passato
if (!isset($idhome) || $idhome <= 0) {
die("Errore: ID immobile non valido.");
}
// Recupera i dettagli della casa
$stmt = $pdo->prepare("SELECT name, address, zip, city, country FROM home WHERE idhome = ? AND iduser = ?");
$stmt->execute([$idhome, $iduserlogin]);
$homeData = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$homeData) {
die("Errore: Casa non trovata o accesso non autorizzato.");
}
// Recupera le pagine disponibili nella tabella 'pages'
$stmt = $pdo->query("SELECT * FROM pages ORDER BY namepages");
$pages = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$pages[] = $row;
}
// Imposta lo slug predefinito
$docpage = isset($_GET['docpage']) ? $_GET['docpage'] : 'legal';
?>
<!-- Contenuto del tab Documenti -->
<div class="tab-pane fade show active" id="documenti" role="tabpanel" aria-labelledby="documenti-tab">
<div class="card">
<div class="card-body">
<!-- Dettagli della Casa -->
<div class="row align-items-center mb-4">
<div class="col-sm-8">
<h4 class="page-title m-0">Documenti per la Casa: <?php echo htmlspecialchars($homeData['name']); ?></h4>
<p class="mb-0"><strong>Indirizzo:</strong> <?php echo htmlspecialchars($homeData['address']) . ', ' . htmlspecialchars($homeData['city']) . ' ' . htmlspecialchars($homeData['zip']); ?></p>
</div>
</div>
<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>
</div>
</div>
<style>
/* Personalizza la riga della sezione */
.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 {
border-radius: 0 !important;
box-shadow: none !important;
}
.section-header i {
font-size: 1.5rem;
margin-right: 10px;
}
.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;
}
.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;
}
.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 {
cursor: pointer;
}
#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;
}
}
</style>
<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 senza ricaricare la pagina
$("#pageSelectDropdown").on("change", function() {
const slug = $(this).val();
loadDocuments(slug);
});
// Carica tutti i documenti e le sezioni da tutte le pagine per la ricerca
let allDocuments = [];
<?php
$stmt = $pdo->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 = $stmt->fetch(PDO::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');
// 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) {
$.ajax({
url: 'get-documents.php',
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 || {};
// 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;
for (let sectionName in documents) {
if (sectionCount >= 100) {
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;
(documents[sectionName] || []).forEach(document => {
if (docCount >= 100) {
console.error('Troppi loop nei documenti, possibile errore nei dati');
return;
}
docCount++;
html += `
<div class="card card-body mb-4">
<div class="document-header d-flex justify-content-between align-items-center p-3 mb-3" style="background-color: #e8f5e9; border-radius: 8px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
<div>
<span class="document-title fw-bold">${document.document_name || 'Documento senza nome'}</span>
${document.is_required ? '<span class="badge bg-danger ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Obbligatorio</span>' : ''}
${document.max_documents > 0 ? `<span class="badge bg-info ms-2" style="font-size: 1rem; padding: 0.5em 0.8em;">Max: ${document.max_documents}</span>` : ''}
</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}`);
if (collapseElement.length) {
$('.accordion-collapse.collapse').collapse('hide');
collapseElement.collapse('show');
$('html, body').animate({
scrollTop: collapseElement.offset().top - 100
}, 500);
} else {
Swal.fire({
icon: 'warning',
title: 'Attenzione',
text: 'La sezione cercata non è stata trovata.'
});
}
}, 1000);
}
// Rinizializza Dropzone per ogni documento
for (let sectionName in documents) {
(documents[sectionName] || []).forEach(document => {
if (!Dropzone.instances.some(dz => dz.element.id === `dropzone-area-${document.document_id}`)) {
new Dropzone(`#dropzone-area-${document.document_id}`, {
url: "upload-document.php",
paramName: "file",
maxFiles: document.max_documents || 1,
maxFilesize: 5,
addRemoveLinks: true,
acceptedFiles: "image/*,application/pdf",
dictDefaultMessage: "Trascina qui i file o clicca per caricarli",
dictRemoveFile: "Rimuovi",
previewTemplate: `
<div class="dz-preview dz-file-preview">
<div class="dz-image"><img data-dz-thumbnail /></div>
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size"><span data-dz-size></span></div>
</div>
<div class="dz-progress">
<span class="dz-upload" data-dz-uploadprogress></span>
</div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<div class="dz-success-mark">
<i class="fas fa-check-circle"></i>
</div>
<div class="dz-error-mark">
<i class="fas fa-times-circle"></i>
</div>
</div>
`,
init: function() {
this.on("success", function(file, response) {
try {
let parsedResponse = typeof response === "string" ? JSON.parse(response) : response;
if (parsedResponse.success) {
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) {
Swal.fire({
icon: 'error',
title: 'Errore',
text: 'Impossibile caricare i documenti: ' + error
});
}
});
}
});
</script>
+799
View File
@@ -0,0 +1,799 @@
<?php
global $idhome, $isNew, $homeData, $namedb, $addressdb, $countrydb, $citydb, $zipdb, $commentdb, $latitudedb, $longitudedb, $fulladdressdb;
require_once dirname(__DIR__) . '/class/db-functions.php';
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
// Recupera i dettagli dell'immobile
$stmt = $pdo->prepare("SELECT name, address, zip, city, country FROM home WHERE idhome = ?");
$stmt->execute([$idhome]);
$homeDetails = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$homeDetails) {
die("Immobile non trovato o accesso non autorizzato.");
}
// Recupera i proprietari associati all'immobile
$stmt = $pdo->prepare("
SELECT
po.owner_id,
po.first_name,
po.last_name,
po.company_name,
po.tax_code,
po.email,
ho.ownership_percentage,
ho.notes
FROM
home_owners AS ho
INNER JOIN
property_owners AS po ON ho.owner_id = po.owner_id
WHERE
ho.home_id = ?
");
$stmt->execute([$idhome]);
$owners = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Recupera tutti i proprietari disponibili dell'utente per la selezione
$stmt = $pdo->prepare("
SELECT
owner_id,
first_name,
last_name,
company_name,
tax_code
FROM
property_owners
WHERE
user_id = ?
AND owner_id NOT IN (
SELECT owner_id FROM home_owners WHERE home_id = ?
)
");
$stmt->execute([$iduserlogin, $idhome]);
$availableOwners = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<style>
/* Stile per l'overlay dello spinner */
.loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 9999;
display: none;
}
.loading-overlay .spinner-custom {
width: 4rem;
height: 4rem;
border: 4px solid #fff;
border-top: 4px solid #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.loading-overlay .spinner-text {
color: #fff;
font-size: 1.2rem;
margin-top: 1rem;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<div class="card card-body">
<!-- Overlay dello spinner -->
<div id="loading-overlay" class="loading-overlay">
<div class="spinner-custom"></div>
<div class="spinner-text">Caricamento...</div>
</div>
<!-- Dettagli dell'immobile -->
<div class="card-header bg-warning text-white mb-4">
<h4 class="mb-0"><?php echo htmlspecialchars($homeDetails['name']); ?></h4>
<span class="badge bg-info text-primary">
<?php echo htmlspecialchars($homeDetails['address'] . ', ' . $homeDetails['zip'] . ', ' . $homeDetails['city'] . ', ' . $homeDetails['country']); ?>
</span>
</div>
<!-- Proprietari associati -->
<div class="card mb-4">
<div class="card-header bg-success text-white">
<h5 class="mb-0">Proprietari</h5>
</div>
<div class="card-body">
<?php if (!empty($owners)) { ?>
<div id="ownersTable">
<table class="table table-bordered">
<thead>
<tr>
<th>Nome</th>
<th>Codice Fiscale</th>
<th>%</th>
<th>Note</th>
<th>Azioni</th>
</tr>
</thead>
<tbody id="ownersTableBody">
<?php
$totalPercentage = 0;
foreach ($owners as $owner) {
$totalPercentage += $owner['ownership_percentage'];
echo "<tr>
<td>" . htmlspecialchars($owner['first_name'] . ' ' . $owner['last_name']) . "</td>
<td>" . htmlspecialchars($owner['tax_code']) . "</td>
<td class='ownership-percentage'>" . htmlspecialchars($owner['ownership_percentage']) . "</td>
<td>" . htmlspecialchars($owner['notes']) . "</td>
<td>
<button class='btn btn-danger btn-sm remove-owner-btn' data-id='" . $owner['owner_id'] . "'>
<i class='fas fa-trash-alt'></i> Rimuovi
</button>
</td>
</tr>";
}
?>
</tbody>
<tfoot>
<tr>
<td colspan="2"><strong>Totale % Proprietà:</strong></td>
<td id="totalOwnership" class="font-weight-bold text-center"><?php echo $totalPercentage; ?>%</td>
<td colspan="2"></td>
</tr>
</tfoot>
</table>
</div>
<?php } else { ?>
<div id="ownersTable">
<p class="text-muted">Nessun proprietario associato.</p>
</div>
<?php } ?>
</div>
</div>
<!-- Aggiungi proprietari -->
<div class="card mb-4">
<div class="card-header bg-info text-white">
<h5 class="mb-0">Assegna Proprietari</h5>
</div>
<div class="card-body">
<form id="addOwnerForm" method="POST">
<input type="hidden" name="idhome" value="<?php echo $idhome; ?>">
<div class="form-group">
<label for="ownerSelect">Seleziona Proprietario</label>
<select class="form-control" id="ownerSelect" name="owner_id" required>
<option value="">-- Seleziona --</option>
<?php foreach ($availableOwners as $availableOwner) { ?>
<option value="<?php echo $availableOwner['owner_id']; ?>">
<?php
echo htmlspecialchars($availableOwner['first_name'] . ' ' . $availableOwner['last_name']);
if ($availableOwner['company_name']) {
echo ' (' . htmlspecialchars($availableOwner['company_name']) . ')';
}
echo ' - ' . htmlspecialchars($availableOwner['tax_code']);
?>
</option>
<?php } ?>
<option value="new_owner"> Aggiungi nuovo proprietario</option>
</select>
</div>
<div class="form-group">
<label for="ownershipPercentage">Percentuale di Proprietà</label>
<input type="number" step="0.01" class="form-control" id="ownershipPercentage" name="ownership_percentage" placeholder="Inserisci la percentuale (es. 50.00)" required>
</div>
<div class="form-group">
<label for="notes">Note</label>
<textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Aggiungi eventuali note"></textarea>
</div>
<!-- Messaggio di errore -->
<small id="percentageError" class="text-danger" style="display:none;">La somma totale non può superare il 100%.</small>
<button type="submit" id="addOwnerBtn" class="btn btn-success mt-3">Aggiungi</button>
</form>
</div>
</div>
</div>
<!-- Modal Aggiungi Nuovo Proprietario -->
<div class="modal fade" id="newOwnerModal" tabindex="-1" aria-labelledby="newOwnerModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="newOwnerModalLabel">Aggiungi Nuovo Proprietario</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="newOwnerForm">
<input type="hidden" name="user_id" value="<?php echo $iduserlogin; ?>">
<div class="row">
<!-- Tipo Proprietario -->
<div class="col-md-6">
<div class="form-group">
<label for="ownerType">Tipo Proprietario</label>
<select class="form-control" id="ownerType" name="owner_type" required>
<option value="individual">Persona Fisica</option>
<option value="company">Azienda</option>
</select>
</div>
</div>
<!-- Codice Fiscale / P. IVA -->
<div class="col-md-6">
<div class="form-group">
<label for="taxCode">Codice Fiscale / Partita IVA</label>
<input type="text" class="form-control" id="taxCode" name="tax_code" required>
</div>
</div>
<!-- Nome -->
<div class="col-md-6">
<div class="form-group">
<label for="firstName">Nome</label>
<input type="text" class="form-control" id="firstName" name="first_name">
</div>
</div>
<!-- Cognome -->
<div class="col-md-6">
<div class="form-group">
<label for="lastName">Cognome</label>
<input type="text" class="form-control" id="lastName" name="last_name">
</div>
</div>
<!-- Nome Azienda -->
<div class="col-md-12">
<div class="form-group">
<label for="companyName">Nome Azienda</label>
<input type="text" class="form-control" id="companyName" name="company_name" disabled>
</div>
</div>
<!-- Email -->
<div class="col-md-6">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
</div>
<!-- Telefono -->
<div class="col-md-6">
<div class="form-group">
<label for="phone">Telefono</label>
<input type="text" class="form-control" id="phone" name="phone">
</div>
</div>
<!-- Indirizzo -->
<div class="col-md-6">
<div class="form-group">
<label for="address">Indirizzo</label>
<input type="text" class="form-control" id="address" name="address">
</div>
</div>
<!-- CAP -->
<div class="col-md-3">
<div class="form-group">
<label for="postalCode">CAP</label>
<input type="text" class="form-control" id="postalCode" name="postal_code">
</div>
</div>
<!-- Città -->
<div class="col-md-3">
<div class="form-group">
<label for="city">Città</label>
<input type="text" class="form-control" id="city" name="city">
</div>
</div>
<!-- Provincia -->
<div class="col-md-6">
<div class="form-group">
<label for="province">Provincia</label>
<input type="text" class="form-control" id="province" name="province">
</div>
</div>
<!-- Nazione -->
<div class="col-md-6">
<div class="form-group">
<label for="country">Nazione</label>
<select class="form-control" id="country" name="country">
<option value="">-- Seleziona --</option>
<?php
$stmt = $pdo->query("SELECT id, name FROM auth_countries ORDER BY name");
while ($country = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='{$country['id']}'>" . htmlspecialchars($country['name']) . "</option>";
}
?>
</select>
</div>
</div>
<!-- Ruolo -->
<div class="col-md-6">
<div class="form-group">
<label for="role">Ruolo</label>
<input type="text" class="form-control" id="role" name="role">
</div>
</div>
<!-- Note -->
<div class="col-md-12">
<div class="form-group">
<label for="notes">Note</label>
<textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annulla</button>
<button type="submit" class="btn btn-success">Salva Proprietario</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
// Passa iduserlogin come variabile JavaScript
const iduserlogin = <?php echo $iduserlogin; ?>;
$(document).ready(function() {
// Verifica che jQuery sia caricato
if (typeof jQuery === "undefined") {
console.error("jQuery non è caricato!");
Swal.fire({
icon: "error",
title: "Errore",
text: "jQuery non è caricato. Contatta l'amministratore."
});
return;
}
// Verifica che Bootstrap modal sia caricato
if (typeof $.fn.modal === "undefined") {
console.error("Bootstrap modal non è caricato!");
Swal.fire({
icon: "error",
title: "Errore",
text: "Bootstrap modal non è caricato. Contatta l'amministratore."
});
return;
}
// Inizializza Select2 se disponibile, altrimenti usa il dropdown nativo
let isSelect2Available = typeof $.fn.select2 !== "undefined";
if (isSelect2Available) {
$("#country").select2({
width: '100%',
placeholder: "Seleziona un paese...",
allowClear: true
});
$("#ownerSelect").select2({
width: '100%',
placeholder: "-- Seleziona --"
});
} else {
console.warn("Select2 non è disponibile, utilizzo dropdown nativo.");
}
// Gestione del totale percentuale e colore
function updateTotalOwnership() {
let total = 0;
document.querySelectorAll(".ownership-percentage").forEach(function(el) {
total += parseFloat(el.textContent) || 0;
});
const totalCell = document.getElementById("totalOwnership");
// Controlla se totalCell esiste prima di aggiornarlo
if (!totalCell) {
console.warn("Elemento #totalOwnership non trovato nel DOM. Probabilmente non ci sono proprietari associati.");
return total;
}
totalCell.textContent = total.toFixed(2) + "%";
if (total >= 100) {
totalCell.style.backgroundColor = "#28a745"; // Verde
totalCell.style.color = "#fff";
document.getElementById("addOwnerForm").style.display = "none"; // Nasconde il form se il totale è 100%
} else {
totalCell.style.backgroundColor = "#ffc107"; // Arancione
totalCell.style.color = "#212529";
document.getElementById("addOwnerForm").style.display = "block";
}
return total;
}
// Validazione percentuale in tempo reale
$("#ownershipPercentage").on("input", function() {
let totalOwnership = updateTotalOwnership();
let newPercentage = parseFloat(this.value) || 0;
let remainingPercentage = 100 - totalOwnership;
let errorMsg = document.getElementById("percentageError");
let submitBtn = document.getElementById("addOwnerBtn");
if (newPercentage > remainingPercentage) {
errorMsg.style.display = "block";
submitBtn.disabled = true;
} else {
errorMsg.style.display = "none";
submitBtn.disabled = false;
}
});
// Inizializza il totale all'avvio
updateTotalOwnership();
// Selezione del proprietario nel dropdown
$("#ownerSelect").on("change", function() {
console.log("ownerSelect cambiato, valore:", $(this).val());
if ($(this).val() === "new_owner") {
try {
$("#newOwnerModal").modal("show");
$(this).val("").trigger("change");
} catch (e) {
console.error("Errore apertura modale:", e);
Swal.fire({
icon: "error",
title: "Errore",
text: "Impossibile aprire il modale per aggiungere un nuovo proprietario: " + e.message
});
}
}
});
// Abilita/disabilita i campi in base al tipo di proprietario
$("#ownerType").on("change", function() {
if ($(this).val() === "company") {
$("#companyName").prop("disabled", false);
$("#firstName, #lastName").prop("disabled", true).val("");
} else {
$("#companyName").prop("disabled", true).val("");
$("#firstName, #lastName").prop("disabled", false);
}
});
// Funzione per aggiornare il dropdown
function updateOwnerSelect() {
return fetch(`get-available-owners.php?idhome=<?php echo $idhome; ?>&iduser=${iduserlogin}`)
.then(response => {
if (!response.ok) {
throw new Error('Errore nella risposta del server: ' + response.statusText);
}
return response.text();
})
.then(html => {
const tempDiv = document.createElement("div");
tempDiv.innerHTML = html;
const newSelect = tempDiv.querySelector("select#ownerSelect");
if (newSelect) {
const ownerSelect = document.getElementById("ownerSelect");
ownerSelect.innerHTML = newSelect.innerHTML;
if (isSelect2Available) {
// Distruggi l'istanza precedente di Select2
$("#ownerSelect").select2('destroy');
// Inizializza Select2
$("#ownerSelect").select2({
width: "100%",
placeholder: "-- Seleziona --",
allowClear: true
});
// Forza Select2 a mostrare l'opzione vuota come selezionabile
const optionsCount = ownerSelect.options.length;
if (optionsCount <= 2) {
$("#ownerSelect").val(null).trigger('change');
}
}
// Debug: verifica quante opzioni ci sono nel dropdown
const optionsCount = ownerSelect.options.length;
console.log("Numero di opzioni nel dropdown dopo aggiornamento:", optionsCount);
// Verifica se il dropdown ha almeno l'opzione "Aggiungi nuovo"
const hasAddNewOption = Array.from(ownerSelect.options).some(option => option.value === "new_owner");
if (!hasAddNewOption) {
const newOption = new Option(" Aggiungi nuovo proprietario", "new_owner");
ownerSelect.appendChild(newOption);
if (isSelect2Available) {
$("#ownerSelect").trigger('change');
}
}
} else {
throw new Error("Elemento select#ownerSelect non trovato nel risultato.");
}
})
.catch(error => {
console.error("Errore aggiornamento dropdown:", error);
const ownerSelect = document.getElementById("ownerSelect");
ownerSelect.innerHTML = '<option value="">-- Seleziona --</option><option value="new_owner"> Aggiungi nuovo proprietario</option>';
if (isSelect2Available) {
$("#ownerSelect").select2({
width: "100%",
placeholder: "-- Seleziona --",
allowClear: true
});
}
Swal.fire({
icon: "error",
title: "Errore",
text: "Errore nell'aggiornamento del dropdown dei proprietari: " + error.message
});
});
}
// Funzione per aggiornare la tabella
function updateOwnersTable() {
return fetch("get-owners.php?idhome=<?php echo $idhome; ?>")
.then(response => {
if (!response.ok) {
throw new Error('Errore nella risposta del server: ' + response.statusText);
}
return response.text();
})
.then(html => {
document.getElementById("ownersTable").innerHTML = html;
updateTotalOwnership();
})
.catch(error => {
console.error("Errore aggiornamento tabella:", error);
Swal.fire({
icon: "error",
title: "Errore",
text: "Errore nell'aggiornamento della tabella dei proprietari: " + error.message
});
});
}
// Validazione client-side del form del nuovo proprietario
$("#newOwnerForm").on("submit", function(e) {
e.preventDefault();
const taxCode = $("#taxCode").val().trim();
const email = $("#email").val().trim();
const ownerType = $("#ownerType").val();
const firstName = $("#firstName").val().trim();
const lastName = $("#lastName").val().trim();
const companyName = $("#companyName").val().trim();
// Controlli di validazione
if (!taxCode) {
Swal.fire({
icon: "error",
title: "Errore",
text: "Il codice fiscale o partita IVA è obbligatorio."
});
return;
}
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
Swal.fire({
icon: "error",
title: "Errore",
text: "Inserisci un'email valida."
});
return;
}
if (ownerType === "individual" && (!firstName || !lastName)) {
Swal.fire({
icon: "error",
title: "Errore",
text: "Nome e cognome sono obbligatori per una persona fisica."
});
return;
}
if (ownerType === "company" && !companyName) {
Swal.fire({
icon: "error",
title: "Errore",
text: "Il nome dell'azienda è obbligatorio per un'azienda."
});
return;
}
const loadingOverlay = document.getElementById("loading-overlay");
loadingOverlay.style.display = "flex";
$.post("add-new-owner.php", $(this).serialize(), function(response) {
loadingOverlay.style.display = "none";
let result;
try {
result = JSON.parse(response);
} catch (e) {
Swal.fire({
icon: "error",
title: "Errore",
text: "Risposta non valida dal server: " + e.message
});
return;
}
if (result.success) {
Swal.fire({
icon: "success",
title: "Proprietario aggiunto!",
text: result.message,
timer: 1500,
showConfirmButton: false
}).then(() => {
$("#newOwnerModal").modal("hide");
// Aggiorna la tabella dei proprietari
updateOwnersTable();
// Aggiorna il dropdown dei proprietari disponibili
updateOwnerSelect();
// Resetta il form del modale
$("#newOwnerForm")[0].reset();
$("#companyName").prop("disabled", true);
$("#firstName, #lastName").prop("disabled", false);
});
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: result.message
});
}
}).fail(function(jqXHR, textStatus, errorThrown) {
loadingOverlay.style.display = "none";
Swal.fire({
icon: "error",
title: "Errore",
text: "Si è verificato un problema con la richiesta: " + textStatus + " - " + errorThrown
});
});
});
// Aggiunta di un proprietario esistente
$("#addOwnerForm").on("submit", function(e) {
e.preventDefault();
const ownerId = $("#ownerSelect").val();
const percentage = parseFloat($("#ownershipPercentage").val()) || 0;
const totalOwnership = updateTotalOwnership();
if (!ownerId) {
Swal.fire({
icon: "error",
title: "Errore",
text: "Seleziona un proprietario."
});
return;
}
if (totalOwnership + percentage > 100) {
Swal.fire({
icon: "error",
title: "Errore",
text: "La somma totale dei proprietari supererebbe il 100%."
});
return;
}
const loadingOverlay = document.getElementById("loading-overlay");
loadingOverlay.style.display = "flex";
let formData = new FormData(this);
fetch("add-owner-to-home.php", {
method: "POST",
body: formData,
})
.then(response => response.json())
.then(data => {
loadingOverlay.style.display = "none";
if (data.success) {
Swal.fire({
icon: "success",
title: "Proprietario aggiunto!",
text: data.message,
timer: 1500,
showConfirmButton: false
}).then(() => {
// Aggiorna la tabella dei proprietari
updateOwnersTable();
// Aggiorna il dropdown dei proprietari disponibili
updateOwnerSelect();
// Resetta il form
this.reset();
$("#ownerSelect").val("").trigger("change");
});
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: data.message
});
}
})
.catch(error => {
loadingOverlay.style.display = "none";
Swal.fire({
icon: "error",
title: "Errore",
text: "Si è verificato un problema con la richiesta: " + error.message
});
});
});
// Rimozione di un proprietario
$(document).on("click", ".remove-owner-btn", function() {
const ownerId = $(this).data("id");
const idhome = "<?php echo $idhome; ?>";
Swal.fire({
title: "Sei sicuro?",
text: "Questa azione rimuoverà il proprietario selezionato.",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#d33",
cancelButtonColor: "#3085d6",
confirmButtonText: "Sì, rimuovi",
cancelButtonText: "Annulla",
}).then((result) => {
if (result.isConfirmed) {
const loadingOverlay = document.getElementById("loading-overlay");
loadingOverlay.style.display = "flex";
$.post("remove-owner-from-home.php", {
owner_id: ownerId,
idhome: idhome
}, function(response) {
loadingOverlay.style.display = "none";
let result;
try {
result = JSON.parse(response);
} catch (e) {
Swal.fire({
icon: "error",
title: "Errore",
text: "Risposta non valida dal server: " + e.message
});
return;
}
if (result.success) {
Swal.fire({
icon: "success",
title: "Rimosso",
text: result.message,
timer: 1500,
showConfirmButton: false,
}).then(() => {
// Aggiorna la tabella dei proprietari
updateOwnersTable();
// Aggiorna il dropdown dei proprietari disponibili
updateOwnerSelect();
});
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: result.message,
});
}
}).fail(function(jqXHR, textStatus, errorThrown) {
loadingOverlay.style.display = "none";
Swal.fire({
icon: "error",
title: "Errore",
text: "Impossibile completare la richiesta: " + textStatus + " - " + errorThrown
});
});
}
});
});
});
</script>