<?php

// ini_set('error_reporting', E_ALL);
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);

const CRM_DOMAIN = 'api.13partners.net';
const LANDING_NAME = 'Q-Kynvestium';

$subid = $_POST['click_id'] ?? '';
$pixel = $_POST['pixel'] ?? '';


sendLeadToCRM($subid, $pixel);

function sendLeadToCRM($subid, $pixel)
{

  // $comment = $_POST['answer'];

  

  $data = array(
    'phone' => preg_replace('/[^0-9]/', '',  $_POST['phone']),
    'full_name' => $_POST['l_name'] . ' ' . $_POST['f_name'],
    'email' => $_POST['email'],
    'ip' => $_POST['ip'],
    'landing' => $_SERVER['HTTP_REFERER'],
    'landing_name' => LANDING_NAME,
    'source' => 'Callback_web',
    'country' => $_POST['country2'],
    'lang' => "en",
    'keitaro_id' => $subid,
    'user_id' => 917,
    // 'description' => $comment
  );

  // if(!isset($_POST['check_user'])){
  //   $data['is_error'] = 1;
  //   $data['error'] = 'Fake Lead';
  // }

  if (isset($_POST['user_id']) && $_POST['user_id']) {
    $data['user_id'] = $_POST['user_id'];
  }

  if (isset($_POST['subid']) && $_POST['subid']) {
      $data['keitaro_id'] =  $_POST['subid'];
  }
  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://' . CRM_DOMAIN . '/api/leads',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => http_build_query($data),
    CURLOPT_HTTPHEADER => array(
      'Accept: application/json',
    ),
  ));

  $response = curl_exec($curl);

  // print_r($response);
  curl_close($curl);

  $response = json_decode($response, true);




  // FOR DEBUG
  // file_put_contents('./logs.txt', print_r($response, true), FILE_APPEND | LOCK_EX);

  // var_dump($data);
  // var_dump($response);

  setcookie('cabinet', $response['link_auto_login'] ?? '', time() + 60 * 90);
  // // if($response[])
  // if(isset($response['status'])){
  //     header('location: ./thanks.php?status=success');
  // }else{
  // header('location: thanks.php?pixel=' . $pixel);

  // echo 'thanks.php?pixel='.$pixel;


  exit(json_encode('thanks.php?pixel=' . $pixel));
  // exit(json_encode('thanks.php?pixel='.$pixel));
  // }
}