<?php
// ACTIVE LES ERREURS POUR LE DEBUG
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// RÉCUPÈRE LES DONNÉES ENTRANTES
$data = json_decode(file_get_contents("php://input"), true);

// VÉRIFIE LE CHAMP EMAIL
if (!isset($data['email'])) {
    http_response_code(400);
    echo json_encode(["error" => "Le champ email est requis."]);
    exit;
}

// PARAMÈTRES À MODIFIER
$publicKey = '2_16mwn0fbd928gsko840ssw8c0sg4wsg88wcggsogg4kkg0kcsk';
$secretKey = '53i34lg2ezwog8wg0400gswcwckkskgowsok8c0g4o4sgo4cwk';
$mauticUrl = 'https://mautic.immobilier-company.com';

// INFOS DU CONTACT À ENVOYER
$contact = [
    'email' => $data['email'],
    'firstname' => $data['firstname'] ?? '',
];

// APPEL DE L’API DE MAUTIC (endpoint /contacts/new)
$ch = curl_init("$mauticUrl/api/contacts/new");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Basic " . base64_encode("$publicKey:$secretKey"),
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($contact));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// RÉPONSE
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

http_response_code($httpCode);
echo $response;
