<?php
// proxy.php – forwards form data to the affiliate API

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Collect form fields (same names as in your HTML)
$firstName  = isset($_POST['firstname']) ? trim($_POST['firstname']) : '';
$lastName   = isset($_POST['lastname']) ? trim($_POST['lastname']) : '';
$email      = isset($_POST['email']) ? trim($_POST['email']) : '';
$phone      = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$clickId    = isset($_POST['click_id']) ? trim($_POST['click_id']) : '';

// Basic validation
if (empty($firstName) || empty($lastName) || empty($email) || empty($phone)) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

// Build fullname
$fullname = $firstName . ' ' . $lastName;

// Format phone to E.164 if not already (you can improve this logic)
// Remove spaces and dashes
$phone = preg_replace('/[\s\-\(\)]/', '', $phone);
if (strpos($phone, '+') !== 0) {
    // Assume Belgian number
    if (strpos($phone, '31') === 0) {
        $phone = '+' . $phone;
    } elseif (strpos($phone, '0') === 0) {
        $phone = '+31' . substr($phone, 1);
    } else {
        $phone = '+31' . $phone;
    }
}

// Prepare the payload for the external API
$payload = [
    'leads' => [
        [
            'email'        => $email,
            'phone'        => $phone,
            'firstname'    => $firstName,
            'lastname'     => $lastName,
            'fullname'     => $fullname,
            'country'      => 'Netherlands',
            'utm_campaign' => 'NL16 - ConflictoplossingInTeamsProNow.click',   // 👈 CHANGE THIS to your campaign
            'comment'      => '',
            'info'         => '',
            'click_id'     => $clickId,
            'trafficSource'=> 'Google' 
        ]
    ]
];

// External API endpoint
$apiUrl = 'https://api.mentemai.com/api/affiliates/leads';
$bearerToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZmZpbGlhdGVfaWQiOiIxNyIsImNyZWF0ZWQiOjE3Nzg3NjQ3NzIsImV4cGlyYXRpb24iOjAsImlhdCI6MTc3ODc2NDc3Mn0.3Ofn2ltf7VK3t06R0h-ro0H-dCFFU01fw5H9aSUGhUk';

// Init cURL
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $bearerToken,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

// Execute and get response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Return the external API response to the browser
http_response_code($httpCode);
header('Content-Type: application/json');
echo $response;