<?php
function ip_in_cidr($ip, $cidr) {
    list($subnet, $mask) = explode('/', $cidr);
    $mask_long = $mask == 0 ? 0 : (-1 << (32 - $mask)) & 0xFFFFFFFF;
    return (ip2long($ip) & $mask_long) === (ip2long($subnet) & $mask_long);
}
$yandex_ranges = ['5.45.192.0/18','5.255.192.0/18','37.9.64.0/18','37.140.128.0/18',
    '77.88.0.0/18','84.252.160.0/19','87.250.224.0/19','90.156.176.0/22',
    '93.158.128.0/18','95.108.128.0/17','100.43.64.0/19','130.193.32.0/19',
    '141.8.128.0/18','178.154.128.0/17','199.21.96.0/22','199.36.240.0/22',
    '213.180.192.0/19'];
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$is_yandex = false;
if ($ip && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
    foreach ($yandex_ranges as $cidr) {
        if (ip_in_cidr($ip, $cidr)) { $is_yandex = true; break; }
    }
}
if (!$is_yandex && $ip) {
    $host = @gethostbyaddr($ip);
    if ($host && preg_match('/\.yandex\.(ru|com|net)$/i', $host)) {
        if (@gethostbyname($host) === $ip) $is_yandex = true;
    }
}
if (!$is_yandex && stripos($ua, 'Yandex') !== false) $is_yandex = true;
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-cache, no-store, must-revalidate, private');
header('Pragma: no-cache');
header('Expires: 0');
header('X-Robots-Tag: ' . ($is_yandex ? 'noarchive' : 'noindex, noarchive'));
readfile(__DIR__ . ($is_yandex ? '/index-bot.html' : '/index-user.html'));
