$(document).ready(function() {
$('#addBuyer').click(function() {
$('.popupAddSearchContainer').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
});
$('#updateBuyerSearch').click(function() {
$('.popupUpdateBuyerSearch').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
});
$('#updateBuyerInfos').click(function() {
$('.popupUpdateBuyerInfos').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
});
$('#updatePropertyInfos').click(function() {
$('.popupUpdatePropertyInfos').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
});
$('#sendQuestionnaireButton').click(function() {
$('.popupSendQuestionnaireContainer').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
});
$('#sendPropertySheetButton').click(function() {
$('.popupSendPropertySheetContainer').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
});
$('.openSimplePopup').click(function() {
var $thisButton = $(this);
var $popup = $thisButton.closest('.group-container').find('.simplePopup');
$popup.show(); // Afficher uniquement cette popup
$('#blurBackground').show(); // Afficher le fond flou
$('body').css('overflow', 'hidden');
});
$('#addEstimationButton').click(function() {
$('.popupAddFormContainer').show();
$('#blurBackground').show();
});
$('#addPropertyButton').click(function() {
$('.popupUrlFormContainer').show();
$('#blurBackground').show();
});
// 1) Ouvrir le popup d'ajout de membres
$(document).on('click', '.openAddMemberPopup', function(e) {
e.preventDefault();
// Récupérer le groupId depuis data-group-id
const groupId = $(this).data('group-id');
// Trouver le popupAddMemberContainer dans le .group-container parent
const $popup = $(this).closest('.group-container').find('.popupAddMemberContainer');
// Afficher le popup
$popup.show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
// Injecter le groupId dans le champ caché .groupIdInput
$popup.find('.groupIdInput').val(groupId);
});
// 2) Fermer le popup quand on clique sur .closeButton
$(document).on('click', '.closePopup', function(e) {
e.preventDefault();
$(this).closest('.popupAddMemberContainer, .popupUrlFormContainer, .simplePopup').hide();
$('#blurBackground').hide();
$('body').css('overflow', 'auto');
});
// 3) Ajouter dynamiquement un champ email supplémentaire
$(document).on('click', '.addMemberEmailButton', function(e) {
e.preventDefault();
// Trouver le conteneur .additionalMembers dans ce popup
const $popup = $(this).closest('.popupAddMemberContainer');
const $additionalMembers = $popup.find('.additionalMembers');
// Générer un nom de champ unique, par exemple en se basant sur le temps
const uniqueName = 'email' + Date.now();
const newEmailHtml = `
`;
$additionalMembers.append(newEmailHtml);
});
$('.closeButton').click(function() {
location.reload();
$('body').css('overflow', 'auto');
});
$(document).mouseup(function(e) {
var container = $(".popupAddFormContainer, .popupUrlFormContainer, .simplePopup, .popupUpdateBuyerSearch, .popupUpdateBuyerInfos, .popupUpdatePropertyInfos, .popupPropertyContainer, .popupSearchDetailsContainer, .popupAddSearchContainer, .popupSendQuestionnaireContainer, .popupSendPropertySheetContainer, .popupAddMemberContainer");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
$('#blurBackground').hide();
$('body').css('overflow', 'auto');
}
});
$('.viewDetailsBuyer').click(function(e) {
e.preventDefault();
const propertyId = $(this).data('property-id');
const searchId = $(this).data('search-id');
$.ajax({
url: `/client/propertySheet/${propertyId}/${searchId}`,
method: 'GET',
success: function(data) {
if (typeof data === 'string') {
data = JSON.parse(data);
}
console.log("Données de la propriété reçues:", data);
const property = data.propertyDetails;
const searchDetails = data.searchDetails;
$('.popupPropertyContainer .h3Title').text(`${property.type || 'Type inconnu'} de ${property.surface || 'Surface inconnue'} m² à ${property.city || 'Ville inconnue'} (${property.postalCode || 'Code postal inconnu'})`);
$('.popupPropertyContainer .framePicture').css('background-image', `url('${property.propertyPath || "/img/property.png"}')`);
// Conditionner l'affichage de la ligne de lien
if (property.url && property.url !== '#') {
$('.propertyLink').attr('href', property.url).attr('target', '_blank').show();
} else {
$('.propertyLink').hide();
}
const description = property.isMandate == 1 ? (property.description || "").replace(/<[^>]*>?/gm, '') : (property.externalNote || "Lien de l'annonce: " + property.url);
$('.popupPropertyContainer input[name="externalNote"]').val(description);
$('.popupPropertyContainer .budgetCell').text(property.budget ? `${property.budget} €` : 'Non spécifié');
$('.popupPropertyContainer .surfaceCell').text(property.surface ? `${property.surface} m²` : 'Non spécifiée');
$('.popupPropertyContainer .locationCell').text(property.city && property.postalCode ? `${property.city} ${property.postalCode}` : 'Non spécifiée');
$('.popupPropertyContainer .bedroomsCell').text(property.bedroomNumber !== null ? property.bedroomNumber : 'Non spécifié');
$('.popupPropertyContainer .typeCell').text(property.type || 'Non spécifié');
if (property.firstFloor !== null) {
$('.popupPropertyContainer .rezDeChausseeRow').show();
$('.popupPropertyContainer .firstFloorCell').text(property.firstFloor === 1 ? "Oui" : "Non");
} else {
$('.popupPropertyContainer .rezDeChausseeRow').hide();
}
if (property.exterior !== null) {
$('.popupPropertyContainer .exteriorRow').show();
$('.popupPropertyContainer .exteriorCell').text(property.exterior === 1 ? "Oui" : "Non");
} else {
$('.popupPropertyContainer .exteriorRow').hide();
}
if (property.parking !== null) {
$('.popupPropertyContainer .parkingRow').show();
$('.popupPropertyContainer .parkingCell').text(property.parking === 1 ? "Oui" : "Non");
} else {
$('.popupPropertyContainer .parkingRow').hide();
}
if (property.renovation !== null) {
$('.popupPropertyContainer .renovationRow').show();
$('.popupPropertyContainer .renovationCell').text(property.renovation === 1 ? "Oui" : "Non");
} else {
$('.popupPropertyContainer .renovationRow').hide();
}
if (property.email !== null) {
$('.popupPropertyContainer .emailCell').text(property.email);
} else {
$('.popupPropertyContainer .emailCell').text("Email non spécifié");
}
if (property.phone !== null) {
$('.popupPropertyContainer .phoneCell').text(property.phone);
} else {
$('.popupPropertyContainer .phoneCell').text("Téléphone non spécifié");
}
if (property.firstName !== null) {
$('.popupPropertyContainer .firstNameCell').text(property.firstName + " " + property.lastName);
} else {
$('.popupPropertyContainer .firstNameCell').text("Prénom non spécifié");
}
if (property.userPath != null) {
$('.popupPropertyContainer .profileAvatar').attr('src', property.userPath);
} else {
$('.popupPropertyContainer .profileAvatar').attr('src', '/img/avatar.png');
}
// Remplir les boutons WhatsApp et Email pour qu'ils s'ouvrent dans un nouvel onglet
const whatsappUrl = `https://wa.me/${property.phone}?text=${encodeURIComponent(data.whatsappUrl)}`;
const emailUrl = `mailto:${searchDetails.email}?subject=Matching SuperProper&body=${encodeURIComponent(data.whatsappUrl)}`;
// Remplir les URLs des boutons et ajouter l'attribut target pour ouvrir dans un nouvel onglet
$('.miniWhatsappButton').attr('href', whatsappUrl).attr('target', '_blank');
$('.miniMailButton').attr('href', emailUrl).attr('target', '_blank');
// Affiche la popup
$('#hiddenPropertyId').val(property.propertyId);
$('.popupPropertyContainer').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Erreur lors de la récupération des détails de la propriété:', errorThrown);
alert('Une erreur est survenue lors de la récupération des détails de la propriété.');
}
});
});
$('.viewDetailsSearch').click(function(e) {
e.preventDefault(); // Empêche l'action par défaut du lien
const searchId = $(this).data('search-id');
const propertyId = $(this).data('property-id');
// Effectue l'appel AJAX pour récupérer les détails de la recherche
$.ajax({
url: `/client/api/searchDetails/${searchId}/${propertyId}`,
method: 'GET',
success: function(data) {
if (typeof data === 'string') {
data = JSON.parse(data);
}
const searchDetails = data.searchDetails;
// Remplir les données de la popup
$('.popupSearchDetailsContainer .helpText').text(searchDetails.externalNote || "Contactez le conseiller pour en savoir plus.");
$('.popupSearchDetailsContainer .dateCell').text(searchDetails.creationDateFormatted.split('-').reverse().join('/') || "Non spécifiée");
$('.popupSearchDetailsContainer .budgetCell').text(`${searchDetails.budget || 'Non spécifié'} €`);
$('.popupSearchDetailsContainer .surfaceCell').text(`${searchDetails.surface || 'Non spécifiée'} m²`);
$('.popupSearchDetailsContainer .postalCodeCell').text(searchDetails.formatPostalCodes || "Non spécifiée");
$('.popupSearchDetailsContainer .bedroomsCell').text(searchDetails.bedroomNumber || "Non spécifié");
$('.popupSearchDetailsContainer .typeCell').text(searchDetails.type || "Non spécifié");
console.log("searchDetails.distance", searchDetails.distance);
// Rez-de-chaussée, Extérieur, Stationnement, Travaux avec gestion d'affichage
if (searchDetails.distance !== null) {
$('.popupSearchDetailsContainer .distanceCell').show();
$('.popupSearchDetailsContainer .distanceCell').text(searchDetails.distance);
} else {
$('.popupSearchDetailsContainer .distanceCell').hide();
}
// Rez-de-chaussée, Extérieur, Stationnement, Travaux avec gestion d'affichage
if (searchDetails.firstFloor !== null) {
$('.popupSearchDetailsContainer .rezDeChausseeRow').show();
$('.popupSearchDetailsContainer .firstFloorCell').text(searchDetails.firstFloor === true ? "Oui" : "Non");
} else {
$('.popupSearchDetailsContainer .rezDeChausseeRow').hide();
}
if (searchDetails.exterior !== null) {
$('.popupSearchDetailsContainer .exteriorRow').show();
$('.popupSearchDetailsContainer .exteriorCell').text(searchDetails.exterior === true ? "Oui" : "Non");
} else {
$('.popupSearchDetailsContainer .exteriorRow').hide();
}
if (searchDetails.parking !== null) {
$('.popupSearchDetailsContainer .parkingRow').show();
$('.popupSearchDetailsContainer .parkingCell').text(searchDetails.parking === true ? "Oui" : "Non");
} else {
$('.popupSearchDetailsContainer .parkingRow').hide();
}
if (searchDetails.renovation !== null) {
$('.popupSearchDetailsContainer .renovationRow').show();
$('.popupSearchDetailsContainer .renovationCell').text(searchDetails.renovation === true ? "Oui" : "Non");
} else {
$('.popupSearchDetailsContainer .renovationRow').hide();
}
if (searchDetails.email !== null) {
$('.popupSearchDetailsContainer .emailCell').text(searchDetails.email);
} else {
$('.popupSearchDetailsContainer .emailCell').text("Email non spécifié");
}
if (searchDetails.phone !== null) {
$('.popupSearchDetailsContainer .phoneCell').text(searchDetails.phone);
} else {
$('.popupSearchDetailsContainer .phoneCell').text("Téléphone non spécifié");
}
if (searchDetails.firstName !== null) {
$('.popupSearchDetailsContainer .firstNameCell').text(searchDetails.firstName + " " + searchDetails.lastName);
} else {
$('.popupSearchDetailsContainer .firstNameCell').text("Prénom non spécifié");
}
if (searchDetails.path) {
$('.popupSearchDetailsContainer .profileAvatar').attr('src', searchDetails.path);
} else {
$('.popupSearchDetailsContainer .profileAvatar').attr('src', '/img/avatar.png'); // Image par défaut
}
// Remplir les boutons WhatsApp et Email pour qu'ils s'ouvrent dans un nouvel onglet
const whatsappUrl = `https://wa.me/${searchDetails.phone}?text=${encodeURIComponent(data.whatsappUrl)}`;
const emailUrl = `mailto:${searchDetails.email}?subject=Matching SuperProper&body=${encodeURIComponent(data.whatsappUrl)}`;
// Remplir les URLs des boutons et ajouter l'attribut target pour ouvrir dans un nouvel onglet
$('.miniWhatsappButton').attr('href', whatsappUrl).attr('target', '_blank');
$('.miniMailButton').attr('href', emailUrl).attr('target', '_blank');
// Affiche la popup
$('.popupSearchDetailsContainer').show();
$('#blurBackground').show();
$('body').css('overflow', 'hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Erreur lors de la récupération des détails de la recherche:', errorThrown);
alert('Une erreur est survenue lors de la récupération des détails de la recherche.');
}
});
});
$('#sendQuestionnaire').submit(function(event) {
event.preventDefault(); // Empêche l'envoi classique du formulaire
// Récupérer les valeurs du formulaire
const phoneElement = $('input[name="sendPhone"]');
const phone = phoneElement.val();
const sendMessage = $('textarea[name="sendMessage"]').val();
// Formater le numéro de téléphone
const formattedPhone = formatPhoneNumber(phone);
if (!formattedPhone) {
Swal.fire({
icon: 'error',
title: 'Numéro de téléphone invalide',
text: 'Veuillez vérifier le format du numéro de téléphone.',
showConfirmButton: false,
timer: 2000,
timerProgressBar: true,
});
return;
}
// Créer l'URL WhatsApp
const whatsappUrl = `https://wa.me/${formattedPhone}?text=${encodeURIComponent(sendMessage)}`;
// Ouvrir le lien dans un nouvel onglet
window.open(whatsappUrl, '_blank');
});
});
// Fonction de formatage du numéro de téléphone côté frontend
function formatPhoneNumber(phone) {
if (!phone) {
return null;
}
console.log(phone);
// Supprimer tous les espaces et les caractères non numériques
let formattedPhone = phone.replace(/\s+/g, '').replace(/[^\d]/g, '');
// Gérer les formats internationaux
const countryCodes = {
'33': '+33', // France
'32': '+32', // Belgium
'41': '+41', // Switzerland
'44': '+44', // United Kingdom
'49': '+49', // Germany
'34': '+34', // Spain
'39': '+39', // Italy
'31': '+31', // Netherlands
};
// Gérer les numéros commençant par '00'
if (formattedPhone.startsWith('00')) {
formattedPhone = '+' + formattedPhone.slice(2);
}
// Gérer les numéros commençant par un code pays sans '+'
let matched = false;
for (let code in countryCodes) {
if (formattedPhone.startsWith(code)) {
formattedPhone = countryCodes[code] + formattedPhone.slice(code.length);
matched = true;
break;
}
}
// Reformater les numéros français de 9 chiffres commençant par 6 ou 7
if (!matched && formattedPhone.length === 9 && /^[67]/.test(formattedPhone)) {
formattedPhone = '+33' + formattedPhone;
}
// Gérer les numéros commençant par '0' (numéros français)
if (!matched && formattedPhone.startsWith('0')) {
formattedPhone = '+33' + formattedPhone.slice(1);
}
// Gérer les numéros qui ne commencent pas par '+'
if (!formattedPhone.startsWith('+')) {
return null;
}
// Vérifier que la longueur est plausible (entre 10 et 15 chiffres)
if (formattedPhone.length < 10 || formattedPhone.length > 15) {
return null;
}
return formattedPhone;
}