<?php
// --- Configuration ---
$baseUrl = 'https://mautic.immobilier-company.com';
$username = 'api@immobilier-company.com';
$password = 'rGKh$h#$$XBm6TF@';

// --- Récupération des données reçues depuis ClickFunnels ---
$data = $_POST; // ou file_get_contents("php://input") si ClickFunnels envoie en raw JSON

// --- Exemple de correspondance ---
$email = $data['email'] ?? null;
$firstname = $data['firstname'] ?? null;
$lastname = $data['lastname'] ?? null;

if (!$email) {
    http_response_code(400);
    echo json_encode(['error' => 'Email is required']);
    exit;
}

// --- Préparation des données à envoyer à Mautic ---
$mauticData = [
    'email' => $email,
    'firstname' => $firstname,
    'lastname' => $lastname,
];

// --- Requête POST vers Mautic pour créer ou mettre à jour le contact ---
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseUrl . '/api/contacts/new');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($mauticData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

// --- Affichage du résultat ---
header('Content-Type: application/json');
if ($error) {
    echo json_encode(['curl_error' => $error]);
} elseif ($httpCode >= 400) {
    echo json_encode(['http_code' => $httpCode, 'response' => $response]);
} else {
    echo $response;
}
