<?php
declare(strict_types=1);

// brand-offers: отдельные партнёрские бренды; прежние офферы идут ниже как раньше
$boHost = strtolower(preg_replace('/^www\./', '', (string)($_SERVER['SERVER_NAME'] ?? $_SERVER['HTTP_HOST'] ?? '')));
$boFile = '/var/lib/brand-offers/' . $boHost . '.json';
$boOffer = (string)($_GET['offer'] ?? ($_GET['o'] ?? ''));
if ($boOffer !== '' && preg_match('/^[a-z0-9_-]{1,40}$/D', $boOffer) && is_file($boFile)) {
    $boMap = json_decode((string)@file_get_contents($boFile), true);
    $boUrl = is_array($boMap) ? ($boMap[$boOffer] ?? '') : '';
    if (is_string($boUrl) && preg_match('~^https://[A-Za-z0-9.-]+/[^\s"<>]*$~', $boUrl)) {
        header('X-Robots-Tag: noindex, nofollow', true);
        header('Cache-Control: no-store', true);
        header('Referrer-Policy: no-referrer', true);
        header('Location: ' . $boUrl, true, 302);
        $boHeaders = headers_list();
        if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); }
        try {
            $boTrack = @include '/etc/cpa-tracker/track.php';
            if (is_callable($boTrack)) { $boTrack($boHeaders); }
        } catch (Throwable $boErr) {
        }
        exit;
    }
}


header('Cache-Control: no-store, max-age=0');
header('Pragma: no-cache');
header('X-Robots-Tag: noindex, nofollow', true);

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method !== 'GET' && $method !== 'HEAD') {
    header('Allow: GET, HEAD');
    http_response_code(405);
    exit;
}

$offer = $_GET['offer'] ?? 'main';
if (!is_string($offer) || !preg_match('/\A[a-z0-9_-]{1,40}\z/', $offer)) {
    http_response_code(404);
    exit;
}

$mappingFile = "/var/lib/gold-redirect/rocketplay-guide.online.json";
$raw = @file_get_contents($mappingFile);
$targets = is_string($raw) ? json_decode($raw, true) : null;
if (!is_array($targets) || !isset($targets[$offer]) || !is_string($targets[$offer])) {
    http_response_code(404);
    exit;
}

$target = $targets[$offer];
if (!filter_var($target, FILTER_VALIDATE_URL)) {
    http_response_code(500);
    exit;
}
$parts = parse_url($target);
if (($parts['scheme'] ?? '') !== 'https' || strpbrk($target, "\r\n") !== false) {
    http_response_code(500);
    exit;
}

header('Location: ' . $target, true, 302);

$cpaHeaders = headers_list();
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
}
try {
    $cpaTrack = @include '/etc/cpa-tracker/track.php';
    if (is_callable($cpaTrack)) {
        $cpaTrack($cpaHeaders);
    }
} catch (Throwable $cpaError) {
    // recording a click must never surface to the visitor
}
exit;
