<?php
/* ═══════════════════════════════════════════════════════════════
   Yapay Zekayla Kur — yapay zeka botu kayıt ucu (bot-kayit.php)
   .htaccess yalnız YAPAY ZEKA botlarını buraya yönlendirir.
   Googlebot, Bingbot ve gerçek ziyaretçiler bu dosyaya hiç uğramaz.
   Görev: ziyareti veri/botlar.jsonl dosyasına yaz, sonra istenen
   dosyayı olduğu gibi servis et (içerik değişmez, gecikme ~1 ms).
   ═══════════════════════════════════════════════════════════════ */
error_reporting(0);

$KOK  = __DIR__;
$VERI = $KOK . '/veri';

$p = isset($_GET['p']) ? (string)$_GET['p'] : '';
$p = ltrim($p, '/');
if ($p === '' || substr($p, -1) === '/') { $p .= 'index.html'; }

/* güvenlik: dizin geçişi yok, yalnız beklenen karakterler ve uzantılar */
if (strpos($p, '..') !== false || !preg_match('#^[A-Za-z0-9/_\-\.]+$#', $p)) {
  http_response_code(400); exit;
}
$uzanti = strtolower(pathinfo($p, PATHINFO_EXTENSION));
if (!in_array($uzanti, ['html', 'txt', 'xml'], true)) { http_response_code(404); exit; }

$dosya = realpath($KOK . '/' . $p);
if ($dosya === false || strpos($dosya, realpath($KOK)) !== 0 || !is_file($dosya)) {
  http_response_code(404); exit;
}

/* ── kayıt ── */
$ua = substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 300);
$BOTLAR = ['GPTBot', 'OAI-SearchBot', 'ChatGPT-User', 'PerplexityBot', 'Perplexity-User',
           'ClaudeBot', 'Claude-User', 'Claude-SearchBot', 'anthropic-ai', 'meta-externalagent',
           'CCBot', 'DuckAssistBot', 'YouBot', 'Amazonbot', 'cohere-ai',
           'Applebot-Extended', 'Timpibot', 'omgili'];
$ad = 'diger';
foreach ($BOTLAR as $b) { if (stripos($ua, $b) !== false) { $ad = $b; break; } }

if (!is_dir($VERI)) { @mkdir($VERI, 0755, true); @file_put_contents("$VERI/.htaccess", "Require all denied\n"); }
/* ⚠️ Kayit DOLARSA bile sayfa yine servis edilir.
   Bu uc gercek sayfa icerigini yapay zeka botlarina donduruyor;
   engellenirse AI gorunurlugu zarar gorur. Bu yuzden sinir yalniz
   KAYIT YAZMAYI durdurur, icerik servisini asla durdurmaz. */
$BOT_KAYIT = "$VERI/botlar.jsonl";
$bot_yazilabilir = !(is_file($BOT_KAYIT) && filesize($BOT_KAYIT) > 10 * 1048576);
if ($bot_yazilabilir) @file_put_contents($BOT_KAYIT, json_encode([
  'ts'   => date('c'),
  'bot'  => $ad,
  'path' => '/' . $p,
  'ua'   => $ua,
  'ip'   => substr((string)($_SERVER['REMOTE_ADDR'] ?? ''), 0, 45),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n", FILE_APPEND | LOCK_EX);

/* ── dosyayı olduğu gibi sun ── */
$tipler = ['html' => 'text/html; charset=utf-8',
           'txt'  => 'text/plain; charset=utf-8',
           'xml'  => 'application/xml; charset=utf-8'];
header('Content-Type: ' . $tipler[$uzanti]);
header('X-Robots-Tag: all');
/* CDN bu yaniti onbellege alip insanlara servis etmesin ve
   her bot ziyareti gercekten kaydedilsin */
header('Cache-Control: private, no-store');
header('Vary: User-Agent');
readfile($dosya);
