
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);



header('Content-Type: application/json; charset=utf-8');


// =====================
// SIMPLE LOCAL LOGGER
// =====================
define('LOG_FILE','genesys_log.txt');

function writeLog(array $data): void {
    $line = json_encode([
        'datetime' => date('Y-m-d H:i:s'),
        'data' => $data
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    file_put_contents(LOG_FILE, $line . PHP_EOL, FILE_APPEND | LOCK_EX);
}



/**
 * Genesys Cloud (mypurecloud.de) - Generate Token + Add Contacts
 */

// =====================
// CONFIG
// =====================
$cfg = [
  'token_url' => 'https://login.mypurecloud.de/oauth/token',
  'api_base'  => 'https://api.mypurecloud.de',

  // ✅ Use your exact Basic header value from Postman (DO NOT re-encode)
  'basic_auth' => 'Basic Y2Q1MTJmNTktYmZmMS00YzU5LWI0OGMtY2JjZDUwYTIzMGI3OlpDeXNvV3BNSldPVy0xbm92aDhia29udkJocTNwNDJmOGt2QnhybVJpUjA=',

  'contact_list_id' => '91674076-ed93-46d9-9f1e-dc6cdc12d301',
];

// =====================
// HTTP helper
// =====================
function httpRequest(string $url, string $method, array $headers = [], ?string $body = null, int $timeout = 30): array {
  $ch = curl_init($url);

  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST  => $method,
    CURLOPT_HTTPHEADER     => $headers,
    CURLOPT_TIMEOUT        => $timeout,
  ]);

  if ($body !== null) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  }

  $respBody = curl_exec($ch);
  $err      = curl_error($ch);
  $status   = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);

  curl_close($ch);

  if ($respBody === false) {
    return ['ok' => false, 'status' => $status ?: 0, 'error' => $err ?: 'cURL error', 'body' => null];
  }

  return ['ok' => ($status >= 200 && $status < 300), 'status' => $status, 'error' => null, 'body' => $respBody];
}

// =====================
// 1) Generate Token
// =====================
function generateToken(array $cfg): array {

  $headers = [
    'Authorization: ' . $cfg['basic_auth'],
    'Content-Type: application/x-www-form-urlencoded',
    'Accept: application/json',
  ];

  $body = http_build_query(['grant_type' => 'client_credentials']);

  $res = httpRequest($cfg['token_url'], 'POST', $headers, $body);

  if (!$res['ok']) {
    return ['ok' => false, 'status' => $res['status'], 'error' => 'Token request failed', 'raw' => $res['body']];
  }

  $json = json_decode($res['body'], true);
  if (!is_array($json) || empty($json['access_token'])) {
    return ['ok' => false, 'status' => $res['status'], 'error' => 'Invalid token response', 'raw' => $res['body']];
  }

  return [
    'ok' => true,
    'access_token' => $json['access_token'],
    'token_type'   => $json['token_type'] ?? null,
    'expires_in'   => $json['expires_in'] ?? null,
    'raw'          => $json
  ];
}

// =====================
// 2) Add Contacts
// =====================
function addContacts(array $cfg, string $accessToken, array $contactsPayload): array {
  $url = rtrim($cfg['api_base'], '/') . '/api/v2/outbound/contactlists/' . $cfg['contact_list_id'] . '/contacts';

  $headers = [
    'Authorization: Bearer ' . $accessToken,
    'Content-Type: application/json',
    'Accept: application/json',
  ];

  $body = json_encode($contactsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

  $res = httpRequest($url, 'POST', $headers, $body);

  if (!$res['ok']) {
    return ['ok' => false, 'status' => $res['status'], 'error' => 'Add contacts failed', 'raw' => $res['body']];
  }

  $json = json_decode($res['body'], true);
  return ['ok' => true, 'status' => $res['status'], 'response' => $json ?? $res['body']];
}


writeLog([
    'type' => 'incoming_post',
    'post' => $_POST
]);

// =====================
// Payload (same as yours)
// =====================
$payload = [
  [
    "data" => [
      "mobile" => $_POST['mobile'],
      "name" => $_POST['name'],
      "email" => $_POST['email'],
      "gender" => $_POST['gender'],
      "city" => $_POST['city'],
      "model" => $_POST['model'],
      "paymethod" => $_POST['paymethod'],
      "purtime" => $_POST['purtime'],
      "preftime" => $_POST['preftime'],
      "source" => $_POST['source'],
      "campaign" => $_POST['campaign'],
      "ref_id" => $_POST['ref_id'],
      "salary" => $_POST['salary'],
      "deduction" => $_POST['deduction'],
      "bank" => $_POST['bank'],
      "Language" => $_POST['lang'],
      "Request_date" => $_POST['request_date'],
      "Data1" => "NA",
      "Data2" => "NA",
      "Data3" => "NA",
      "Data4" => "NA",
      "Data5" => "NA"
    ],
    "callable" => true,
    "contactListId" => $cfg['contact_list_id'],
    "phoneNumberStatus" => [
      "mobile" => ["callable" => true]
    ]
  ]
];

// =====================
// Run
// =====================
$tok = generateToken($cfg);
if (!$tok['ok']) {
  http_response_code(500);
  echo json_encode(['step' => 'token', 'details' => $tok], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

$result = addContacts($cfg, $tok['access_token'], $payload);

echo json_encode([
  'token' => [
    'token_type' => $tok['token_type'],
    'expires_in' => $tok['expires_in'],
  ],
  'add_contacts' => $result
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);


writeLog([
    'type' => 'genesys_response',
    'response' => $result
]);