<?php
// NERGtrack collector: receives beacons from the Shopify store and logs them.
declare(strict_types=1);
require __DIR__ . '/config.php';

header('Cache-Control: no-store');
header('X-Robots-Tag: noindex, nofollow');

function nt_done(bool $gif = false): void {
    if ($gif) {
        header('Content-Type: image/gif');
        echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
    } else {
        http_response_code(204);
    }
    exit;
}

function nt_str($v, int $max): string {
    if (!is_scalar($v)) return '';
    $s = trim((string)$v);
    $s = preg_replace('/[\x00-\x1F\x7F]/u', '', $s) ?? '';
    return function_exists('mb_substr') ? mb_substr($s, 0, $max) : substr($s, 0, $max);
}

function nt_origin_ok(string $url): bool {
    if ($url === '') return false;
    $host = strtolower((string)parse_url($url, PHP_URL_HOST));
    if ($host === '') return false;
    foreach (NT_ALLOWED_HOSTS as $h) {
        if ($host === strtolower($h)) return true;
    }
    return false;
}

$method   = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$noscript = ($method === 'GET' && isset($_GET['ns']));

// Only accept hits that come from the store's own pages.
$origin  = $_SERVER['HTTP_ORIGIN'] ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if (!nt_origin_ok($origin) && !nt_origin_ok($referer)) nt_done($noscript);

// Real visitor IP/country come from Cloudflare's headers (nergtwo is behind Cloudflare).
$ip      = nt_str($_SERVER['HTTP_CF_CONNECTING_IP'] ?? ($_SERVER['REMOTE_ADDR'] ?? ''), 45);
$country = strtoupper(nt_str($_SERVER['HTTP_CF_IPCOUNTRY'] ?? '', 2));
$ua      = nt_str($_SERVER['HTTP_USER_AGENT'] ?? '', 500);
if ($ip === '') nt_done($noscript);

try {
    $db = new PDO(
        'mysql:host=' . NT_DB_HOST . ';dbname=' . NT_DB_NAME . ';charset=utf8mb4',
        NT_DB_USER, NT_DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false]
    );
} catch (Throwable $e) {
    nt_done($noscript);
}

// Parse the hit
if ($noscript) {
    $d = ['t' => 'view', 'sid' => 'noscript', 'pv' => bin2hex(random_bytes(8)),
          'u' => nt_str($_GET['u'] ?? '', 500), 'r' => $referer];
} else {
    $raw = file_get_contents('php://input', false, null, 0, 8192);
    $d = json_decode((string)$raw, true);
    if (!is_array($d)) nt_done();
}

$type = nt_str($d['t'] ?? '', 10);
$sid  = nt_str($d['sid'] ?? '', 32);
$pvid = nt_str($d['pv'] ?? '', 32);
if (!preg_match('/^[a-z0-9]{1,32}$/', $sid) || !preg_match('/^[a-z0-9]{1,32}$/', $pvid)) nt_done($noscript);

try {
    if ($type === 'leave') {
        $st = $db->prepare('UPDATE nt_hits
            SET dur_ms = GREATEST(COALESCE(dur_ms,0), ?), interacted = GREATEST(COALESCE(interacted,0), ?)
            WHERE pvid = ? AND sid = ?');
        $st->execute([min(max((int)($d['ms'] ?? 0), 0), 86400000), ((int)($d['it'] ?? 0)) ? 1 : 0, $pvid, $sid]);
        nt_done();
    }
    if ($type !== 'view') nt_done($noscript);

    // Rate limit per IP; anything over the limit is counted in nt_floods instead.
    $st = $db->prepare('SELECT COUNT(*) FROM nt_hits WHERE ip = ? AND ts >= NOW() - INTERVAL 60 SECOND');
    $st->execute([$ip]);
    if ((int)$st->fetchColumn() >= NT_RATE_PER_MIN) {
        $st = $db->prepare("INSERT INTO nt_floods (ip, minute, country, hits)
            VALUES (?, DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:00'), ?, 1)
            ON DUPLICATE KEY UPDATE hits = hits + 1");
        $st->execute([$ip, $country]);
        nt_done($noscript);
    }

    $sw = isset($d['sw']) ? min(max((int)$d['sw'], 0), 65535) : null;
    $sh = isset($d['sh']) ? min(max((int)$d['sh'], 0), 65535) : null;

    $st = $db->prepare('INSERT IGNORE INTO nt_hits
        (pvid, sid, ip, country, ua, path, tpl, referrer, sw, sh, lang, tz, webdriver, noscript)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
    $st->execute([
        $pvid, $sid, $ip, $country, $ua,
        nt_str($d['u'] ?? '', 500),
        nt_str($d['tp'] ?? '', 60),
        nt_str($d['r'] ?? '', 500),
        $sw, $sh,
        nt_str($d['lang'] ?? '', 20),
        nt_str($d['tz'] ?? '', 50),
        ((int)($d['wd'] ?? 0)) ? 1 : 0,
        $noscript ? 1 : 0,
    ]);

    // Occasional cleanup of old data
    if (random_int(1, 500) === 1) {
        $db->prepare('DELETE FROM nt_hits WHERE ts < NOW() - INTERVAL ? DAY')->execute([NT_KEEP_DAYS]);
        $db->prepare('DELETE FROM nt_floods WHERE minute < NOW() - INTERVAL ? DAY')->execute([NT_KEEP_DAYS]);
    }
} catch (Throwable $e) {
    // never break the store; just drop the hit
}
nt_done($noscript);
