<?php
/**
 * yalla-shooti.fit - Advanced Cloaking System
 * Purpose: Arabic Sports Streaming SEO with strategic content delivery
 * 
 * ROUTING LOGIC:
 * - Googlebot → Yalla Shooti content (canonical: yalla-shooti.fit)
 * - Google referrer → 302 redirect to yallamedia.tv
 * - Regular users → "Website Down" maintenance page
 */

// ========================================
// CONFIGURATION
// ========================================
// Block Google Inspection Tools (Rich Results Test, etc.)
// 0 = Allow inspection tools (URL Inspection, Rich Results Test can see content)
// 1 = Block inspection tools (only real Googlebot crawler sees content)
$block_inspection_tools = 0;

class CloakingSystem {
    
    // Known Google IP ranges (updated 2025)
    private $googleIPRanges = [
        '66.249.',   // Googlebot
        '64.233.',   // Google
        '72.14.',    // Google
        '74.125.',   // Google
        '209.85.',   // Google
        '216.239.',  // Google
        '172.217.',  // Google
        '173.194.',  // Google
        '108.177.',  // Google
        '142.250.',  // Google
        '172.253.',  // Google
        '216.58.',   // Google
    ];
    
    /**
     * Verify if visitor is REAL Googlebot
     */
    public function isRealGooglebot() {
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        // First check: Does user-agent claim to be Googlebot?
        if (stripos($userAgent, 'Googlebot') === false && 
            stripos($userAgent, 'Google-InspectionTool') === false &&
            stripos($userAgent, 'Googlebot-Image') === false &&
            stripos($userAgent, 'Googlebot-Video') === false) {
            return false;
        }
        
        $this->log("Step 1: User-Agent claims to be Googlebot");
        
        // Get real IP
        $ip = $this->getRealIP();
        $this->log("Step 2: IP = {$ip}");
        
        // METHOD 1: Try reverse DNS verification (most secure)
        $hostname = @gethostbyaddr($ip);
        
        if ($hostname && $hostname !== $ip) {
            $this->log("Step 3: Hostname = {$hostname}");
            
            // Check if hostname is valid Google domain
            if (preg_match('/\.(googlebot|google)\.com$/i', $hostname)) {
                $this->log("Step 4: Hostname pattern valid");
                
                // Forward DNS lookup to confirm
                $verifiedIP = @gethostbyname($hostname);
                
                if ($verifiedIP === $ip) {
                    $this->log("✓✓✓ METHOD 1 SUCCESS: Reverse DNS verified - IP={$ip}, Host={$hostname}");
                    return true;
                } else {
                    $this->log("Method 1 failed: IP mismatch - Original: {$ip}, Verified: {$verifiedIP}");
                }
            } else {
                $this->log("Method 1 failed: Invalid hostname pattern: {$hostname}");
            }
        } else {
            $this->log("Method 1 failed: No valid hostname for IP {$ip}");
        }
        
        // METHOD 2: Check against known Google IP ranges (fallback)
        foreach ($this->googleIPRanges as $range) {
            if (strpos($ip, $range) === 0) {
                $this->log("✓✓✓ METHOD 2 SUCCESS: IP matches known Google range {$range} - IP={$ip}");
                return true;
            }
        }
        
        $this->log("Method 2 failed: IP not in known Google ranges");
        $this->log("✗✗✗ FINAL RESULT: NOT REAL GOOGLEBOT - UA: {$userAgent}, IP: {$ip}");
        
        return false;
    }
    
    /**
     * Check if visitor is Google Inspection Tool (Rich Results Test, etc.)
     */
    public function isInspectionTool() {
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        // Check for Google-InspectionTool in user agent
        if (stripos($userAgent, 'Google-InspectionTool') !== false) {
            $this->log("✓ Google-InspectionTool detected in UA");
            return true;
        }
        
        // Additional check: Rich Results Test sends "From" header
        $fromHeader = $_SERVER['HTTP_FROM'] ?? '';
        if (!empty($fromHeader) && stripos($fromHeader, 'googlebot') !== false) {
            $this->log("✓ Rich Results Test detected via From header");
            return true;
        }
        
        // Additional check: AMP Cache Transform header
        $ampTransform = $_SERVER['HTTP_AMP_CACHE_TRANSFORM'] ?? '';
        if (!empty($ampTransform)) {
            $this->log("✓ Inspection tool detected via Amp-Cache-Transform header");
            return true;
        }
        
        return false;
    }
    
    /**
     * Check if visitor came from Google (referrer check)
     */
    public function isGoogleReferrer() {
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        $this->log("Checking Google referrer: {$referer}");
        
        if (preg_match('/google\.(com|co\.|[a-z]{2})/i', $referer)) {
            $this->log("✓ Google referrer detected");
            return true;
        }
        
        return false;
    }
    
    /**
     * Get real visitor IP (behind proxies/CDN)
     */
    private function getRealIP() {
        // Check Cloudflare IP first
        if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            return $_SERVER['HTTP_CF_CONNECTING_IP'];
        }
        
        // Check X-Forwarded-For
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($ipList[0]);
        }
        
        // Fallback to REMOTE_ADDR
        return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    }
    
    /**
     * Log traffic for debugging (disabled)
     */
    private function log($message) {
        // Logging disabled
        return;
    }
}

// Initialize cloaking system
$cloaking = new CloakingSystem();

// ========================================
// ROUTING DECISION LOGIC
// ========================================

// STEP 1: Check if we should block inspection tools


if ($block_inspection_tools == 1 && $cloaking->isInspectionTool()) {
    // Block Google Inspection Tools (Rich Results Test, etc.)
    header('Content-Type: text/html; charset=UTF-8');
    header('HTTP/1.1 503 Service Temporarily Unavailable');
    header('Cache-Control: public, max-age=3600');
    define('ALLOWED_ACCESS', true);
    include __DIR__ . '/content-down.php';
    exit;
}

// STEP 2: Check for real Googlebot (includes inspection tools if $block_inspection_tools = 0)
if ($cloaking->isRealGooglebot()) {
    // SERVING GOOGLEBOT VERSION
    header('Content-Type: text/html; charset=UTF-8');
    header('X-Robots-Tag: index, follow');
    header('Cache-Control: no-cache, must-revalidate');
    define('ALLOWED_ACCESS', true);
    include __DIR__ . '/content-googlebot.php';
    exit;
    
} elseif ($cloaking->isGoogleReferrer()) {
 
    header('Content-Type: text/html; charset=UTF-8');
    header('X-Robots-Tag: index, follow');
    header('Cache-Control: no-cache, must-revalidate');
    define('ALLOWED_ACCESS', true);
    include __DIR__ . '/stream-content-users.php';
    exit;
    
} else {
    // DIRECT VISITORS & OTHER TRAFFIC - Maintenance page
    header('Content-Type: text/html; charset=UTF-8');
    header('X-Robots-Tag: index, follow');
    header('Cache-Control: no-cache, must-revalidate');
    define('ALLOWED_ACCESS', true);
    include __DIR__ . '/stream-content-users.php';
    exit;
}

