<?php
// CONFIGURATION
$api_key = '2d818e598d37d1775a7e85012cea46b3c330e7fced4ccc90';
$nocrm_url = 'https://jjf-audit.nocrm.io/api/v2/leads';
$csvProjetDetecte = __DIR__ . '/webhook_output_projet_detecte.csv';
$csvAllAppels     = __DIR__ . '/webhook_output_all.csv';

$header = [
    'timestamp', 'ip', 'client_id', 'civilite', 'nom', 'prenom', 'societe', 'siret', 'adresse',
    'code_postal', 'ville', 'activite', 'fonction', 'tel_fixe', 'tel_portable', 'email',
    'etat_appel', 'duree', 'date_appel', 'teleoperateur', 'audio_url', 'commentaire'
];

// Initialisation CSV
foreach ([$csvProjetDetecte, $csvAllAppels] as $file) {
    if (!file_exists($file)) {
        $fp = fopen($file, 'w');
        fputcsv($fp, $header);
        fclose($fp);
    }
}

// RÉCEPTION DES DONNÉES
$rawData = file_get_contents('php://input');
$ip = $_SERVER['REMOTE_ADDR'];
$timestamp = date('Y-m-d H:i:s');
$data = json_decode($_POST['data'] ?? $rawData, true);

if (!$data) {
    error_log("[$timestamp] Erreur JSON: " . json_last_error_msg());
    exit;
}

$client = $data['Client'] ?? [];

foreach ($data['HistoriqueAppel'] ?? [] as $appel) {
    $row = [
        $timestamp,
        $ip,
        $client['ID'] ?? '',
        $client['Civilite'] ?? '',
        $client['Nom'] ?? '',
        $client['Prenom'] ?? '',
        $client['Societe'] ?? '',
        $client['Siret'] ?? '',
        $client['Adresse'] ?? '',
        $client['CodePostal'] ?? '',
        $client['Ville'] ?? '',
        $client['Activite'] ?? '',
        $client['Fonction'] ?? '',
        $client['TelephoneFixe'] ?? '',
        $client['TelephonePortable'] ?? '',
        $client['Mail'] ?? '',
        $appel['Etat'] ?? '',
        $appel['Duree'] ?? '',
        $appel['DateAppel'] ?? '',
        $appel['Teleoperateur']['Login'] ?? '',
        $appel['AudioUrl'] ?? '',
        $appel['Commentaire'] ?? '',
    ];

    // Sauvegarde CSV
    $fpAll = fopen($csvAllAppels, 'a'); fputcsv($fpAll, $row); fclose($fpAll);

    if (mb_strtolower($appel['Etat']) === 'projet détecté') {
        $fpProjet = fopen($csvProjetDetecte, 'a'); fputcsv($fpProjet, $row); fclose($fpProjet);

        // CRÉATION DU LEAD DANS NOCRM
        $fullName = trim(($client['Civilite'] ?? '') . ' ' . ($client['Nom'] ?? '') . ' ' . ($client['Prenom'] ?? ''));

        $leadData = [
            "title" => $client['Societe'] ?: "Projet détecté sans société",
            "description" => "Nom responsable: $fullName\n"
                           . "Téléphone: " . ($client['TelephoneFixe'] ?? '') . "\n"
                           . "E-mail: " . ($client['Mail'] ?? '') . "\n"
                           . "adresse: " . ($client['Adresse'] ?? '') . "\n"
                           . "ville: " . ($client['Ville'] ?? '') . "\n"
                           . "code postal: " . ($client['CodePostal'] ?? '') . "\n"
                           . "société: " . ($client['Societe'] ?? '') . "\n"
                           . "DATE DE CREATION: " . date('d/m/Y') . "\n"
                           . "installation: " . ($appel['Commentaire'] ?? '') . "\n"
                           . "Ordonance par jour: 20",
            "tags" => ["Projet détecté", "WEBHOOK"],
            "user_id" => 148292,
            "step_id" => 319093,
            "custom_fields" => [
                "545474" => $fullName,
                "545475" => $client['TelephoneFixe'] ?? $client['TelephonePortable'] ?? '',
                "545476" => $client['Mail'] ?? '',
                "665322" => $client['Adresse'] ?? '',
                "545674" => $client['Ville'] ?? '',
                "650788" => $client['CodePostal'] ?? '',
                "554006" => $client['Societe'] ?? '',
                "554045" => date('d/m/Y'),
                "554163" => $appel['Commentaire'] ?? '',
                "754576" => "20"
            ]
        ];

        // Envoi API
        $ch = curl_init($nocrm_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "X-API-KEY: $api_key",
            "Content-Type: application/json"
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($leadData));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // si SSL local

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

        // Log du résultat
        file_put_contents(__DIR__ . '/lead_created.log', "[$timestamp] HTTP $httpCode\n$response\n\n", FILE_APPEND);
    }
}
?>
