<?php
declare(strict_types=1);

// Publik, anonym pixel-endpoint på Engine-domänen.

header('Content-Type: image/gif');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');
header('Content-Length: 34');

$pixel = base64_decode('R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==', true);
require_once __DIR__ . '/tracking-filter.php';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET'
    || tracking_is_automated((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), (string)($_SERVER['HTTP_REFERER'] ?? ''))) {
    echo $pixel === false ? '' : $pixel;
    exit;
}

function tracking_normalize_title(string $title): string {
    $title = trim((string)preg_replace('/\s+/u', ' ', $title));
    return mb_strtolower(mb_substr($title, 0, 500), 'UTF-8');
}

function tracking_legacy_publication(PDO $pdo, string $customerName, string $title): ?int {
    $customerName = trim($customerName);
    $title = trim((string)preg_replace('/\s+/u', ' ', $title));
    if ($customerName === '' || $title === '' || mb_strlen($title, 'UTF-8') > 500) return null;

    $identityTable=databases_separated()?'motor_services':'motor_customers';
    $stmt = platform_db()->prepare("SELECT id FROM {$identityTable} WHERE name=? LIMIT 1");
    $stmt->execute([$customerName]);
    $customerId = (int)$stmt->fetchColumn();
    if ($customerId < 1) return null;
    if(customer_product($customerId)!=='publishing')return null;

    $normalized = tracking_normalize_title($title);
    $stmt = $pdo->prepare(
        'SELECT id FROM motor_tracking_publications
         WHERE customer_id=? AND LOWER(TRIM(title))=? ORDER BY is_legacy,id LIMIT 2'
    );
    $stmt->execute([$customerId, $normalized]);
    $matches = $stmt->fetchAll(PDO::FETCH_COLUMN);
    if (count($matches) === 1) return (int)$matches[0];

    $legacyKey = hash('sha256', $customerId . "\0" . $normalized);
    $token = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
    $stmt = $pdo->prepare(
        "INSERT INTO motor_tracking_publications
             (token,customer_id,title,legacy_key,is_legacy)
         VALUES (?,?,?,?,1)
         ON DUPLICATE KEY UPDATE title=VALUES(title),id=LAST_INSERT_ID(id)"
    );
    $stmt->execute([$token, $customerId, mb_substr($title, 0, 500), $legacyKey]);
    $id = (int)$pdo->lastInsertId();
    if ($id > 0) return $id;
    $stmt = $pdo->prepare('SELECT id FROM motor_tracking_publications WHERE legacy_key=?');
    $stmt->execute([$legacyKey]);
    return ($value = $stmt->fetchColumn()) ? (int)$value : null;
}

try {
    require_once __DIR__ . '/live2/config.php';
    $pdo = product_db('publishing');
    $publicationId = null;
    $token = trim((string)($_GET['t'] ?? ''));

    if (preg_match('/^[A-Za-z0-9_-]{40,64}$/', $token)) {
        $stmt = $pdo->prepare('SELECT id FROM motor_tracking_publications WHERE token=?');
        $stmt->execute([$token]);
        $value = $stmt->fetchColumn();
        if ($value !== false) $publicationId = (int)$value;
    } else {
        $customer = (string)($_GET['legacy_customer'] ?? '');
        $title = (string)($_GET['legacy_title'] ?? '');
        $signature = (string)($_GET['sig'] ?? '');
        $expected = hash_hmac('sha256', $customer . "\n" . $title, TRACKING_LEGACY_SECRET);
        if ($customer !== '' && $title !== '' && preg_match('/^[a-f0-9]{64}$/', $signature)
            && hash_equals($expected, $signature)) {
            $publicationId = tracking_legacy_publication($pdo, $customer, $title);
        }
    }

    if ($publicationId) {
        $stmt = $pdo->prepare(
            "INSERT INTO motor_tracking_hourly
                 (publication_id,view_hour_utc,live_views)
             VALUES (?,UTC_TIMESTAMP() - INTERVAL MINUTE(UTC_TIMESTAMP()) MINUTE
                                      - INTERVAL SECOND(UTC_TIMESTAMP()) SECOND,1)
             ON DUPLICATE KEY UPDATE live_views=live_views+1"
        );
        $stmt->execute([$publicationId]);
    }
} catch (Throwable $error) {
    error_log('Live² tracking pixel error: ' . $error->getMessage());
}

echo $pixel === false ? '' : $pixel;
