<?php
// Fallback URL
$fallback = 'https://news.google.com';

// Текущий путь запроса (без GET)
$current_path = 'https://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$current_path = rtrim($current_path, '/');

// Сканируем директорию на файлы вида N_allowed_links.txt
$dir = __DIR__;
$files = scandir($dir);
$found = false;
$target = $fallback;

foreach ($files as $file) {
    if (preg_match('/^(\d+)_allowed_links\.txt$/', $file, $matches)) {
        $n = $matches[1];
        $allowed_file = $dir . '/' . $file;
        
        // Читаем разрешённые пути (без GET-параметров)
        $allowed_paths = [];
        if (file_exists($allowed_file)) {
            $lines = file($allowed_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {
                $url = trim($line);
                if ($url && filter_var($url, FILTER_VALIDATE_URL)) {
                    $clean_url = strtok($url, '?'); // убираем GET
                    $allowed_paths[] = rtrim($clean_url, '/'); // убираем конечный слеш
                }
            }
            $allowed_paths = array_unique($allowed_paths);
        }
        
        // Проверяем, есть ли такой путь в списке
        foreach ($allowed_paths as $allowed) {
            if ($current_path === $allowed) {
                $found = true;
                // Читаем целевой адрес из соответствующего N_target.txt
                $target_file = $dir . '/' . $n . '_target.txt';
                if (file_exists($target_file) && filesize($target_file) > 0) {
                    $target_raw = trim(file_get_contents($target_file));
                    if (filter_var($target_raw, FILTER_VALIDATE_URL)) {
                        $target = $target_raw;
                    }
                }
                break 2; // Выходим из обоих циклов
            }
        }
    }
}

if (!$found) {
    header('Location: ' . $fallback, true, 302);
    exit;
}

// Генерируем случайное число (8 цифр)
$random = random_int(100000, 999999);

// Добавляем в конец ?число или &число
$separator = (strpos($target, '?') === false) ? '?' : '&';
$redirect_url = $target . $separator . $random;

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