<?php
function send_bitrix() {

  define('CRM_HOST', '[name].bitrix24.ru'); // Ваш домен CRM системы
  define('CRM_PORT', '443'); // Порт сервера CRM. Установлен по умолчанию
  define('CRM_PATH', '/crm/configs/import/lead.php'); // Путь к компоненту lead.rest
  define('CRM_LOGIN', '[username]'); // Логин пользователя Вашей CRM по управлению лидами
  define('CRM_PASSWORD', '[password]'); // Пароль пользователя Вашей CRM по управлению лидами

  $your_name = $_POST['your_name'];
  $your_phone = $_POST['your_phone'];
  $your_email = $_POST['your_email'];

  $product = $_POST['product'];

  $_POST['is_install'] === 'true' ? $is_install = 'С монтажом' : $is_install = 'Без монтажа';
  $order_sum = $_POST['order_sum'];
  $qt_f6 = $_POST['f6'];
  $delivery = $_POST['delivery'];
  $payment = $_POST['payment'];
  $dealer_email = $_POST['dealer_email'];
  $_POST['dealer_email'] != '' ? $dealer = 'Заявка отправлена дилеру на ' . $_POST['dealer_email'] : $dealer = 'Заявка дилеру НЕ ОТПРАВЛЕНА (нет адреса)';
  $userLocation = $_COOKIE['geolocationCountry'] . ', ' . $_COOKIE['geolocationRegion'] . ', ' . $_COOKIE['geolocationCity'];
  // $acceptance = $_POST['acceptance'];
  $comments = $product . '<br>' . $is_install . '<br>Сумма заказа: ' . $order_sum . '<br>Фильтры F6: ' . $qt_f6 . '<br><br>Доставка: ' . $delivery . '<br>Оплата: ' . $payment . '<br><br>' . $dealer . '<br><br>Город, определённый автоматически: ' . $userLocation;

  $post_title = $_POST['post_title'];
  $post_url = $_POST['post_url'];
  $sourceDescription = $post_title . ' (' . $post_url . ')';

  $utmSource = $_COOKIE['utm_source'];
  $utmMedium = $_COOKIE['utm_medium'];
  $utmCampaign = $_COOKIE['utm_campaign'];
  $utmContent = $_COOKIE['utm_content'];
  $utmTerm = $_COOKIE['utm_term'];

  $postData = array(
    'TITLE' => 'Тестовая заявка с сайта',
    // 'ASSIGNED_BY_ID' => '',
    'NAME' => $your_name,
    'PHONE_WORK' => $your_phone,
    'EMAIL_WORK' => $your_email,
    'OPPORTUNITY' => $order_sum,
    'SOURCE_ID' => 'WEB',
    'SOURCE_DESCRIPTION' => $sourceDescription,
    'UTM' => 'Это UTM',
    'COMMENTS' => $comments
    // Товар можно ставить
  );

  if (defined('CRM_AUTH')) {
    $postData['AUTH'] = CRM_AUTH;
  } else {
    $postData['LOGIN'] = CRM_LOGIN;
    $postData['PASSWORD'] = CRM_PASSWORD;
  }

  $fp = fsockopen("ssl://".CRM_HOST, CRM_PORT, $errno, $errstr, 30);

  if ($fp) {
    $strPostData = '';
    foreach ($postData as $key => $value)
        $strPostData .= ($strPostData == '' ? '' : '&').$key.'='.urlencode($value);
    $str = "POST ".CRM_PATH." HTTP/1.0\r\n";
    $str .= "Host: ".CRM_HOST."\r\n";
    $str .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $str .= "Content-Length: ".strlen($strPostData)."\r\n";
    $str .= "Connection: close\r\n\r\n";
    $str .= $strPostData;
    fwrite($fp, $str);
    $result = '';
    while (!feof($fp))
    {
        $result .= fgets($fp, 128);
    }
    fclose($fp);
    $response = explode("\r\n\r\n", $result);
    $output = '<pre>'.print_r($response[1], 1).'</pre>';
  } else {
    echo 'Connection Failed! '.$errstr.' ('.$errno.')';
  }
}

add_action( 'wp_ajax_send_bitrix', 'send_bitrix' );
add_action( 'wp_ajax_nopriv_send_bitrix', 'send_bitrix' );