<?php

function isDuplicateLead($phone)
{
    $file = 'leads.txt';

    if (!file_exists($file)) {
        file_put_contents($file, '');
    }

    $leads = file_get_contents($file);
    $escapedPhone = preg_quote($phone, '/');
    $phonePattern = '/' . $escapedPhone . "\n/";

    if (preg_match($phonePattern, $leads)) {
        return true;
    } else {
        file_put_contents($file, $phone . "\n", FILE_APPEND);
        return false;
    }
}

function cleanPhoneNumber($phoneNumber)
{
    return preg_replace('/[^0-9]/', '', $phoneNumber);
}

$cleanedPhone = cleanPhoneNumber($_POST['phone']);

if (isDuplicateLead($cleanedPhone)) {
    header('Location: error.php?name=' . urlencode($_POST['name']) . '&phone=' . urlencode($_POST['phone']));
    exit;
}

function getApiKeyByTrafficSource($sub9)
{
    $sub9 = strtolower(trim($sub9));

    if (stripos($sub9, 'facebook') !== false || stripos($sub9, 'fb') !== false) {
        return 'OwK-9mieB5Oq6XPuHo7glL8RrhgFaXcr';
    }

    if (stripos($sub9, 'google') !== false || stripos($sub9, 'googleads') !== false) {
        return 'qfRwpn-2-VwGN088qVQiV6yfeZncLx1F';
    }

    return 'OwK-9mieB5Oq6XPuHo7glL8RrhgFaXcr';
}


$url = 'https://api.arbitpro.ru/lead/add';

$data = [
    'api_key' => '3hZfVLJAJNg9iT7k0Kbo2PggOpJOYdeF',
    'fio' => $_POST['name'],
    'phone' => $_POST['phone'],
    'hash' => $_POST['flow'],
    'ip' => $_SERVER['REMOTE_ADDR'],
    'sub1' => $_POST['sub1'] ?? '',
    'sub2' => $_POST['sub2'] ?? '',
    'sub3' => $_POST['sub3'] ?? '',
    'sub4' => $_POST['sub4'] ?? '',
    'sub5' => $_POST['sub5'] ?? '',
    'ewid' => $_POST['ewid'] ?? '',
];

$jsonData = json_encode($data);

$process = curl_init();
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($process, CURLOPT_TIMEOUT, 20);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($process, CURLOPT_POST, true);
curl_setopt($process, CURLOPT_POSTFIELDS, $jsonData); // Устанавливаем JSON-данные
curl_setopt($process, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);

$return = curl_exec($process);

file_put_contents('serv.txt', date('Y-m-d H:i:s') . " - Server Response: \n" . $return . "\n\n", FILE_APPEND);

curl_close($process);

$arr = json_decode($return, true);

if ($arr['success']) {
    header('Location: success.php?name=' . urlencode($_POST['name']) . '&phone=' . urlencode($_POST['phone']));
    exit;
} else {
    header('Location: error.php?name=' . urlencode($_POST['name']) . '&phone=' . urlencode($_POST['phone']) . '&error=' . $arr['message']);
    exit;
}
?>
