<?php
/**
 * 🕵️ AI Visitor Tracker Integration für Intelectra Shop
 * Erkennt KI-Besucher und loggt sie automatisch
 * 
 * USAGE: Include in item.class.php oder header.php
 */

class AIVisitorTracker {
    
    private $flask_dashboard_url = 'http://127.0.0.1:5000';
    
    public function trackVisitor() {
        // Visitor-Daten sammeln
        $visitor_data = [
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'url' => $_SERVER['REQUEST_URI'] ?? '',
            'ip_address' => $this->getRealIPAddress(),
            'referer' => $_SERVER['HTTP_REFERER'] ?? '',
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        // Async call zum Flask Dashboard (non-blocking)
        $this->sendToFlaskDashboard($visitor_data);
    }
    
    private function getRealIPAddress() {
        // Echte IP ermitteln (auch hinter Proxies)
        $ip_headers = [
            'HTTP_CF_CONNECTING_IP',     // Cloudflare
            'HTTP_CLIENT_IP',            // Proxy
            'HTTP_X_FORWARDED_FOR',      // Load Balancer
            'HTTP_X_FORWARDED',          
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'                // Standard
        ];
        
        foreach ($ip_headers as $header) {
            if (!empty($_SERVER[$header])) {
                $ip = $_SERVER[$header];
                // Bei mehreren IPs die erste nehmen
                if (strpos($ip, ',') !== false) {
                    $ip = trim(explode(',', $ip)[0]);
                }
                // IP validieren
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    }
    
    private function sendToFlaskDashboard($data) {
        // Non-blocking cURL request zum Flask Dashboard
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->flask_dashboard_url . '/api/detect-visitor',
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'User-Agent: Intelectra-AI-Tracker/1.0'
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 2,           // Max 2 Sekunden warten
            CURLOPT_CONNECTTIMEOUT => 1,    // Max 1 Sekunde für Verbindung
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_SSL_VERIFYPEER => false
        ]);
        
        // Async ausführen (non-blocking)
        $this->execInBackground($ch);
    }
    
    private function execInBackground($ch) {
        // cURL im Hintergrund ausführen ohne auf Antwort zu warten
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);  // Sehr kurzer Timeout
        @curl_exec($ch);  // @ um Fehler zu unterdrücken
        curl_close($ch);
    }
    
    /**
     * Intelligente KI-Erkennung (falls Flask nicht verfügbar)
     */
    public function detectAILocally($user_agent) {
        $ai_patterns = [
            'ChatGPT' => ['GPTBot', 'ChatGPT-User', 'OpenAI', 'gpt-crawler'],
            'Claude' => ['Claude-Web', 'Anthropic', 'claude.ai'],
            'Gemini' => ['Google-Extended', 'Bard', 'Gemini', 'GoogleOther'],
            'Perplexity' => ['PerplexityBot', 'perplexity.ai'],
            'Bing AI' => ['BingBot', 'EdgeBot', 'bing.com/chat'],
            'Meta AI' => ['FacebookBot', 'facebookexternalhit'],
            'You.com' => ['YouBot'],
            'SearchGPT' => ['SearchGPT', 'OpenAI-SearchBot']
        ];
        
        $user_agent_lower = strtolower($user_agent);
        
        foreach ($ai_patterns as $ai_name => $patterns) {
            foreach ($patterns as $pattern) {
                if (strpos($user_agent_lower, strtolower($pattern)) !== false) {
                    return $ai_name;
                }
            }
        }
        
        return null;
    }
    
    /**
     * Log AI-Besuch direkt in MySQL (Fallback)
     */
    public function logAIVisitDirectly($ai_name, $visitor_data) {
        try {
            // DB-Verbindung (hier deine DB-Credentials einsetzen)
            $pdo = new PDO(
                'mysql:host=localhost;dbname=intelectra_problems;charset=utf8mb4',
                'ai_schema_user',
                'your_password_here'
            );
            
            // Artikel-ID aus URL extrahieren
            $article_id = null;
            if (preg_match('/\/artikel\/(\d+)/', $visitor_data['url'], $matches)) {
                $article_id = intval($matches[1]);
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO ai_visitor_log 
                (ai_name, url, article_id, user_agent, ip_address, referer, visited_at)
                VALUES (?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $stmt->execute([
                $ai_name,
                $visitor_data['url'],
                $article_id,
                $visitor_data['user_agent'],
                $visitor_data['ip_address'],
                $visitor_data['referer']
            ]);
            
            return true;
            
        } catch (Exception $e) {
            // Silent fail - Live Shop darf nicht gestört werden
            error_log("AI Tracking failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Public API für Integration in Shop
     */
    public static function track() {
        $tracker = new self();
        $tracker->trackVisitor();
    }
    
    public static function isAI($user_agent) {
        $tracker = new self();
        return $tracker->detectAILocally($user_agent);
    }
}

// Auto-Track wenn direkt aufgerufen
if (basename(__FILE__) == basename($_SERVER['SCRIPT_NAME'])) {
    AIVisitorTracker::track();
}

/**
 * INTEGRATION BEISPIELE:
 * 
 * 1. In item.class.php am Ende von buildSingleItem():
 *    require_once 'ai_tracker_integration.php';
 *    AIVisitorTracker::track();
 * 
 * 2. In header.php/index.php:
 *    include_once 'core/python/ai_tracker_integration.php';
 *    AIVisitorTracker::track();
 * 
 * 3. Als separater Tracker:
 *    $ai_name = AIVisitorTracker::isAI($_SERVER['HTTP_USER_AGENT']);
 *    if ($ai_name) {
 *        echo "<!-- AI erkannt: $ai_name -->";
 *    }
 */
?>