<?php
declare(strict_types=1);

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

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../lib/db.php';

function out(string $status, string $result, string $data): void {
  echo json_encode(['status'=>$status,'result'=>$result,'data'=>$data], JSON_UNESCAPED_UNICODE);
  exit;
}

function client_ip(): string {
  foreach (['HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','HTTP_CLIENT_IP','REMOTE_ADDR'] as $k) {
    if (!empty($_SERVER[$k])) {
      $ip = (string)$_SERVER[$k];
      if (str_contains($ip, ',')) $ip = trim(explode(',', $ip)[0]);
      return $ip;
    }
  }
  return '0.0.0.0';
}

$cfg = app_config();

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  out('error', 'e', 'POST bekleniyor');
}

$token = (string)($_GET['token'] ?? '');
$expectedToken = (string)($cfg['netgsm_webhook_token'] ?? '');
$tokenOk = ($expectedToken !== '' && hash_equals($expectedToken, $token));

$ip = client_ip();

// Whitelist açıksa IP dışındaysa token’u geçersiz say
$wl = $cfg['netgsm_ip_whitelist'] ?? [];
if (is_array($wl) && count($wl) > 0 && !in_array($ip, $wl, true)) {
  $tokenOk = false;
}

$rawBody = (string)file_get_contents('php://input');
$contentType = (string)($_SERVER['CONTENT_TYPE'] ?? '');
$httpMethod  = (string)($_SERVER['REQUEST_METHOD'] ?? 'POST');

$data = $_POST;

// JSON parse ( {..} veya [ {..} ] )
if ((empty($data) || !is_array($data)) && str_contains(strtolower($contentType), 'application/json')) {
  $j = json_decode($rawBody, true);
  if (is_array($j)) {
    if (function_exists('array_is_list') && array_is_list($j)) {
      $data = $j[0] ?? [];
    } else {
      // PHP<8.1 için basit liste kontrolü
      $isList = array_keys($j) === range(0, count($j)-1);
      $data = $isList ? ($j[0] ?? []) : $j;
    }
  }
}

$arayan_no   = trim((string)($data['arayan_no']   ?? ''));
$aranan_no   = trim((string)($data['aranan_no']   ?? ''));
$santral_no  = trim((string)($data['santral_no']  ?? ''));
$arama_id    = trim((string)($data['arama_id']    ?? ''));
$tus_bilgisi = trim((string)($data['tus_bilgisi'] ?? ''));

try {
  $pdo = db();

  // log her zaman yaz
  $st = $pdo->prepare("
    INSERT INTO webhook_logs (arama_id, ip, token_ok, http_method, content_type, raw_body)
    VALUES (?, ?, ?, ?, ?, ?)
  ");
  $st->execute([
    $arama_id !== '' ? $arama_id : null,
    $ip,
    $tokenOk ? 1 : 0,
    $httpMethod,
    $contentType,
    $rawBody,
  ]);

  if (!$tokenOk) out('error', 'e', 'Token/IP hatalı');
  if ($arama_id === '') out('error', 'e', 'arama_id boş gelemez');

  $callStatus = ($tus_bilgisi !== '') ? 'routed' : 'started';

  $st2 = $pdo->prepare("
    INSERT INTO calls (arama_id, arayan_no, aranan_no, santral_no, status, last_tus)
    VALUES (?, ?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
      arayan_no  = VALUES(arayan_no),
      aranan_no  = VALUES(aranan_no),
      santral_no = VALUES(santral_no),
      status     = IF(NULLIF(VALUES(last_tus),'') IS NULL, status, 'routed'),
      last_tus   = COALESCE(NULLIF(VALUES(last_tus),''), last_tus),
      updated_at = CURRENT_TIMESTAMP
  ");
  $st2->execute([
    $arama_id,
    $arayan_no !== '' ? $arayan_no : null,
    $aranan_no !== '' ? $aranan_no : null,
    $santral_no !== '' ? $santral_no : null,
    $callStatus,
    $tus_bilgisi !== '' ? $tus_bilgisi : null,
  ]);

  if ($tus_bilgisi !== '') {
    $st3 = $pdo->prepare("
      INSERT INTO dtmf_events (arama_id, arayan_no, tus_bilgisi, step, raw_payload)
      VALUES (?, ?, ?, 'menu1', ?)
    ");
    $st3->execute([
      $arama_id,
      $arayan_no !== '' ? $arayan_no : null,
      $tus_bilgisi,
      json_encode($data, JSON_UNESCAPED_UNICODE),
    ]);
  }

  out('success', '1', 'OK');

} catch (Throwable $e) {
  out('error', 'e', 'DB hata: ' . $e->getMessage());
}
