<?php
declare(strict_types=1);

/**
 * Ortak yardımcılar:
 * - session başlatma (config'teki session_name ile)
 * - CSRF
 * - output escape
 */

function start_app_session(): void
{
  $cfg = app_config();

  if (session_status() !== PHP_SESSION_ACTIVE) {
    session_name((string)$cfg['session_name']);
    session_start();
  }
}

function csrf_token(): string
{
  start_app_session();
  if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(16));
  }
  return (string)$_SESSION['csrf'];
}

function csrf_verify(): void
{
  start_app_session();
  $t = (string)($_POST['csrf'] ?? '');
  if ($t === '' || !hash_equals((string)($_SESSION['csrf'] ?? ''), $t)) {
    http_response_code(419);
    echo "CSRF doğrulaması başarısız.";
    exit;
  }
}

function e(string $v): string
{
  return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

/**
 * webhook_logs.raw_body icin ortak parser.
 * - JSON object / JSON list / { raw: "{...}" } destekler
 * - application/x-www-form-urlencoded (a=1&b=2) destekler
 */
function parse_webhook_payload(string $raw): array
{
  $raw = trim($raw);
  if ($raw === '') return [];

  $decoded = json_decode($raw, true);
  if (is_array($decoded)) {
    $isList = array_keys($decoded) === range(0, count($decoded) - 1);
    if ($isList) {
      $first = $decoded[0] ?? null;
      if (is_array($first)) $decoded = $first;
    }

    if (isset($decoded['raw']) && is_string($decoded['raw'])) {
      $inner = json_decode((string)$decoded['raw'], true);
      if (is_array($inner)) return $inner;
    }

    return $decoded;
  }

  $parsed = [];
  parse_str($raw, $parsed);
  if (is_array($parsed) && !empty($parsed)) {
    if (isset($parsed['raw']) && is_string($parsed['raw'])) {
      $inner = json_decode((string)$parsed['raw'], true);
      if (is_array($inner)) return $inner;
    }
    return $parsed;
  }

  return [];
}

function payload_pick(array $payload, array $keys): string
{
  foreach ($keys as $k) {
    if (isset($payload[$k]) && !is_array($payload[$k])) {
      return trim((string)$payload[$k]);
    }
  }
  return '';
}
