<?php
declare(strict_types=1);

ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
error_reporting(0);
while (ob_get_level() > 0) { @ob_end_clean(); }

require_once __DIR__ . '/../lib/db.php';
require_once __DIR__ . '/../lib/helpers.php';
require_once __DIR__ . '/../lib/consent.php';
require_once __DIR__ . '/../lib/iys.php';

$EXPECTED_TOKEN = '1b40bd059d3ee0f9c5acccf50618a46b259e9460b2c844f7';

const RESULT_ASK      = '1'; // Onay IVR (menu)
const RESULT_CONTINUE = '2'; // Normal akış

function netgsm_out(string $status, string $result, string $data = ''): void {
  header('Content-Type: application/json; charset=UTF-8');
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  header('Pragma: no-cache');
  echo json_encode([
    'status' => (string)$status,
    'result' => (string)$result,
    'data'   => (string)$data,
  ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

function read_input(): array {
  $in = [];
  foreach (['token','arayan_no','aranan_no','santral_no','arama_id','tus_bilgisi','caller','from','msisdn'] as $k) {
    if (isset($_GET[$k]))  $in[$k] = (string)$_GET[$k];
    if (isset($_POST[$k])) $in[$k] = (string)$_POST[$k];
  }
  $ct = (string)($_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '');
  if (stripos($ct, 'application/json') !== false) {
    $raw = file_get_contents('php://input');
    $j = is_string($raw) ? json_decode($raw, true) : null;
    if (is_array($j)) {
      foreach ($j as $k => $v) {
        if (is_scalar($v) || $v === null) $in[(string)$k] = (string)$v;
      }
    }
  }
  return $in;
}

function norm_phone(string $s): string {
  $s = trim($s);
  if ($s === '') return '';
  return preg_replace('/\D+/', '', $s) ?? '';
}

function has_tus(string $arayanNo, string $tus): bool {
  $arayanNo = trim($arayanNo);
  if ($arayanNo === '' || $tus === '') return false;

  try {
    $pdo = db();
    $sql = "
      SELECT 1
      FROM webhook_logs
      WHERE raw_body IS NOT NULL
        AND JSON_VALID(raw_body)
        AND JSON_UNQUOTE(JSON_EXTRACT(raw_body,'$.arayan_no')) = ?
        AND JSON_UNQUOTE(JSON_EXTRACT(raw_body,'$.tus_bilgisi')) = ?
      LIMIT 1
    ";
    $st = $pdo->prepare($sql);
    $st->execute([$arayanNo, $tus]);
    return (bool)$st->fetchColumn();
  } catch (Throwable $e) {
    return false;
  }
}

/** ✅ tuş geldiyse kaydet */
function log_webhook(array $in): void {
  try {
    $pdo = db();
    $raw = json_encode($in, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if (!is_string($raw) || $raw === '') return;

    // created_at yoksa bunu: INSERT INTO webhook_logs (raw_body) VALUES (?)
    $sql = "INSERT INTO webhook_logs (raw_body, created_at) VALUES (?, NOW())";
    $st = $pdo->prepare($sql);
    $st->execute([$raw]);
  } catch (Throwable $e) {
    // log hatası akışı bozmasın
  }
}

$in = read_input();

$token    = trim((string)($in['token'] ?? ''));
$arayanNo = norm_phone((string)($in['arayan_no'] ?? $in['caller'] ?? $in['from'] ?? $in['msisdn'] ?? ''));
$tus      = trim((string)($in['tus_bilgisi'] ?? ''));

if ($EXPECTED_TOKEN !== '') {
  if ($token === '' || !hash_equals($EXPECTED_TOKEN, $token)) {
    netgsm_out('error', 'hangup', '');
  }
}

if ($arayanNo === '') {
  netgsm_out('error', 'hangup', '');
}

/**
 * Tuş geldiyse:
 * - MUTLAKA logla (yeni kayıt burada)
 * - her iki durumda da normal akışa devam et (result=2)
 */
if (consent_is_approved_digit($tus) || consent_is_rejected_digit($tus)) {
  log_webhook($in);

  if (consent_is_approved_digit($tus) && $arayanNo !== '') {
    try {
      iys_sync_phone(db(), $arayanNo, 'onayli', [
        'source' => 'webhook_consent_test',
        'event_ref' => (string)($in['arama_id'] ?? ''),
        'force' => false,
      ]);
    } catch (Throwable $e) {
      // IYS hatasi webhook cevabini bozmasin
    }
  }

  netgsm_out('success', RESULT_CONTINUE, '');
}

/**
 * Tuş yoksa sadece karar:
 * - geçmişte 2 varsa devam
 * - yoksa sor (Onay IVR'a yönlendir)
 */
if (has_tus($arayanNo, consent_digit_approved())) {
  netgsm_out('success', RESULT_CONTINUE, '');
}

netgsm_out('success', RESULT_ASK, '');
