credit-direct/app/models/old/credit.php
2025-12-18 09:44:42 +01:00

2275 lines
87 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace models;
use CRED_base;
use stdClass;
class CRED_credit extends CRED_base {
public static $instance;
/* public $main; */
protected $contractTypes = [
'cdi' => 'Contrat de travail à durée indéterminée (CDI)',
'cdd' => 'Contrat de travail à durée déterminée (CDD)',
'fon' => 'Nommé',
'int' => 'Intérimaire',
'oth' => 'Autre',
'ssc' => 'Sans contrat de travail'
];
protected $creditTypes = [
'pat' => 'Prêt personnel / Tous motifs / Achats divers',
'frais_notaire' => 'Financement frais de notaire',
'but_immo' => 'Crédit travaux / Rénovation / Energie',
'fin_neuve' => 'Financement véhicule NEUF',
'fin_occ_m3a' => 'Financement véhicule d\'occasion MOINS de 3 ans',
'fin_occ_p3a' => 'Financement véhicule d\'occasion PLUS de 3 ans',
'mobil_carav' => 'Financement Mobil-home et caravane',
'reno_energie' => 'Rénovation énergétique',
'regrouping' => 'Regroupement de crédit / Rachat de crédit',
'regroup_cred' => 'Regroupement de crédit / Rachat de crédit'
];
protected $creditTypesLabels = [
'pat' => 'Prêt à temprérament',
'frais_notaire' => 'Financement frais de notaire',
'but_immo' => 'Crédit travaux',
'fin_neuve' => 'Financement véhicule NEUF',
'fin_occ_m3a' => 'Financement véhicule d\'occasion MOINS de 3 ans',
'fin_occ_p3a' => 'Financement véhicule d\'occasion PLUS de 3 ans',
'am' => 'Crédit hypothécaire',
'cied' => 'Indépendant et entreprise en difficulté'
];
public $one_step_credit_types = [
'am','amr','cied','ph','frais_notaire','cdp'
];
public $creditAutos = [
'fin_neuve',
'fin_occ_m3a',
'fin_occ_p3a',
'mobil_carav'
];
public $type_habitat = [
'proprietaire' => 'Propriétaire avec prêt hypothécaire',
'proprietaire_sans_pret' => 'Propriétaire sans prêt hypothécaire',
'locataire' => 'Locataire',
'cohabitant' => 'Cohabitant'
];
/* protected $houseCreditTypes = [
'purchasehouse' => 'Achat bien immobilier',
'construction' => 'Nouvelle construction',
'purchaseabroad' => 'Achat d\'une 2éme résidence (à l\'étranger, en belgique)',
'refinancing' => 'Prêt Hypothécaire (Refinancement)',
'regrouping' => 'Prêt Hypothécaire (Regroupement)',
'balance' => 'Soulte / Rachat de parts indivisées',
'other'=> 'Autre'
]; */
protected $houseCreditTypes = [
'purchasehouse' => 'Achat bien immobilier',
'construction' => 'Nouvelle construction',
'regrouping_immo' => 'Regroupement de crédits',
'refinancing' => 'Refinancement crédit(s) hypothécaire(s)',
'purchaseabroad' => 'Achat d\'une 2éme résidence (à l\'étranger, en belgique)',
'but_immo_hypo' => 'Travaux de rénovation',
'achat_maison_de_rapport' => 'Achat maison de rapport',
'credit_pont' => 'Crédit pont',
'independants_et_entreprises_en_difficultes' => 'Indépendants et entreprises en difficultés',
'regroupement_de_credit__rachats_de_credits' => 'Rachats de crédits',
'financement_frais_de_notaire' => 'Financement frais de notaire',
'fonds_roulement_independants' => 'Fonds de roulement'
];
protected $wpdb;
private $isDevMode;
private $synchroUrl;
private $synchroClientId;
public $main;
/**
* Constructor
*/
public function __construct()
{
global $wpdb;
$this->wpdb = $wpdb;
$this->main = $this->getMain();
//instance de la classe
self::$instance = $this;
/* $this->isDevMode =
strpos($_SERVER['HTTP_HOST'], 'localhost') !== false
|| strpos($_SERVER['HTTP_HOST'], 'eteamsys') !== false
;
$this->synchroUrl = $this->isDevMode ?
'https://staging-wshubspot.eteamsys.com/'
: 'https://prod-wshubspot.eteamsys.com/'
;
$this->synchroClientId = $this->isDevMode ?
'JuIXU6EK37giPF3smU71IMBWiNHP9wlkW9TdUZwoY0u175DH11XixOQDSNi4Qmmi'
: 'RfQyevXwW0nZvoXwifnZu4VgKeGPhmlmGZsXjj0s6Aruy5qxCVOiho0Sdpw38Tcp'
; */
}
/**
* @param $token
* @return object|null
*/
public function getCredit($token) {
if (!is_string($token))
return null;
$currentCredit = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM cdf_Credit WHERE token LIKE '%s'", $token));
if (is_object($currentCredit)) {
if (!is_null($currentCredit->FK_credit_auto)) {
$currentCredit->options_credit_auto = $this->wpdb->get_row(
$this->wpdb->prepare(
"SELECT * FROM cdf_Options_credit_auto WHERE idOptions_credit_auto = %d",
$currentCredit->FK_credit_auto
)
);
}
if (!is_null($currentCredit->FK_credit_hypothecaire)) {
$currentCredit->options_credit_hypothecaire = $this->wpdb->get_row(
$this->wpdb->prepare(
"SELECT * FROM cdf_Options_credit_hypotecaire WHERE idOptions_credit_hypotecaire = %d",
$currentCredit->FK_credit_hypothecaire
)
);
}
}
return $currentCredit;
}
/**
* @return array
*/
public function getAgencies() {
$allAgencies = [];
$args = array(
'post_type' => 'agences',
'post_status' => 'publish',
'numberposts' => -1
);
$agencies = get_posts($args);
foreach($agencies as $agency) {
$objAgency = new stdClass();
$objAgency->idAgences = $agency->ID;
$objAgency->label = get_field('libele_champ',$agency->ID);
$objAgency->Nom_agence = get_field('libele_champ',$agency->ID);
$objAgency->description_agence = '';
$objAgency->emails = get_field('listing_email',$agency->ID);
$allAgencies[$agency->ID] = $objAgency;
}
return $allAgencies;
}
/**
* @return array
*/
public function getCivilStatus() {
$allCivilStatus = [];
$civilStatus = $this->wpdb->get_results("SELECT * FROM cdf_Etat_civil");
foreach ($civilStatus as $etat_civil) {
$allCivilStatus[$etat_civil->idetat_civil] = $etat_civil;
}
return $allCivilStatus;
}
public function getCreditLabel($credit_selected)
{
if(isset($this->creditTypes[$credit_selected])){
return $this->creditTypes[$credit_selected];
}
if(isset($this->houseCreditTypes[$credit_selected])){
return $this->houseCreditTypes[$credit_selected];
}
return false;
}
/**
* @return string[]
*/
public function getContractTypes()
{
return $this->contractTypes;
}
/**
* @return string[]
*/
public function getCreditTypes()
{
return $this->creditTypes;
}
/**
* @return string[]
*/
public function getCreditOptionsLabels($option_name)
{
if (!function_exists('get_field_object')) {
return false;
}
$field = get_field_object($option_name, 'option');
$field_inarray = '';
if (!$field) {
if(isset($this->creditTypesLabels[$option_name])){
return $this->creditTypesLabels[$option_name];
}
if(isset($this->houseCreditTypes[$option_name])){
return $this->houseCreditTypes[$option_name];
}
return false;
}
if ($field && isset($field['type']) && $field['type'] === 'group' && isset($field['label'])) {
return $field['label'];
}
return false;
}
/**
* @return string[]
*/
public function getHouseCreditTypes()
{
return $this->houseCreditTypes;
}
/**
* @return array
*/
public function getWorks()
{
$allWorks = [];
$works = $this->wpdb->get_results("SELECT * FROM cdf_Profession");
foreach ($works as $work) {
$allWorks[$work->idprofession] = $work;
}
return $allWorks;
}
/**
* @return array
*/
public function getExistingCreditTypes()
{
$allCreditTypes = [];
$creditTypes = $this->wpdb->get_results("SELECT * FROM cdf_Type_creance");
foreach ($creditTypes as $creditType) {
$allCreditTypes[$creditType->idtype_creance] = $creditType;
}
return $allCreditTypes;
}
/**
* @param $currentCredit
* @return array|object|void|null
*/
public function getBorrower($currentCredit) {
$borrower = $this->wpdb->get_row(
$this->wpdb->prepare(
"SELECT * FROM cdf_Emprunteur WHERE FK_demande_creditdirect = %d",
$currentCredit->idCredit
)
);
if (is_object($borrower)) {
/**
* Other credits
*/
$other_credits = $this->wpdb->get_results(
$this->wpdb->prepare(
"SELECT * FROM cdf_Autre_credit WHERE FK_emprunteur = %d",
$borrower->idemprunteur
)
);
foreach($other_credits as $other_credit) {
$FK_type_creance = $other_credit->FK_type_creance;
$type_creance = $this->wpdb->get_row(
$this->wpdb->prepare(
"SELECT * FROM cdf_Type_creance WHERE idtype_creance = %d",
$FK_type_creance
)
);
$other_credit->type_creance = $type_creance->nom_creance;
$borrower->other_credits[] = $other_credit;
}
if (!is_null($borrower->FK_agence)) {
$agency_id = $borrower->FK_agence;
$agency = get_post($agency_id);
$emails_data = get_field('listing_email',$agency_id);
$emails = [];
foreach($emails_data as $email) {
/* $emails[]['email'] = $email['email']->name;
$emails[]['type_de_contact'] = $email['type_de_contact']; */
$emails[] = ['email' => $email['email']->name, 'type_de_contact' => $email['type_de_contact']];
}
$agency->emails = $emails;
$borrower->agency = $agency;
}
/**
* Civil status
*/
if (!is_null($borrower->FK_etat_civil)) {
$borrower->etat_civil = $this->wpdb->get_results("SELECT * FROM cdf_Etat_civil WHERE idetat_civil = $borrower->FK_etat_civil");
}
}
return $borrower;
}
/**
* @param $currentCredit
* @return array|object|void|null
*/
public function getCoBorrower($currentCredit) {
$coBorrower = $this->wpdb->get_row(
$this->wpdb->prepare(
"SELECT * FROM cdf_Emprunteur WHERE FK_demande_creditdirect = %d AND parent_emprunteur IS NOT NULL",
$currentCredit->idCredit
)
);
if (is_object($coBorrower)) {
$coBorrower->other_credits = $this->wpdb->get_results(
$this->wpdb->prepare(
"SELECT * FROM cdf_Autre_credit WHERE FK_emprunteur = %d",
$coBorrower->idemprunteur
)
);
/**
* Civil status
*/
if (!is_null($coBorrower->FK_etat_civil)) {
$coBorrower->etat_civil = $this->wpdb->get_results("SELECT * FROM cdf_Etat_civil WHERE idetat_civil = $coBorrower->FK_etat_civil");
}
}
return $coBorrower;
}
/**
* @param $mailTitle
* @param $mailBody
* @param $borrower
* @return bool
*/
public function sendEmail($mailTitle, $mailBody, $borrower, $currentCredit, $attachments = [], $to_client = false) {
/* $currentCredit = $this->getCredit($borrower->token); */
$credit_type = $currentCredit->type_credit;
if(empty($credit_type)) {
$credit_type = 'credit';
}
$custom_from = 'demande-'.$credit_type.'@credit-direct.be';
$mailHeaders = [
'Content-Type: text/html; charset=UTF-8',
'X-Mailer: PHP/' . phpversion(),
'MIME-Version: 1.0',
'From: Credit Direct <'.$custom_from.'>'
];
$agencies = $this->getAgencies();
if (!empty($borrower->idemprunteur)) {
$to = [];
$zipCode = $borrower->code_postal;
if(!empty($zipCode)) {
$agency = $this->switchAgency_byZipCode($zipCode, $borrower);
}
/* echo 'prout'; */
foreach($agency['emails'] as $email) {
switch ($email['type_de_contact']) {
case 'to':
$to[] = $email['email']->name;
break;
case 'cc':
$mailHeaders[] = 'Cc: ' . $email['email']->name;
}
}
/* $to[] = 'jps@esi-informatique.com'; */
/* $to[] = 'testcreditdirect@yopmail.com'; */
if($to_client) {
$to = [$borrower->email];
$mailHeaders = [
'Content-Type: text/html; charset=UTF-8',
'X-Mailer: PHP/' . phpversion(),
'MIME-Version: 1.0',
'From: Credit Direct <votre-demande@credit-direct.be>'
];
}
if (!empty($to)) {
$mailBody = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>' . $mailTitle . '</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head><body>' . $mailBody . '</body></html>';
/* $attachments = []; */
/* foreach ($attachments as $file) {
if (file_exists($file)) {
@unlink($file);
} */
return wp_mail($to, $mailTitle, $mailBody, $mailHeaders, $attachments);
}
}
return false;
}
/**
* @param $datas
* @return void
*/
public function save_step($currentCredit) {
/* $currentCredit = $this->getCredit($datas['credit-direct-token']); */
if(!is_object($currentCredit)) {
return false;
}
$borrower = $this->getBorrower($currentCredit);
if(!is_object($borrower)) {
return false;
}
//save the current credit in a cookie for 2 months
$credit_data = [
'credit_token' => $currentCredit->token,
'current_step' => $currentCredit->last_step,
'type_credit_selected' => $currentCredit->sel_credit
];
setcookie('credit_data', json_encode($credit_data), time() + 5256000, '/');
}
/**
* @param $creditId
* @return string
*/
protected function generateToken($creditId) {
$date = new \DateTime();
$token = sha1($date->format('YmdHisu') . '-' . $creditId);
$this->wpdb->update(
'cdf_Credit',
['token' => $token],
['idCredit' => $creditId]
);
return $token;
}
/**
* @param object $currentCredit
* @param object $borrower
* @return bool
*/
protected function mailchimpSynchro($currentCredit, $borrower) {
global $post;
$json = json_encode([
'form_id' => 'credit-application',
'client_id' => $this->synchroClientId,
'name' => $borrower->nom,
'firstname' => $borrower->prenom,
'mail' => $borrower->email,
'recovery_url' => get_page_link($post) . '?token=' . $currentCredit->token,
'last_action_date' =>
!is_null($currentCredit->last_update_date) ?
$currentCredit->last_update_date :
$currentCredit->create_date
]);
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => true,
CURLOPT_ENCODING => '',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $this->synchroUrl,
CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Content-Length: ' . strlen($json)],
CURLOPT_POSTFIELDS => $json
];
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return true;
}
/**
* Mapping centralisé des champs formulaire vers la base de données pour l'emprunteur principal
*/
protected $borrowerFieldMap = [
'email' => 'email',
'lastname' => 'nom',
'firstname' => 'prenom',
'phone' => 'telephone',
'country' => 'pays',
'num_registre_national' => 'num_registre_national',
'birthdate' => 'date_naissance',
'birthplace' => 'lieu_naissance',
'nationality' => 'nationalité',
'cardnumber' => 'num_carte_identite',
'cnvaliditydate' => 'carte_identite_validite',
'nationalregistrationnumber' => 'num_registre_national',
'bankaccountnumber' => 'num_compte_bancaire',
'address' => 'adresse',
'zip' => 'code_postal',
'city' => 'localite',
'country' => 'pays',
'movingdate' => 'date_emmenagement',
'dependentchildren' => 'enfant_charge',
'montant_allocation_familiale' => 'montant_allocation_familiale',
'codependentchildren' => 'enfant_charge',
'comontant_allocation_familiale' => 'montant_allocation_familiale',
// Mappings pour les champs co-emprunteur
'cobirthdate' => 'date_naissance',
'cobirthplace' => 'lieu_naissance',
'conationality' => 'nationalité',
'cocardnumber' => 'num_carte_identite',
'cocnvaliditydate' => 'carte_identite_validite',
'conationalregistrationnumber' => 'num_registre_national',
'cobankaccountnumber' => 'num_compte_bancaire',
'coaddress' => 'adresse',
'cozip' => 'code_postal',
'cocity' => 'localite',
'cocountry' => 'pays',
'cocontract_type' => 'contract_type',
'coindependent_since' => 'independent_since',
'contract_type' => 'contract_type',
'independent_since' => 'independent_since',
'emname' => 'nom_employeur',
'emnumber' => 'numero_entreprise',
'emaddress' => 'adresse_employeur',
'emzip' => 'code_postal_employeur',
'emcity' => 'localite_employeur',
'emcountry' => 'pays_employeur',
'commitmentdate' => 'date_engagement',
'salary' => 'salaire',
'annual_taxable_income' => 'annual_taxable_income',
'oiamouthmealvoucher' => 'cheque_repas',
'oiamouthrentalincome' => 'revenus_locatifs',
'oiamouthunemployment' => 'chomage',
'oiothertext' => 'autre_revenu_type',
'oiamouthother' => 'autre_revenu_montant',
'civilstatus' => 'FK_etat_civil',
'job' => 'FK_profession',
'habitation_type' => 'habitation_type',
'habitation_loyer' => 'habitation_loyer',
'autre_revenu_type' => 'autre_revenu_type',
'autre_revenu_montant' => 'autre_revenu_montant',
'fichage_status' => 'fichage_status',
'housing_status' => 'housing_status',
'remarques' => 'remarques',
// Ajoutez d'autres mappings si besoin
];
protected $autresRevenusFieldMap = [
'oiamouthmealvoucher' => 'cheque_repas',
'oiamouthrentalincome' => 'revenus_locatifs',
'oiamouthunemployment' => 'chomage',
'oiothertext' => 'autre_revenu_type',
'oiamouthother' => 'autre_revenu_montant',
];
protected $autoFieldMap = [
'marque' => 'marque',
'vehicleregistrationdate' => 'date_immatriculation',
'sellername' => 'nom_vendeur',
'selleraddress' => 'adresse_vendeur',
'vehicleprice' => 'prix_vehicule',
'vehicule_accompte' => 'montant_accompte',
'vehicule_reprise' => 'montant_reprise',
'vehicule_emprunt' => 'montant_emprunt',
'vehicule_duree' => 'duree'
];
protected $dateFields = [
'birthdate',
'cnvaliditydate',
'movingdate',
'commitmentdate',
'vehicleregistrationdate',
'independent_since',
'date_envoi_dossier',
'date_envoi_dossier_agence',
// Champs de date co-emprunteur
'cobirthdate',
'cocnvaliditydate',
'coindependent_since'
];
protected function insert_co_emprunteur($data, $currentCredit) {
// Vérifier si l'email du co-emprunteur contient @example.com
if(isset($data['coemail']) && strpos($data['coemail'], '@example.com') !== false) {
return false; // Rejeter la demande si l'adresse email du co-emprunteur contient @example.com
}
$borrower = $this->getBorrower($currentCredit);
if (!is_object($borrower)) {
error_log('Erreur insert_co_emprunteur: borrower non trouvé pour le crédit ID: ' . $currentCredit->idCredit);
return false;
}
/* echo '<pre>';
print_r($data);
echo '</pre>';
die(); */
// Construire le tableau d'insertion en gérant les valeurs NULL et les valeurs par défaut
$insertData = array(
'nom' => isset($data['colastname']) ? $data['colastname'] : null,
'prenom' => isset($data['cofirstname']) ? $data['cofirstname'] : null,
'email' => isset($data['coemail']) ? $data['coemail'] : null,
'telephone' => isset($data['cophone']) ? $data['cophone'] : null,
'date_naissance' => isset($data['cobirthdate']) ? $data['cobirthdate'] : null,
'lieu_naissance' => isset($data['cobirthplace']) ? $data['cobirthplace'] : null,
'nationalité' => isset($data['conationality']) ? $data['conationality'] : null,
'num_carte_identite' => isset($data['cocardnumber']) ? $data['cocardnumber'] : null,
'carte_identite_validite' => isset($data['cocnvaliditydate']) ? $data['cocnvaliditydate'] : null,
'num_registre_national' => isset($data['conationalregistrationnumber']) ? $data['conationalregistrationnumber'] : null,
'num_compte_bancaire' => isset($data['cobankaccountnumber']) ? $data['cobankaccountnumber'] : null,
'adresse' => isset($data['coaddress']) ? $data['coaddress'] : null,
'code_postal' => isset($data['cozip']) ? $data['cozip'] : null,
'localite' => isset($data['cocity']) ? $data['cocity'] : null,
'pays' => isset($data['cocountry']) ? $data['cocountry'] : null,
'enfant_charge' => isset($data['codependentchildren']) ? $data['codependentchildren'] : null,
'montant_allocation_familiale' => isset($data['comontant_allocation_familiale']) && !empty($data['comontant_allocation_familiale']) ? $data['comontant_allocation_familiale'] : 0,
'contract_type' => isset($data['cocontract_type']) ? $data['cocontract_type'] : null,
'independent_since' => isset($data['coindependent_since']) && !empty($data['coindependent_since']) ? $data['coindependent_since'] : '0000-00-00',
'nom_employeur' => isset($data['coemname']) ? $data['coemname'] : null,
'numero_entreprise' => isset($data['coemnumber']) ? $data['coemnumber'] : null,
'adresse_employeur' => isset($data['coemaddress']) ? $data['coemaddress'] : null,
'code_postal_employeur' => isset($data['coemzip']) ? $data['coemzip'] : null,
'localite_employeur' => isset($data['coemcity']) ? $data['coemcity'] : null,
'pays_employeur' => isset($data['coemcountry']) ? $data['coemcountry'] : null,
'date_engagement' => isset($data['cocommitmentdate']) ? $data['cocommitmentdate'] : null,
'salaire' => isset($data['cosalary']) ? $data['cosalary'] : null,
'annual_taxable_income' => isset($data['coannual_taxable_income']) ? $data['coannual_taxable_income'] : null,
'cheque_repas' => isset($data['cooiamouthmealvoucher']) ? $data['cooiamouthmealvoucher'] : null,
'revenus_locatifs' => isset($data['cooiamouthrentalincome']) ? $data['cooiamouthrentalincome'] : null,
'chomage' => isset($data['cooiamouthunemployment']) ? $data['cooiamouthunemployment'] : null,
'autre_revenu_type' => isset($data['cooiothertext']) ? $data['cooiothertext'] : null,
'autre_revenu_montant' => isset($data['cooiamouthother']) ? $data['cooiamouthother'] : null,
'parent_emprunteur' => $borrower->idemprunteur,
'habitation_type' => isset($data['coHabitation_type']) ? $data['coHabitation_type'] : null,
'habitation_loyer' => isset($data['coHabitation_loyer']) ? $data['coHabitation_loyer'] : null,
'FK_demande_creditdirect' => $currentCredit->idCredit,
'FK_etat_civil' => isset($data['cocivilstatus']) ? $data['cocivilstatus'] : null,
'FK_profession' => isset($data['cojob']) ? $data['cojob'] : null,
'fichage_status' => isset($data['coFichage_status']) && !empty($data['coFichage_status']) ? $data['coFichage_status'] : '',
'housing_status' => isset($data['cohousing_status']) && !empty($data['cohousing_status']) ? $data['cohousing_status'] : ''
);
$result = $this->wpdb->insert('cdf_Emprunteur', $insertData);
if ($result === false) {
error_log('Erreur lors de l\'insertion du co-emprunteur. Erreur DB: ' . $this->wpdb->last_error);
error_log('Données: ' . print_r($data, true));
return false;
}
return $this->wpdb->insert_id;
}
protected function save_autre_credit_emprunteur($data,$currentCredit) {
$borrower = $this->getBorrower($currentCredit);
$updateData = [];
/* $this->wpdb->update('cdf_Emprunteur', array(
'habitation_type' => $data['habitation_type'],
'habitation_loyer' => $data['habitation_loyer'],
'habitation_charge_hypothecaire' => $data['homeowner'],
'habitation_sans_charge_locative' => $data['homewithoutrentalcharge'],
'remarques' => $data['commentary']
), array('idemprunteur' => $borrower->idemprunteur)); */
if(isset($data['habitation_type'])) {
$updateData = array(
'habitation_type' => $data['habitation_type'],
);
}
// Protection pour habitation_loyer - ne pas écraser si pas présent
if (isset($data['habitation_loyer'])) {
$updateData['habitation_loyer'] = $data['habitation_loyer'];
}
if(!empty($updateData)) {
$this->wpdb->update('cdf_Emprunteur', $updateData, array('idemprunteur' => $borrower->idemprunteur));
}
if (
array_key_exists('hascurrentloan', $data) && $data['hascurrentloan'] === '1'
&& array_key_exists('currentloans', $data) && !empty($data['currentloans'])
) {
/* echo '<pre>';
print_r($data['currentloans']);
echo '</pre>';
die(); */
foreach ($data['currentloans'] as $currentLoan) {
$this->wpdb->insert(
'cdf_Autre_credit',
array(
'banque' => $currentLoan['bankname'],
'montant' => $currentLoan['borrowedcapital'],
'duree_credit' => $currentLoan['durationmonth'],
'mensualite' => $currentLoan['monthlypayment'],
'date_premiere_echeance' => $currentLoan['firstduedate'],
'solde_restant_du' => $currentLoan['remainingbalance'],
'cloture' => $currentLoan['hasclosed'],
'FK_type_creance' => $currentLoan['loantype'],
'FK_emprunteur' => $borrower->idemprunteur
)
);
}
}
}
protected function save_autre_credit_co_emprunteur($data, $currentCredit) {
$borrower = $this->getBorrower($currentCredit);
// Recharger le crédit pour s'assurer que le co-emprunteur nouvellement créé est disponible
if (is_object($currentCredit) && isset($currentCredit->token)) {
$currentCredit = $this->getCredit($currentCredit->token);
}
$coBorrower = $this->getCoBorrower($currentCredit);
// Si le co-emprunteur n'existe toujours pas, on ne peut pas continuer
if (!is_object($coBorrower)) {
return;
}
$updateData = [];
/* $this->wpdb->update('cdf_Emprunteur', array(
'habitation_type' => $data['habitation_type'],
'habitation_loyer' => $data['habitation_loyer'],
'habitation_charge_hypothecaire' => $data['habitation_charge_hypothecaire'],
'habitation_sans_charge_locative' => $data['habitation_sans_charge_locative']
), array(
'idemprunteur' => $coBorrower->idemprunteur,
'parent_emprunteur' => $borrower->idemprunteur
)); */
if(isset($data['coHabitation_type'])) {
$updateData = array(
'habitation_type' => $data['coHabitation_type'],
);
}
// Protection pour habitation_loyer - ne pas écraser si pas présent
if (isset($data['coHabitation_loyer'])) {
$updateData['habitation_loyer'] = $data['coHabitation_loyer'];
}
if(!empty($updateData)) {
$this->wpdb->update('cdf_Emprunteur', $updateData, array('idemprunteur' => $coBorrower->idemprunteur));
}
if (
array_key_exists('cohascurrentloan', $data) && $data['cohascurrentloan'] === '1'
&& array_key_exists('cocurrentloans', $data) && !empty($data['cocurrentloans'])
) {
foreach ($data['cocurrentloans'] as $currentLoan) {
$this->wpdb->insert(
'cdf_Autre_credit',
array(
'banque' => $currentLoan['bankname'],
'montant' => $currentLoan['borrowedcapital'],
'duree_credit' => $currentLoan['durationmonth'],
'mensualite' => $currentLoan['monthlypayment'],
'date_premiere_echeance' => $currentLoan['firstduedate'],
'solde_restant_du' => $currentLoan['remainingbalance'],
'cloture' => $currentLoan['hasclosed'],
'FK_type_creance' => $currentLoan['loantype'],
'FK_emprunteur' => $coBorrower->idemprunteur
)
);
}
}
}
/**
* Gère les uploads de fichiers et génère une liste HTML de liens
* @param array $files Les fichiers uploadés ($_FILES)
* @param array $allowed_types Les types MIME autorisés
* @param int $max_size Taille maximale en octets
* @param string $token Le token du crédit
* @return array ['files' => [], 'errors' => [], 'html_links' => string]
*/
public function handleUploads($files, $allowed_types, $max_size, $token) {
$uploaded_files = [];
$errors = [];
$html_links = '';
// Limite de taille totale pour l'envoi par email (10MB)
$total_size_limit = 10 * 1024 * 1024; // 10MB en octets
$total_size = 0;
// Mapping des noms de champs vers les types de documents
$field_to_doc_type = [
'paycheck' => 'fiche_paie',
'cojob' => 'fiche_paie_co',
'notice_of_assessment' => 'avis_imposition',
'conotice_of_assessment' => 'avis_imposition_co',
'identity_card' => 'carte_identite',
'coidentity_card' => 'carte_identite_co',
'tax_notice' => 'avis_imposition',
'cotax_notice' => 'avis_imposition_co',
'property_tax' => 'taxe_fonciere',
'coproperty_tax' => 'taxe_fonciere_co',
'rent_receipt' => 'quittance_loyer',
'corent_receipt' => 'quittance_loyer_co',
'compromise' => 'compromis_vente',
'cocompromise' => 'compromis_vente_co'
];
// Première passe : calculer la taille totale des fichiers
// Détecter le type de structure de fichiers
$is_direct_structure = isset($files['name']) && is_array($files['name']);
if ($is_direct_structure) {
// Structure directe : $files['name'], $files['type'], etc.
$file_count = count($files['name']);
for ($i = 0; $i < $file_count; $i++) {
// Sauter si pas de fichier uploadé
if ($files['error'][$i] === 4) continue;
if ($files['error'][$i] === 0) {
$total_size += $files['size'][$i];
}
}
} else {
// Structure avec champs nommés : $files['test1'], $files['test2'], etc.
foreach ($files as $field_name => $file) {
if (is_array($file['name'])) {
// Champ multiple
$file_count = count($file['name']);
for ($i = 0; $i < $file_count; $i++) {
if ($file['error'][$i] === 4) continue;
if ($file['error'][$i] === 0) {
$total_size += $file['size'][$i];
}
}
} else {
// Champ simple
if ($file['error'] !== 4 && $file['error'] === 0) {
$total_size += $file['size'];
}
}
}
}
// Vérifier la taille totale
if ($total_size > $total_size_limit) {
$errors[] = "La taille totale des fichiers (" . round($total_size / 1024 / 1024, 2) . " MB) dépasse la limite autorisée de 10 MB pour l'envoi par email.";
return [
'files' => [],
'errors' => $errors,
'html_links' => ''
];
}
// Créer le dossier de destination s'il n'existe pas
$upload_dir = \wp_upload_dir()['basedir'] . '/credit_direct/clients/' . $token;
if (!file_exists($upload_dir)) {
\wp_mkdir_p($upload_dir);
}
// Traiter chaque fichier uploadé
if ($is_direct_structure) {
// Structure directe : $files['name'], $files['type'], etc.
$file_count = count($files['name']);
for ($i = 0; $i < $file_count; $i++) {
// Sauter si pas de fichier uploadé
if ($files['error'][$i] === 4) continue;
if ($files['error'][$i] !== 0) {
$errors[] = "Erreur lors de l'upload du fichier ($i): " . $this->getUploadErrorMessage($files['error'][$i]);
continue;
}
if (!in_array($files['type'][$i], $allowed_types)) {
$errors[] = "Type de fichier non autorisé pour le fichier ($i): " . $files['type'][$i];
continue;
}
if ($files['size'][$i] > $max_size) {
$errors[] = "Fichier trop volumineux pour le fichier ($i): " . round($files['size'][$i] / 1024 / 1024, 2) . " Mo";
continue;
}
// Générer le nom du fichier avec index
$original_name = $files['name'][$i];
$extension = pathinfo($original_name, PATHINFO_EXTENSION);
$new_filename = $token . '_document_' . ($i+1) . '.' . $extension;
$destination = $upload_dir . '/' . $new_filename;
if (move_uploaded_file($files['tmp_name'][$i], $destination)) {
$uploaded_files[] = $destination;
$file_url = content_url('/uploads/credit_direct/clients/' . $token . '/' . $new_filename);
$html_links .= sprintf(
'<li><a href="%s" target="_blank">%s</a></li>',
esc_url($file_url),
esc_html($original_name)
);
} else {
$errors[] = "Impossible de déplacer le fichier ($i)";
}
}
} else {
// Structure avec champs nommés : $files['test1'], $files['test2'], etc.
foreach ($files as $field_name => $file) {
if (is_array($file['name'])) {
// Champ multiple
$file_count = count($file['name']);
for ($i = 0; $i < $file_count; $i++) {
// Sauter si pas de fichier uploadé
if ($file['error'][$i] === 4) continue;
if ($file['error'][$i] !== 0) {
$errors[] = "Erreur lors de l'upload du fichier $field_name ($i): " . $this->getUploadErrorMessage($file['error'][$i]);
continue;
}
if (!in_array($file['type'][$i], $allowed_types)) {
$errors[] = "Type de fichier non autorisé pour $field_name ($i): " . $file['type'][$i];
continue;
}
if ($file['size'][$i] > $max_size) {
$errors[] = "Fichier trop volumineux pour $field_name ($i): " . round($file['size'][$i] / 1024 / 1024, 2) . " Mo";
continue;
}
// Générer le nom du fichier avec type de document
$doc_type = isset($field_to_doc_type[$field_name]) ? $field_to_doc_type[$field_name] : $field_name;
$extension = pathinfo($file['name'][$i], PATHINFO_EXTENSION);
$new_filename = $token . '_' . $doc_type . '_' . ($i+1) . '.' . $extension;
$destination = $upload_dir . '/' . $new_filename;
if (move_uploaded_file($file['tmp_name'][$i], $destination)) {
$uploaded_files[] = $destination;
$file_url = content_url('/uploads/credit_direct/clients/' . $token . '/' . $new_filename);
$html_links .= sprintf(
'<li><a href="%s" target="_blank">%s</a></li>',
esc_url($file_url),
esc_html(ucfirst(str_replace('_', ' ', $doc_type))) . ' (' . ($i+1) . ')'
);
} else {
$errors[] = "Impossible de déplacer le fichier $field_name ($i)";
}
}
} else {
// Champ simple
if ($file['error'] === 4) continue; // Pas de fichier uploadé
if ($file['error'] !== 0) {
$errors[] = "Erreur lors de l'upload du fichier $field_name: " . $this->getUploadErrorMessage($file['error']);
continue;
}
if (!in_array($file['type'], $allowed_types)) {
$errors[] = "Type de fichier non autorisé pour $field_name: " . $file['type'];
continue;
}
if ($file['size'] > $max_size) {
$errors[] = "Fichier trop volumineux pour $field_name: " . round($file['size'] / 1024 / 1024, 2) . " Mo";
continue;
}
// Générer le nom du fichier
$doc_type = isset($field_to_doc_type[$field_name]) ? $field_to_doc_type[$field_name] : $field_name;
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$new_filename = $token . '_' . $doc_type . '.' . $extension;
$destination = $upload_dir . '/' . $new_filename;
if (move_uploaded_file($file['tmp_name'], $destination)) {
$uploaded_files[] = $destination;
$file_url = content_url('/uploads/credit_direct/clients/' . $token . '/' . $new_filename);
$html_links .= sprintf(
'<li><a href="%s" target="_blank">%s</a></li>',
esc_url($file_url),
esc_html(ucfirst(str_replace('_', ' ', $doc_type)))
);
} else {
$errors[] = "Impossible de déplacer le fichier $field_name";
}
}
}
}
return [
'files' => $uploaded_files,
'errors' => $errors,
'html_links' => $html_links ? '<ul class="uploaded-files">' . $html_links . '</ul>' : ''
];
}
/**
* Retourne un message d'erreur lisible pour les codes d'erreur d'upload
* @param int $error_code Le code d'erreur PHP
* @return string Le message d'erreur
*/
private function getUploadErrorMessage($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return "Le fichier dépasse la taille maximale autorisée par PHP";
case UPLOAD_ERR_FORM_SIZE:
return "Le fichier dépasse la taille maximale autorisée par le formulaire";
case UPLOAD_ERR_PARTIAL:
return "Le fichier n'a été que partiellement uploadé";
case UPLOAD_ERR_NO_FILE:
return "Aucun fichier n'a été uploadé";
case UPLOAD_ERR_NO_TMP_DIR:
return "Dossier temporaire manquant";
case UPLOAD_ERR_CANT_WRITE:
return "Impossible d'écrire le fichier sur le disque";
case UPLOAD_ERR_EXTENSION:
return "Une extension PHP a arrêté l'upload du fichier";
default:
return "Erreur inconnue lors de l'upload";
}
}
/**
* Récupère tous les fichiers uploadés pour un token de crédit donné
* @param string $token Le token du crédit
* @return array Array d'URLs des fichiers uploadés
*/
public function getUploadedFiles($token) {
$uploaded_files = [];
// Limite de taille totale pour l'envoi par email (10MB)
$total_size_limit = 10 * 1024 * 1024; // 10MB en octets
$total_size = 0;
// Construire le chemin du dossier
$upload_dir = \wp_upload_dir()['basedir'] . '/credit_direct/clients/' . $token;
// Vérifier si le dossier existe
if (!file_exists($upload_dir) || !is_dir($upload_dir)) {
return $uploaded_files;
}
// Récupérer tous les fichiers du dossier
$files = scandir($upload_dir);
foreach ($files as $file) {
// Ignorer les dossiers . et ..
if ($file === '.' || $file === '..') {
continue;
}
// Construire l'URL complète du fichier
$file_path = $upload_dir . '/' . $file;
// Vérifier que c'est bien un fichier
if (is_file($file_path)) {
$file_size = filesize($file_path);
$total_size += $file_size;
// Vérifier si la taille totale dépasse la limite
if ($total_size > $total_size_limit) {
// Retourner les fichiers déjà trouvés avec un avertissement
$uploaded_files[] = 'WARNING: Taille totale dépassée (' . round($total_size / 1024 / 1024, 2) . ' MB)';
break;
}
$file_url = content_url('/uploads/credit_direct/clients/' . $token . '/' . $file);
$uploaded_files[] = $file_url;
}
}
// Trier les fichiers par ordre alphabétique
sort($uploaded_files);
return $uploaded_files;
}
/**
* Récupère tous les fichiers uploadés avec leurs métadonnées pour un token de crédit donné
* @param string $token Le token du crédit
* @return array Array avec les informations des fichiers (url, nom, type, taille, date)
*/
public function getUploadedFilesWithMetadata($token) {
$uploaded_files = [];
// Limite de taille totale pour l'envoi par email (10MB)
$total_size_limit = 10 * 1024 * 1024; // 10MB en octets
$total_size = 0;
$size_limit_exceeded = false;
// Construire le chemin du dossier
$upload_dir = \wp_upload_dir()['basedir'] . '/credit_direct/clients/' . $token;
// Vérifier si le dossier existe
if (!file_exists($upload_dir) || !is_dir($upload_dir)) {
return $uploaded_files;
}
// Récupérer tous les fichiers du dossier
$files = scandir($upload_dir);
foreach ($files as $file) {
// Ignorer les dossiers . et ..
if ($file === '.' || $file === '..') {
continue;
}
$file_path = $upload_dir . '/' . $file;
// Vérifier que c'est bien un fichier
if (is_file($file_path)) {
$file_size = filesize($file_path);
$total_size += $file_size;
// Vérifier si la taille totale dépasse la limite
if ($total_size > $total_size_limit && !$size_limit_exceeded) {
$size_limit_exceeded = true;
$uploaded_files[] = [
'url' => '',
'filename' => 'WARNING',
'doc_type' => 'size_limit',
'size' => 0,
'size_formatted' => '0 B',
'modified_date' => time(),
'extension' => '',
'warning' => 'La taille totale des fichiers (' . round($total_size / 1024 / 1024, 2) . ' MB) dépasse la limite de 10 MB pour l\'envoi par email.'
];
break;
}
$file_url = content_url('/uploads/credit_direct/clients/' . $token . '/' . $file);
// Extraire le type de document du nom de fichier
$file_info = pathinfo($file);
$filename_parts = explode('_', $file_info['filename']);
// Le type de document est généralement après le token
$doc_type = isset($filename_parts[1]) ? $filename_parts[1] : 'unknown';
$uploaded_files[] = [
'url' => $file_url,
'filename' => $file,
'doc_type' => $doc_type,
'size' => $file_size,
'size_formatted' => $this->formatFileSize($file_size),
'modified_date' => filemtime($file_path),
'extension' => strtolower($file_info['extension']),
'total_size' => $total_size,
'total_size_formatted' => $this->formatFileSize($total_size)
];
}
}
// Trier par date de modification (plus récent en premier)
usort($uploaded_files, function($a, $b) {
return $b['modified_date'] - $a['modified_date'];
});
return $uploaded_files;
}
/**
* Formate la taille d'un fichier en format lisible
* @param int $bytes Taille en octets
* @return string Taille formatée
*/
private function formatFileSize($bytes) {
$units = ['B', 'KB', 'MB', 'GB'];
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
$bytes /= 1024;
}
return round($bytes, 2) . ' ' . $units[$i];
}
/**
* Vérifie si une demande de crédit est en cours pour l'utilisateur
* @return array|false Retourne les données de la demande en cours ou false
*/
public function checkOngoingCreditRequest($debug = false) {
/* if(isset($_GET['debug'])) {
echo '<pre>';
print_r($_COOKIE['credit_data']);
echo '</pre>';
} */
$debug = false;
if (isset($_COOKIE['credit_data']) || $debug) {
$_COOKIE['credit_data'] = stripslashes($_COOKIE['credit_data']);
$credit_data = null;
if(isset($_COOKIE['credit_data'])) {
$credit_data = json_decode($_COOKIE['credit_data'], true);
}
if($debug) {
$credit_data = [];
$credit_data['credit_token'] = '151b8853cc8a501e61bb4d0f0fdd05bc1a4d73e8';
}
if ($credit_data && isset($credit_data['credit_token'])) {
$currentCredit = $this->getCredit($credit_data['credit_token']);
if ($currentCredit && is_object($currentCredit)) {
// Récupérer les données de l'emprunteur pour avoir plus d'informations
$borrower = $this->getBorrower($currentCredit);
return [
'token' => $currentCredit->token,
'step' => $currentCredit->last_step,
'type' => $currentCredit->type_credit,
'capital' => $currentCredit->capital,
'duree' => $currentCredit->duree,
'has_borrower' => !empty($borrower),
'has_co_borrower' => !empty($this->getCoBorrower($currentCredit)),
'last_update_date' => $currentCredit->last_update_date
];
}
}
}
return false;
}
public function get_ongoing_credit_token() {
$token = null;
if(isset($_GET['credit-direct-token'])) {
$token = $_GET['credit-direct-token'];
$credit_data = $this->getCredit($token);
if($credit_data) {
$token = $credit_data->token;
}
} else {
$ongoing_credit = $this->checkOngoingCreditRequest();
if($ongoing_credit) {
$token = $ongoing_credit['token'];
}
}
return $token;
}
public function get_agency($location) {
$agency_mail = '';
$location = sanitize_title($location);
$agence = [];
//location = slug de la page agence
$args = array(
'post_type' => 'agences',
'name' => $location,
'posts_per_page' => 1
);
$agencies = get_posts($args);
if($agencies) {
$agency = $agencies[0];
$agence['id'] = $agency->ID;
$agence['name'] = $agency->post_title;
$agence['emails'] = get_field('listing_email', $agency->ID);
}
return $agence;
}
public function switchAgency_byZipCode(int $zipCode, object $borrower): array {
$agency_mail = [];
$mons = $this->get_agency('mons');
$verviers = $this->get_agency('verviers');
$pays = $this->getFieldValue('pays', $borrower);
if($pays == 'LU') {
$agency_mail = $verviers;
return $agency_mail;
}
if (($zipCode >= 4000 && $zipCode <= 4999) || // Liège
($zipCode >= 6600 && $zipCode <= 6999)) { // Luxembourg
$agency_mail = $verviers;
}
$wallonieBruxelles =
($zipCode >= 1000 && $zipCode <= 1299) || // BruxellesCapitale
($zipCode >= 1300 && $zipCode <= 1499) || // Brabant wallon
($zipCode >= 5000 && $zipCode <= 5680) || // Namur
($zipCode >= 6000 && $zipCode <= 6599) || // Hainaut (partie 1)
($zipCode >= 7000 && $zipCode <= 7999);
$agency_mail = $wallonieBruxelles ? $mons : $verviers;
return $agency_mail;
}
/**
* Vérifie si la taille totale des fichiers pour un token dépasse la limite email
* @param string $token Le token du crédit
* @return array ['exceeded' => bool, 'total_size' => int, 'total_size_formatted' => string, 'limit' => int, 'limit_formatted' => string]
*/
public function checkTotalFileSize($token) {
$total_size_limit = 10 * 1024 * 1024; // 10MB en octets
$total_size = 0;
// Construire le chemin du dossier
$upload_dir = \wp_upload_dir()['basedir'] . '/credit_direct/clients/' . $token;
// Vérifier si le dossier existe
if (!file_exists($upload_dir) || !is_dir($upload_dir)) {
return [
'exceeded' => false,
'total_size' => 0,
'total_size_formatted' => '0 B',
'limit' => $total_size_limit,
'limit_formatted' => '10 MB'
];
}
// Récupérer tous les fichiers du dossier
$files = scandir($upload_dir);
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$file_path = $upload_dir . '/' . $file;
if (is_file($file_path)) {
$total_size += filesize($file_path);
}
}
return [
'exceeded' => $total_size > $total_size_limit,
'total_size' => $total_size,
'total_size_formatted' => $this->formatFileSize($total_size),
'limit' => $total_size_limit,
'limit_formatted' => '10 MB'
];
}
/**
* Récupère la valeur d'un champ pour l'emprunteur ou le co-emprunteur
* @param string $fieldName Le nom du champ
* @param object $borrower Les données de l'emprunteur
* @return string La valeur à afficher dans le champ
*/
public function getFieldValue($fieldName, $borrower) {
$value = '';
$map = $this->borrowerFieldMap;
// Détermine si c'est un champ co-emprunteur basé sur le préfixe 'co'
$isCoBorrowerField = strpos($fieldName, 'co') === 0;
if ($isCoBorrowerField) {
// Récupère le co-emprunteur automatiquement
$currentCredit = $this->getCreditFromBorrower($borrower);
$coBorrower = $currentCredit ? $this->getCoBorrower($currentCredit) : null;
if (is_object($coBorrower)) {
// Retire le préfixe 'co' pour retrouver la clé de mapping
$baseField = substr($fieldName, 2);
if (isset($map[$baseField])) {
$dbField = $map[$baseField];
if (isset($coBorrower->$dbField)) {
$value = $coBorrower->$dbField;
}
} elseif (isset($coBorrower->$fieldName)) {
$value = $coBorrower->$fieldName;
}
}
} else if (is_object($borrower)) {
if (isset($map[$fieldName])) {
$dbField = $map[$fieldName];
if (isset($borrower->$dbField)) {
$value = $borrower->$dbField;
}
} elseif (isset($borrower->$fieldName)) {
$value = $borrower->$fieldName;
}
}
if(in_array($fieldName, $this->dateFields) && !empty($value)) {
$value = \DateTime::createFromFormat('Y-m-d', $value)->format('d/m/Y');
}
if(!empty($value)) {
return htmlspecialchars($value);
}
}
/**
* Récupère le crédit à partir de l'emprunteur
* @param object $borrower Les données de l'emprunteur
* @return object|null Le crédit associé
*/
private function getCreditFromBorrower($borrower) {
if (!is_object($borrower) || !isset($borrower->FK_demande_creditdirect)) {
return null;
}
return $this->wpdb->get_row(
$this->wpdb->prepare(
"SELECT * FROM cdf_Credit WHERE idCredit = %d",
$borrower->FK_demande_creditdirect
)
);
}
/**
* Fonction helper pour vérifier si une option est sélectionnée
* @param string $fieldName Le nom du champ
* @param string $optionValue La valeur de l'option
* @param object $borrower Les données de l'emprunteur
* @return string 'selected' si l'option doit être sélectionnée
*/
public function isOptionSelected($fieldName, $optionValue, $borrower) {
$currentValue = $this->getFieldValue($fieldName, $borrower);
return ($currentValue == $optionValue) ? 'selected' : '';
}
/**
* Fonction helper pour vérifier si une radio est cochée
* @param string $fieldName Le nom du champ
* @param string $optionValue La valeur de l'option
* @param object $borrower Les données de l'emprunteur
* @return string 'checked' si l'option doit être cochée
*/
public function isRadioChecked($fieldName, $optionValue, $borrower) {
$currentValue = $this->getFieldValue($fieldName, $borrower);
return ($currentValue == $optionValue) ? 'checked' : '';
}
public function hasCreditCoBorrower($currentCredit) {
$hasCreditCoBorrower = false;
$coBorrower = $this->getCoBorrower($currentCredit);
if($coBorrower) {
$hasCreditCoBorrower = true;
}
return $hasCreditCoBorrower;
}
/**
* Fonction helper pour vérifier si une checkbox est cochée
* @param string $fieldName Le nom du champ
* @param string $optionValue La valeur de l'option
* @param object $borrower Les données de l'emprunteur
* @return string 'checked' si l'option doit être cochée
*/
public function isCheckboxChecked($fieldName, $optionValue, $borrower) {
$currentValue = $this->getFieldValue($fieldName, $borrower);
return ($currentValue == $optionValue) ? 'checked' : '';
}
/**
* Récupère les crédits en cours d'un emprunteur
* @param object $borrower Les données de l'emprunteur
* @return array Liste des crédits en cours
*/
public function getCurrentLoans($borrower) {
if (!is_object($borrower) || !isset($borrower->idemprunteur)) {
return [];
}
$query = $this->wpdb->prepare(
"SELECT * FROM cdf_Autre_credit WHERE FK_emprunteur = %d ORDER BY idautrecredit ASC",
$borrower->idemprunteur
);
return $this->wpdb->get_results($query);
}
/**
* Génère le HTML pour pré-remplir les crédits en cours
* @param object $borrower Les données de l'emprunteur
* @param string $prefix Préfixe pour les champs co-emprunteur (ex: 'co')
* @return string HTML des crédits pré-remplis
*/
public function getCurrentLoansHTML($borrower, $prefix = '') {
$currentLoans = $this->getCurrentLoans($borrower);
$html = '';
$index = 0;
$class_col = $this->hasCoBorrower($borrower) ? 'col-md-3' : 'col-md-6';
foreach ($currentLoans as $loan) {
$html .= '<div class="py-5 wpcf-currentloan--block">';
$html .= '<button type="button" class="close wpcf-currentloan--block--remove wpcf-btn-retirer" aria-label="Retirer">';
$html .= '<span class="wpcf-btn-retirer__icon" aria-hidden="true" style="vertical-align:middle;display:inline-block;width:1em;height:1em;"><svg viewBox="0 0 16 16" fill="currentColor" width="1em" height="1em" style="vertical-align:middle;"><path d="M2.146 2.146a.5.5 0 0 1 .708 0L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8 2.146 2.854a.5.5 0 0 1 0-.708z"/></svg></span> Retirer';
$html .= '</button>';
$html .= '<div class="form-row">';
// Type de créance
$html .= '<div class="form-group ' . $class_col . '">';
$html .= '<label for="ID' . $index . $prefix . 'loantype">Type de créance</label>';
$html .= '<select name="' . $prefix . 'currentloans[' . $index . '][loantype]" id="ID' . $index . $prefix . 'loantype" class="form-control" required>';
$html .= '<option value="">Veuillez faire un choix</option>';
$typesCreance = $this->wpdb->get_results("SELECT * FROM cdf_Type_creance");
foreach ($typesCreance as $typeCreance) {
$selected = ($loan->FK_type_creance == $typeCreance->idtype_creance) ? 'selected' : '';
$html .= '<option value="' . $typeCreance->idtype_creance . '" ' . $selected . '>' . $typeCreance->nom_creance . '</option>';
}
$html .= '</select></div>';
// Nom de l'organisme / Banque
$html .= '<div class="form-group ' . $class_col . '">';
$html .= '<label for="ID' . $index . $prefix . 'bankname">Nom de l\'organisme / Banque</label>';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][bankname]" type="text" class="form-control" id="ID' . $index . $prefix . 'bankname" value="' . htmlspecialchars($loan->banque) . '" required>';
$html .= '</div>';
// Capital emprunté
$html .= '<div class="form-group ' . $class_col . '">';
$html .= '<label for="ID' . $index . $prefix . 'borrowedcapital">Capital emprunté</label>';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][borrowedcapital]" type="number" class="form-control" id="ID' . $index . $prefix . 'borrowedcapital" min="0" step="0.01" value="' . $loan->montant . '" required>';
$html .= '</div>';
// Durée du crédit
$html .= '<div class="form-group ' . $class_col . '">';
$html .= '<label for="ID' . $index . $prefix . 'durationmonth">Durée du crédit (en mois)</label>';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][durationmonth]" type="number" class="form-control" id="ID' . $index . $prefix . 'durationmonth" min="0" step="1" value="' . $loan->duree_credit . '" required>';
$html .= '</div>';
// Mensualité
$html .= '<div class="form-group ' . $class_col . '">';
$html .= '<label for="ID' . $index . $prefix . 'monthlypayment">Mensualité</label>';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][monthlypayment]" type="number" class="form-control" id="ID' . $index . $prefix . 'monthlypayment" min="0" step="0.01" value="' . $loan->mensualite . '" required>';
$html .= '</div>';
// Date 1ère échéance
$html .= '<div class="form-group ' . $class_col . '">';
$html .= '<label for="ID' . $index . $prefix . 'firstduedate">Date 1ère échéance</label>';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][firstduedate]" type="date" class="form-control" id="ID' . $index . $prefix . 'firstduedate" value="' . $loan->date_premiere_echeance . '" required>';
$html .= '</div>';
// Solde restant dû
$html .= '<div class="form-group ' . $class_col . '">';
$html .= '<label for="ID' . $index . $prefix . 'remainingbalance">Solde restant dû (approximatif)</label>';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][remainingbalance]" type="number" class="form-control" id="ID' . $index . $prefix . 'remainingbalance" min="0" step="0.01" value="' . $loan->solde_restant_du . '" required>';
$html .= '</div>';
// À clôturer / Solder
$html .= '<div class="' . $class_col . ' form-group">';
$html .= '<div class="col-form-label pr-3">À clôturer / Solder ?</div>';
$html .= '<div class="form-check form-check-inline">';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][hasclosed]" type="radio" class="form-check-input" id="ID' . $index . $prefix . '1hasclosed" value="0" ' . ($loan->cloture == '0' ? 'checked' : '') . '>';
$html .= '<label class="form-check-label" for="ID' . $index . $prefix . '1hasclosed">Non</label>';
$html .= '</div>';
$html .= '<div class="form-check form-check-inline">';
$html .= '<input name="' . $prefix . 'currentloans[' . $index . '][hasclosed]" type="radio" class="form-check-input" id="ID' . $index . $prefix . '2hasclosed" value="1" ' . ($loan->cloture == '1' ? 'checked' : '') . '>';
$html .= '<label class="form-check-label" for="ID' . $index . $prefix . '2hasclosed">Oui</label>';
$html .= '</div>';
$html .= '</div>';
$html .= '<input type="hidden" class="wpcf-currentloan--block--kuid" name="' . $prefix . 'currentloans[' . $index . '][kuid]" value="' . $loan->idautre_credit . '">';
$html .= '</div>';
$html .= '</div>';
$index++;
}
return $html;
}
/**
* Récupère les autres revenus d'un emprunteur ou co-emprunteur
* @param object $borrower Les données de l'emprunteur ou co-emprunteur
* @return array Array avec les autres revenus
*/
public function getAutresRevenus($borrower) {
if (!is_object($borrower) || !isset($borrower->idemprunteur)) {
return [];
}
$autresRevenus = [];
// Récupérer les autres revenus depuis la table cdf_Emprunteur
$query = $this->wpdb->prepare(
"SELECT
cheque_repas,
revenus_locatifs,
chomage,
autre_revenu_type,
autre_revenu_montant
FROM cdf_Emprunteur
WHERE idemprunteur = %d",
$borrower->idemprunteur
);
$result = $this->wpdb->get_row($query);
if ($result) {
// Construire un array avec les autres revenus
if (!empty($result->cheque_repas)) {
$autresRevenus[] = [
'type' => 'Chèque repas',
'montant' => $result->cheque_repas,
'description' => 'Chèque repas mensuel'
];
}
if (!empty($result->revenus_locatifs)) {
$autresRevenus[] = [
'type' => 'Revenus locatifs',
'montant' => $result->revenus_locatifs,
'description' => 'Revenus locatifs mensuels'
];
}
if (!empty($result->chomage)) {
$autresRevenus[] = [
'type' => 'Chômage',
'montant' => $result->chomage,
'description' => 'Allocation de chômage mensuelle'
];
}
if (!empty($result->autre_revenu_montant) && !empty($result->autre_revenu_type)) {
$autresRevenus[] = [
'type' => 'Autre revenu',
'montant' => $result->autre_revenu_montant,
'description' => $result->autre_revenu_type
];
}
}
return $autresRevenus;
}
/**
* @param $data
* @return void
*/
protected function update_emprunteur($data, $currentCredit)
{
// Vérifier si l'email de l'emprunteur contient @example.com
if(isset($data['email']) && strpos($data['email'], '@example.com') !== false) {
return false; // Rejeter la demande si l'adresse email contient @example.com
}
$borrower = $this->getBorrower($currentCredit);
$updateData = [];
foreach ($this->borrowerFieldMap as $formField => $dbField) {
/* echo '<pre>';
print_r($data);
echo '</pre>'; */
// Protection générale : ne mettre à jour que les champs présents dans les données POST
if (!isset($data[$formField])) {
continue; // On saute ce champ s'il n'est pas présent dans les données
}
// Si le champ est un champ de date, on le formate correctement
if (in_array($formField, $this->dateFields)) {
if (!empty($data[$formField])) {
$date = \DateTime::createFromFormat('d/m/Y', $data[$formField]);
if ($date) {
$updateData[$dbField] = $date->format('Y-m-d');
} else {
$updateData[$dbField] = null; // Si la date n'est pas valide, on met à null
}
} else {
$updateData[$dbField] = null; // Si le champ est vide, on met à null
}
} else {
// Pour les champs non-date, on utilise directement la valeur
$updateData[$dbField] = $data[$formField];
}
}
/* echo '<pre>';
print_r($updateData);
echo '</pre>';
die(); */
$this->wpdb->update('cdf_Emprunteur', $updateData, array('idemprunteur' => $borrower->idemprunteur));
}
/**
* Met à jour les données du co-emprunteur
* @param $data
* @param $currentCredit
* @return void
*/
protected function update_co_emprunteur($data, $currentCredit)
{
// Vérifier si l'email du co-emprunteur contient @example.com
if(isset($data['coemail']) && strpos($data['coemail'], '@example.com') !== false) {
return false; // Rejeter la demande si l'adresse email du co-emprunteur contient @example.com
}
$coBorrower = $this->getCoBorrower($currentCredit);
if (!is_object($coBorrower)) {
return; // Pas de co-emprunteur, on sort
}
$updateData = [];
foreach ($this->borrowerFieldMap as $formField => $dbField) {
// Vérifier si c'est un champ co-emprunteur (préfixe 'co')
if (strpos($formField, 'co') === 0) {
// Protection générale : ne mettre à jour que les champs présents dans les données POST
if (!isset($data[$formField])) {
continue; // On saute ce champ s'il n'est pas présent dans les données
}
// Si le champ est un champ de date, on le formate correctement
if (in_array($formField, $this->dateFields)) {
if (!empty($data[$formField])) {
$date = \DateTime::createFromFormat('d/m/Y', $data[$formField]);
if ($date) {
$updateData[$dbField] = $date->format('Y-m-d');
} else {
$updateData[$dbField] = null; // Si la date n'est pas valide, on met à null
}
} else {
$updateData[$dbField] = null; // Si le champ est vide, on met à null
}
} else {
// Pour les champs non-date, on utilise directement la valeur
$updateData[$dbField] = $data[$formField];
}
}
}
if (!empty($updateData)) {
$this->wpdb->update('cdf_Emprunteur', $updateData, array('idemprunteur' => $coBorrower->idemprunteur));
}
}
public function is_credit_pat($currentCredit) {
$type_credit = $currentCredit->type_credit;
if(array_key_exists($type_credit, $this->one_step_credit_types)) {
return true;
}
return false;
}
public function is_credit_auto($currentCredit) {
$type_credit = $currentCredit->type_credit;
if(in_array($type_credit, $this->creditAutos)) {
return true;
}
return false;
}
public function hasCoBorrower($currentCredit) {
$borrower = $this->getBorrower($currentCredit);
$coBorrower = $this->getCoBorrower($currentCredit);
if($coBorrower) {
return true;
}
return false;
}
public function hasOtherIncome($borrower) {
$cheque_repas = $this->getFieldValue('cheque_repas', $borrower);
$revenus_locatifs = $this->getFieldValue('revenus_locatifs', $borrower);
$chomage = $this->getFieldValue('chomage', $borrower);
$autre_revenu_montant = $this->getFieldValue('autre_revenu_montant', $borrower);
$autre_revenu_type = $this->getFieldValue('autre_revenu_type', $borrower);
if($cheque_repas || $revenus_locatifs || $chomage || $autre_revenu_montant || $autre_revenu_type) {
return true;
}
return false;
}
public function estFicheBanqueNational($borrower) {
$fichage_status = $borrower->fichage_status;
if(!empty($fichage_status)) {
return true;
}
return false;
}
public function is_locataire($borrower) {
$habitation_type = $borrower->habitation_type;
if(empty($habitation_type)) {
return false;
}
if($habitation_type == 'locataire') {
return true;
}
return false;
}
/**
* Génère des liens HTML pour les documents uploadés
* @param string $token Le token du crédit
* @param bool $include_metadata Inclure les métadonnées (taille, date) dans l'affichage
* @param string $css_class Classe CSS pour le conteneur des liens
* @return string HTML des liens vers les documents uploadés
*/
public function generateUploadedFilesLinksHTML($token, $include_metadata = false, $css_class = 'uploaded-documents') {
$html = '';
if ($include_metadata) {
$files = $this->getUploadedFilesWithMetadata($token);
} else {
$files = $this->getUploadedFiles($token);
}
if (empty($files)) {
return '<p class="' . esc_attr($css_class) . '">Aucun document uploadé</p>';
}
$html .= '<div class="' . esc_attr($css_class) . '">';
$html .= '<h4>Documents uploadés :</h4>';
$html .= '<ul style="list-style: none; padding: 0; margin: 0;">';
foreach ($files as $file) {
if ($include_metadata && is_array($file)) {
// Fichier avec métadonnées
if (isset($file['warning'])) {
$html .= '<li style="color: #ff6b6b; margin-bottom: 8px;">⚠️ ' . esc_html($file['warning']) . '</li>';
continue;
}
$file_url = $file['url'];
$filename = $file['filename'];
$doc_type = $file['doc_type'];
$size_formatted = $file['size_formatted'];
$modified_date = date('d/m/Y H:i', $file['modified_date']);
// Traduire le type de document
$doc_type_labels = [
'fiche_paie' => 'Fiche de paie',
'fiche_paie_co' => 'Fiche de paie (co-emprunteur)',
'avis_imposition' => 'Avis d\'imposition',
'avis_imposition_co' => 'Avis d\'imposition (co-emprunteur)',
'carte_identite' => 'Carte d\'identité',
'carte_identite_co' => 'Carte d\'identité (co-emprunteur)',
'taxe_fonciere' => 'Taxe foncière',
'taxe_fonciere_co' => 'Taxe foncière (co-emprunteur)',
'quittance_loyer' => 'Quittance de loyer',
'quittance_loyer_co' => 'Quittance de loyer (co-emprunteur)',
'compromis_vente' => 'Compromis de vente',
'compromis_vente_co' => 'Compromis de vente (co-emprunteur)'
];
$doc_label = isset($doc_type_labels[$doc_type]) ? $doc_type_labels[$doc_type] : ucfirst(str_replace('_', ' ', $doc_type));
$html .= '<li style="margin-bottom: 12px; padding: 8px; border: 1px solid #e0e0e0; border-radius: 4px; background: #f9f9f9;">';
$html .= '<a href="' . esc_url($file_url) . '" target="_blank" style="color: #001954; text-decoration: none; font-weight: bold;">';
$html .= '📄 ' . esc_html($doc_label);
$html .= '</a>';
$html .= '<div style="font-size: 12px; color: #666; margin-top: 4px;">';
$html .= 'Taille: ' . esc_html($size_formatted) . ' | Modifié le: ' . esc_html($modified_date);
$html .= '</div>';
$html .= '</li>';
} else {
// Fichier simple (URL seulement)
if (is_string($file) && strpos($file, 'WARNING:') === 0) {
$html .= '<li style="color: #ff6b6b; margin-bottom: 8px;">⚠️ ' . esc_html($file) . '</li>';
continue;
}
$file_url = $file;
$filename = basename($file_url);
$html .= '<li style="margin-bottom: 8px;">';
$html .= '<a href="' . esc_url($file_url) . '" target="_blank" style="color: #001954; text-decoration: none;">';
$html .= '📄 ' . esc_html($filename);
$html .= '</a>';
$html .= '</li>';
}
}
$html .= '</ul>';
$html .= '</div>';
return $html;
}
/**
* Génère des liens HTML simples pour les documents uploadés (version simplifiée)
* @param string $token Le token du crédit
* @param string $css_class Classe CSS pour le conteneur des liens
* @return string HTML des liens vers les documents uploadés
*/
public function generateSimpleUploadedFilesLinksHTML($token, $css_class = 'uploaded-documents-simple') {
$files = $this->getUploadedFiles($token);
if (empty($files)) {
return '';
}
$html = '<div class="' . esc_attr($css_class) . '">';
$html .= '<p><strong>Documents joints :</strong></p>';
$html .= '<ul style="list-style: disc; margin-left: 20px;">';
foreach ($files as $file) {
if (is_string($file) && strpos($file, 'WARNING:') === 0) {
$html .= '<li style="color: #ff6b6b;">⚠️ ' . esc_html($file) . '</li>';
continue;
}
$file_url = $file;
$filename = basename($file_url);
$html .= '<li>';
$html .= '<a href="' . esc_url($file_url) . '" target="_blank">';
$html .= esc_html($filename);
$html .= '</a>';
$html .= '</li>';
}
$html .= '</ul>';
$html .= '</div>';
return $html;
}
/**
* Récupère les limites basse et haute pour un type de crédit depuis ACF
*/
public function get_credit_limits($credit_types) {
$credit_type_map = array(
'but_immo' => 'credit_travaux__renovation__energie',
'fin_neuve' => 'financement_vehicule_neuf',
'fin_occ_m3a' => 'financement_vehicule_doccasion_moins_de_3_ans',
'fin_occ_p3a' => 'financement_vehicule_doccasion_plus_de_3_ans',
'mobil_carav' => 'financement_mobilhome_et_caravane_de_moins_de_3_ans',
'reno_energie' => 'credit_travaux__renovation__energie',
'regroup_cred' => 'regroupement_de_credit__rachats_de_credits',
'frais_notaire' => 'financement_frais_de_notaire',
'pat' => 'pret_personnel__tous_motifs__achats_divers',
'ph' => 'credit_hypothecaire_social',
'am' => 'credit_hypothecaire_classique',
'amr' => 'achat_maison_de_rapport',
'cied' => 'independants_et_entreprises_en_difficultes',
'cdp' => 'credit_pont'
);
$acf_field_name = isset($credit_type_map[$credit_types]) ? $credit_type_map[$credit_types] : null;
if (!$acf_field_name || !function_exists('get_field')) {
return [
'limite_basse' => 0,
'limite_haute' => PHP_INT_MAX
];
}
$credit_data = get_field($acf_field_name, 'option');
if (!$credit_data || !is_array($credit_data)) {
return [
'limite_basse' => 0,
'limite_haute' => PHP_INT_MAX
];
}
return [
'limite_basse' => isset($credit_data['limite_basse']) ? (int)$credit_data['limite_basse'] : 0,
'limite_haute' => isset($credit_data['limite_haute']) ? (int)$credit_data['limite_haute'] : PHP_INT_MAX
];
}
/**
* get exemple_infod_from acf
*/
public function get_exemples_infos($credit_types) {
$credit_type_map = array(
'but_immo' => 'credit_travaux__renovation__energie',
'fin_neuve' => 'financement_vehicule_neuf',
'fin_occ_m3a' => 'financement_vehicule_doccasion_moins_de_3_ans',
'fin_occ_p3a' => 'financement_vehicule_doccasion_plus_de_3_ans',
'mobil_carav' => 'financement_mobilhome_et_caravane_de_moins_de_3_ans',
'reno_energie' => 'credit_travaux__renovation__energie',
'regroup_cred' => 'regroupement_de_credit__rachats_de_credits',
'frais_notaire' => 'financement_frais_de_notaire',
'pat' => 'pret_personnel__tous_motifs__achats_divers',
'ph' => 'credit_hypothecaire_social',
'am' => 'credit_hypothecaire_classique',
'amr' => 'achat_maison_de_rapport',
'cdp' => 'credit_pont',
'cied' => 'independants_et_entreprises_en_difficultes',
'reno_energie' => 'credit_travaux__renovation__energie',
'but_immo_hypo' => 'credit_hypothecaire_classique',
);
$credit = $credit_type_map[$credit_types];
$exemple_info = get_field($credit, 'option');
$exemple_info = $exemple_info['exemple_et_infos'];
if(empty($exemple_info)) {
return false;
}
return $exemple_info;
}
/**
* check if is webdev user
*/
public function is_webdev_user() {
$user = wp_get_current_user();
$user_id = $user->ID;
if($user_id == 1) {
return true;
}
return false;
}
/**
* Sauvegarde dans cdf_Credits_listing
* @param object $currentCredit Le crédit actuel
* @return void
*/
public function save_to_credits_listing($currentCredit) {
// Récupérer les données complètes du crédit
$credit_data = $this->wpdb->get_row($this->wpdb->prepare(
"SELECT * FROM cdf_Credit WHERE idCredit = %d",
$currentCredit->idCredit
));
$code_type_credit = $this->is_credit_pat($currentCredit) ? 'pat' : 'ph';
// Récupérer les données de l'emprunteur
$emprunteur_data = $this->wpdb->get_row($this->wpdb->prepare(
"SELECT * FROM cdf_Emprunteur WHERE FK_demande_creditdirect = %d",
$currentCredit->idCredit
));
// Récupérer les autres crédits de l'emprunteur
$other_credits_ids = '';
if ($emprunteur_data) {
$borrower = $this->getBorrower($currentCredit);
if ($borrower && isset($borrower->other_credits) && is_array($borrower->other_credits)) {
$ids = array();
foreach ($borrower->other_credits as $other_credit) {
if (isset($other_credit->idautre_credit)) {
$ids[] = $other_credit->idautre_credit;
}
}
$other_credits_ids = implode(',', $ids);
}
}
// Vérifier si l'enregistrement existe déjà
$existing = $this->wpdb->get_row($this->wpdb->prepare(
"SELECT id FROM cdf_Credits_listing WHERE credit_id = %d",
$currentCredit->idCredit
));
$credit_label = $this->getCreditLabel($credit_data->sel_credit);
$listing_data = array(
'credit_id' => $currentCredit->idCredit,
'emprunteur_id' => $emprunteur_data ? $emprunteur_data->idemprunteur : 0,
'autre_credit_id' => $other_credits_ids,
'credit_auto_id' => $credit_data ? $credit_data->FK_credit_auto : 0,
'credit_hypotecaire_id' => $credit_data ? $credit_data->FK_credit_hypothecaire : 0,
'title' => $credit_label,
'credit_code_select' => $credit_data->sel_credit,
'code_credit' => $credit_data->type_credit,
'type_credit' => $code_type_credit,
'nom' => $emprunteur_data ? $emprunteur_data->nom : '',
'prenom' => $emprunteur_data ? $emprunteur_data->prenom : '',
'adresse' => $emprunteur_data ? $emprunteur_data->adresse : '',
'localite' => $emprunteur_data ? $emprunteur_data->localite : '',
'email' => $emprunteur_data ? $emprunteur_data->email : '',
'telephone' => $emprunteur_data ? $emprunteur_data->telephone : '',
'gsm' => $emprunteur_data ? $emprunteur_data->telephone : '', // Utiliser telephone comme gsm si pas de gsm séparé
'societe_credit' => '',
'montant' => $credit_data ? floatval($credit_data->capital) : 0,
'date' => $credit_data ? $credit_data->create_date : date('Y-m-d'),
'date_signature' => '', // Par défaut non signé
'numero_dossier' => '',
'code' => '',
'remarque' => $credit_data ? $credit_data->commentaire : '',
'status' => 0,
);
if ($existing) {
// Mettre à jour l'enregistrement existant
$this->wpdb->update(
'cdf_Credits_listing',
$listing_data,
array('id' => $existing->id),
array(
'%d', '%d', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s', '%s', '%f', '%s', '%d', '%s', '%s', '%s'
)
);
} else {
// Créer un nouvel enregistrement
$this->wpdb->insert(
'cdf_Credits_listing',
$listing_data,
array(
'%d', '%d', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s', '%s', '%f', '%s', '%d', '%s', '%s', '%s'
)
);
}
}
}