<?php

header('Content-Type: application/json');

// Get raw webhook body
$body = file_get_contents('php://input');

// Decode JSON
$data = json_decode($body, true);

// Log payloads for debugging
file_put_contents("lead_raw.txt", $body . PHP_EOL, FILE_APPEND);
file_put_contents("lead_decoded.txt", print_r($data, true) . PHP_EOL, FILE_APPEND);


// Validate JSON
if (!$data || !is_array($data)) {

    echo json_encode([
        "status" => "error",
        "message" => "Invalid or empty JSON payload"
    ]);

    exit;
}

// Extract form data
$formData = isset($data['data']) ? $data['data'] : [];
$submissions = isset($formData['submissions']) ? $formData['submissions'] : [];

// Convert submissions array into associative array
$fields = [];
$otherfields = [];

foreach ($submissions as $item) {

    if (!empty($item['label'])) {

        $label = trim($item['label']);
        $value = $item['value'] ?? '';

        // Convert arrays to comma separated string
        if (is_array($value)) {
            $value = implode(', ', $value);
        }

        $value = trim($value);

        $fields[$label] = $value;
    }
}

// Map primary fields
$fname      = $fields['First name'] ?? '';
$lname      = $fields['Last name'] ?? '';
$email      = $fields['Email'] ?? '';
$phone      = $fields['Phone'] ?? '';
$adlugeId   = $fields['AdLuge'] ?? '';

// Assign remaining fields to otherfields
foreach ($fields as $label => $value) {

    if (
        $label != 'First name' &&
        $label != 'Last name' &&
        $label != 'Email' &&
        $label != 'Phone' &&
        $label != 'AdLuge'
    ) {

        $otherfields[$label] = $value;
        if($label == 'Anything else we should know?'){
            $comments= $value;
        }
    }
}

// Load ClientCenter / AdLuge API
require_once("clientcenter-api-library.php");

// Create lead
$lead = new clientcenter();

$lead->client_code = "33r7mxm355ic1r1";

$lead->fname = $fname;
$lead->lname = $lname;
$lead->email = $email;
$lead->phone = $phone;
$lead->comments = $comments;

$lead->tag = "Wix Form";
$lead->status = 1;

// Pass other fields
$lead->other_fields = json_encode($otherfields);

$lead->useragent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$lead->remote_ip = $_SERVER['REMOTE_ADDR'] ?? '';
$lead->referrer  = $_SERVER['HTTP_REFERER'] ?? '';
// Pass AdLuge visitor/session ID
if (!empty($adlugeId)) {
    $lead->visitor_tracking_Id = $adlugeId;
}


$lead->contact_date = date("Y-m-d H:i:s");

// Enable AdLuge tracking
$lead->send_to_adluge = true;

// Send lead
// $leadResponse = $lead->send();

die();

?>