<?php
/**
 * AI-zichtbaarheid voor Alexander (alxndr.ai).
 *
 * AI-assistenten en crawlers draaien geen JavaScript, dus de tracker ziet ze
 * nooit. De .htaccess in out/ (scripts/write-redirects.mjs) stuurt alleen hun
 * verzoeken naar dit bestand (in out/, naast de pagina's).
 * Het serveert precies het bestand dat de server
 * zelf had gegeven en meldt daarna aan Alexander wie welke pagina las.
 * Mensen komen hier nooit langs.
 *
 * De schrijfsleutel staat in data/alexander.json, buiten de docroot, en wordt
 * ingesteld op /gevonden. Zonder sleutel wordt er niets gemeld; de pagina
 * wordt altijd geserveerd.
 */
declare(strict_types=1);

$root = realpath(__DIR__);
$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');

$types = [
    'html' => 'text/html; charset=utf-8',
    'txt' => 'text/plain; charset=utf-8',
    'xml' => 'application/xml',
    'json' => 'application/json',
    'pdf' => 'application/pdf',
    'md' => 'text/markdown; charset=utf-8',
];

// trailingSlash staat aan: /contact wordt /contact/, net als bij een gewoon bezoek.
if (substr($path, -1) !== '/' && $root && is_file($root . $path . '/index.html')
    && strpos((string) realpath($root . $path), $root . DIRECTORY_SEPARATOR) === 0) {
    $query = $_SERVER['QUERY_STRING'] ?? '';
    header('Location: ' . $path . '/' . ($query !== '' ? '?' . $query : ''), true, 301);
    $status = 301;
    $file = null;
} else {
    $file = null;
    foreach ([$path, rtrim($path, '/') . '/index.html'] as $candidate) {
        $real = realpath($root . $candidate);
        if ($real && is_file($real) && strpos($real, $root . DIRECTORY_SEPARATOR) === 0
            && isset($types[strtolower(pathinfo($real, PATHINFO_EXTENSION))])) {
            $file = $real;
            break;
        }
    }
    $status = 200;
    if ($file === null) {
        $status = 404;
        $file = is_file($root . '/404.html') ? $root . '/404.html' : null;
    }
}

http_response_code($status);
if ($file) {
    $type = $types[strtolower(pathinfo($file, PATHINFO_EXTENSION))];
    header('Content-Type: ' . $type);
    header('Content-Length: ' . (string) filesize($file));
    if (strpos($type, 'text/html') === 0) header('Cache-Control: no-cache');
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') readfile($file);
}

// Het antwoord is weg; wat volgt houdt de bezoeker niet op.
if (function_exists('litespeed_finish_request')) {
    litespeed_finish_request();
} elseif (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
}

$config = @json_decode((string) @file_get_contents(dirname(__DIR__) . '/data/alexander.json'), true);
$key = is_array($config) ? (string) ($config['writeKey'] ?? '') : '';
if ($key === '' || !function_exists('curl_init')) return;

$ch = curl_init('https://alxndr.ai/api/v1/crawls');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode([
        'via' => 'static',
        'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'path' => $path,
        'status' => $status,
        'ip' => $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? null,
    ]),
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key, 'Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 2,
    CURLOPT_TIMEOUT => 3,
]);
curl_exec($ch);
curl_close($ch);
