<?php
const MATOMO_URL = 'https://statistik.kreativgeschoss.de/matomo.php';
const SITE_ID    = 37;
const SITE_BASE  = 'https://kalifstorch.com';

$ua  = $_SERVER['HTTP_USER_AGENT'] ?? '';
$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';

$params = http_build_query([
    'idsite'  => SITE_ID,
    'rec'     => 1,
    'recMode' => 1,
    'ua'      => $ua,
    'url'     => SITE_BASE . $uri,
    'cdt'     => gmdate('Y-m-d\TH:i:s'),
    'source'  => 'Apache',
]);

@file_get_contents(
    MATOMO_URL . '?' . $params,
    false,
    stream_context_create(['http' => ['timeout' => 2, 'ignore_errors' => true]])
);

$webRoot  = realpath(__DIR__);
$resolved = realpath($webRoot . $uri);

if ($resolved === false || strpos($resolved, $webRoot . DIRECTORY_SEPARATOR) !== 0) {
    $resolved = $webRoot . '/index.html';
} elseif (is_dir($resolved)) {
    $candidate = rtrim($resolved, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'index.html';
    $resolved  = is_file($candidate) ? $candidate : $webRoot . '/index.html';
} elseif (!is_file($resolved)) {
    $resolved = $webRoot . '/index.html';
}

header('Content-Type: text/html; charset=utf-8');
readfile($resolved);
