<?php
/**
 * Gemini AI Integration with Knowledge Base (RAG)
 * Smart customer support with context memory + trained answers
 */

class GeminiAI {
    private $apiKey;
    private $model;
    private $apiUrl;
    private $db;
    private $systemPrompt;

    public function __construct() {
        $this->apiKey = GEMINI_API_KEY;
        $this->model = GEMINI_MODEL;
        $this->apiUrl = GEMINI_API_URL . $this->model . ':generateContent?key=' . $this->apiKey;
        $this->db = Database::getInstance();
        $this->systemPrompt = $this->getSystemPrompt();
    }

    /**
     * Get system prompt from database or use default
     */
    private function getSystemPrompt() {
        $setting = $this->db->fetch(
            "SELECT setting_value FROM settings WHERE setting_key = 'ai_system_prompt'"
        );
        return $setting ? $setting['setting_value'] : $this->getDefaultSystemPrompt();
    }

    /**
     * Enhanced default system prompt with full business context
     */
    private function getDefaultSystemPrompt() {
        return "You are the AI assistant for Team Hydra Shop - India's most trusted digital product store.

" .
               "BUSINESS INFO:
" .
               "- Store: Team Hydra Shop (teamhydrashop.com)
" .
               "- Support: WhatsApp 917038146526, Telegram @teamhydrashops
" .
               "- Products: Netflix (₹299), Prime Video (₹199), ChatGPT Plus (₹399), Midjourney (₹499), CapCut Pro (₹149), Canva Pro (₹499), Spotify (₹349), YouTube Premium (₹199)
" .
               "- Payment: UPI (teamhydra@kotak), screenshot required after payment
" .
               "- Delivery: Auto (2-5 mins) or Manual (15-30 mins)
" .
               "- Warranty: As per product page, replacement if stops working
" .
               "- Reseller: 15% commission, min withdrawal ₹500

" .
               "BEHAVIOR RULES:
" .
               "1. Always be friendly, professional, and use emojis
" .
               "2. If you don't know something, say you'll connect them to human support
" .
               "3. Never make up prices - use only the prices listed above
" .
               "4. For payment issues, always mention sending screenshot to bot
" .
               "5. Keep responses under 150 words unless detailed explanation needed
" .
               "6. Use Hindi/English mix if user writes in Hindi
" .
               "7. Always guide users to browse products for latest availability";
    }

    /**
     * Generate AI Response with Knowledge Base RAG
     */
    public function generateResponse($userId, $message, $context = []) {
        // Step 1: Search Knowledge Base for relevant answers
        $kbAnswers = $this->searchKnowledgeBase($message);

        // Step 2: Get chat history for context
        $history = $this->getChatHistory($userId);

        // Step 3: Build conversation with knowledge injection
        $contents = [];

        // System instruction as first turn
        $systemText = $this->systemPrompt;

        // Inject knowledge base answers if found
        if (!empty($kbAnswers)) {
            $systemText .= "

RELEVANT KNOWLEDGE FROM DATABASE:
";
            foreach ($kbAnswers as $i => $answer) {
                $systemText .= ($i + 1) . ". Q: " . $answer['question'] . "
   A: " . $answer['answer'] . "
";
            }
            $systemText .= "
Use this knowledge to answer accurately. If user asks something not in knowledge base, use your general understanding but stay within business context.";

            // Track usage
            foreach ($kbAnswers as $ans) {
                $this->db->execute("UPDATE knowledge_base SET usage_count = usage_count + 1 WHERE id = ?", [$ans['id']], 'i');
            }
        }

        $contents[] = [
            'role' => 'user',
            'parts' => [['text' => $systemText]]
        ];

        $contents[] = [
            'role' => 'model',
            'parts' => [['text' => 'Understood. I am ready to assist customers using the provided knowledge base and business context.']]
        ];

        // Add history
        foreach ($history as $chat) {
            $role = $chat['role'] === 'assistant' ? 'model' : 'user';
            $contents[] = [
                'role' => $role,
                'parts' => [['text' => $chat['message']]]
            ];
        }

        // Add current message
        $contents[] = [
            'role' => 'user',
            'parts' => [['text' => $message]]
        ];

        $payload = [
            'contents' => $contents,
            'generationConfig' => [
                'temperature' => 0.7,
                'maxOutputTokens' => 800,
                'topP' => 0.9,
                'topK' => 40
            ],
            'safetySettings' => [
                ['category' => 'HARM_CATEGORY_HARASSMENT', 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'],
                ['category' => 'HARM_CATEGORY_HATE_SPEECH', 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'],
                ['category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'],
                ['category' => 'HARM_CATEGORY_DANGEROUS_CONTENT', 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE']
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 || empty($response)) {
            error_log('Gemini API Error: HTTP ' . $httpCode);
            return $this->getFallbackResponse($message, $kbAnswers);
        }

        $data = json_decode($response, true);

        if (isset($data['error'])) {
            error_log('Gemini API Error: ' . json_encode($data['error']));
            return $this->getFallbackResponse($message, $kbAnswers);
        }

        if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
            $aiResponse = $data['candidates'][0]['content']['parts'][0]['text'];

            // Save to history
            $this->saveChatHistory($userId, 'user', $message);
            $this->saveChatHistory($userId, 'assistant', $aiResponse);

            return $aiResponse;
        }

        return $this->getFallbackResponse($message, $kbAnswers);
    }

    /**
     * Search Knowledge Base using FULLTEXT + keyword matching
     */
    private function searchKnowledgeBase($query) {
        $query = strtolower(trim($query));

        // Method 1: FULLTEXT search (if available)
        try {
            $results = $this->db->fetchAll(
                "SELECT * FROM knowledge_base 
                 WHERE is_active = 1 
                 AND MATCH(question, answer, keywords) AGAINST(? IN NATURAL LANGUAGE MODE)
                 ORDER BY priority DESC, usage_count DESC
                 LIMIT 3",
                [$query],
                's'
            );

            if (!empty($results)) {
                return $results;
            }
        } catch (Exception $e) {
            // FULLTEXT not available, fall through to keyword search
        }

        // Method 2: Keyword matching
        $words = explode(' ', preg_replace('/[^a-z0-9\s]/', '', $query));
        $words = array_filter($words, function($w) { return strlen($w) > 2; });

        if (empty($words)) {
            return [];
        }

        $conditions = [];
        $params = [];
        foreach ($words as $word) {
            $conditions[] = "(question LIKE ? OR answer LIKE ? OR keywords LIKE ?)";
            $params[] = "%{$word}%";
            $params[] = "%{$word}%";
            $params[] = "%{$word}%";
        }

        $sql = "SELECT * FROM knowledge_base 
                WHERE is_active = 1 
                AND (" . implode(' OR ', $conditions) . ")
                ORDER BY priority DESC, usage_count DESC
                LIMIT 3";

        return $this->db->fetchAll($sql, $params);
    }

    /**
     * Get chat history for user
     */
    private function getChatHistory($userId) {
        return $this->db->fetchAll(
            "SELECT role, message FROM chat_history 
             WHERE user_id = ? 
             ORDER BY created_at DESC 
             LIMIT ?",
            [$userId, MAX_CHAT_HISTORY],
            'ii'
        );
    }

    /**
     * Save chat to history
     */
    private function saveChatHistory($userId, $role, $message) {
        $this->db->insert('chat_history', [
            'user_id' => $userId,
            'role' => $role,
            'message' => $message
        ]);
    }

    /**
     * Clear chat history
     */
    public function clearHistory($userId) {
        return $this->db->delete('chat_history', 'user_id = ?', [$userId]);
    }

    /**
     * Get fallback response using knowledge base directly
     */
    private function getFallbackResponse($message, $kbAnswers = []) {
        $message = strtolower($message);

        // If knowledge base has direct match, use it
        if (!empty($kbAnswers)) {
            return $kbAnswers[0]['answer'] . "

💡 Need more help? Contact @teamhydrashops or WhatsApp 917038146526";
        }

        // Keyword-based fallback
        if (strpos($message, 'price') !== false || strpos($message, 'cost') !== false || strpos($message, '₹') !== false) {
            return "💰 Our prices:
🎬 Netflix Premium 4K - ₹299
🤖 ChatGPT Plus - ₹399
🎨 CapCut Pro Lifetime - ₹149
📺 Spotify Premium - ₹349
📺 YouTube Premium - ₹199

Browse all: /products";
        }

        if (strpos($message, 'order') !== false || strpos($message, 'buy') !== false || strpos($message, 'purchase') !== false) {
            return "🛒 To order:
1️⃣ Browse products with /products
2️⃣ Click 'Buy Now'
3️⃣ Pay via UPI to teamhydra@kotak
4️⃣ Send screenshot here
5️⃣ Get delivery instantly!";
        }

        if (strpos($message, 'support') !== false || strpos($message, 'help') !== false || strpos($message, 'issue') !== false) {
            return "🆘 Support:
📱 WhatsApp: 917038146526
📢 Telegram: @teamhydrashops
🌐 Website: teamhydrashop.com

Or create ticket via /support";
        }

        if (strpos($message, 'refund') !== false || strpos($message, 'money back') !== false) {
            return "💸 Refund Policy:
✅ Full refund if not delivered in 24h
✅ Partial refund for technical issues
❌ No refund after credentials used

Contact support with Order ID.";
        }

        if (strpos($message, 'reseller') !== false || strpos($message, 'affiliate') !== false || strpos($message, 'earn') !== false) {
            return "🤝 Reseller Program:
✅ 15% commission per sale
✅ Unique referral code
✅ Real-time tracking
✅ Min withdrawal: ₹500

Click 'Reseller Panel' in menu!";
        }

        if (strpos($message, 'payment') !== false || strpos($message, 'upi') !== false || strpos($message, 'pay') !== false) {
            return "💳 Payment:
UPI ID: teamhydra@kotak
Apps: GPay, PhonePe, Paytm, any UPI

After payment, send screenshot here for verification!";
        }

        if (strpos($message, 'delivery') !== false || strpos($message, 'when') !== false || strpos($message, 'time') !== false) {
            return "📦 Delivery:
⚡ Auto: 2-5 minutes
⏱️ Manual: 15-30 minutes

You'll receive credentials right here in chat!";
        }

        if (strpos($message, 'netflix') !== false) {
            return "🎬 Netflix Premium 4K - ₹299/month
✅ 4 screens + Ultra HD
✅ Private profile
✅ 30 days warranty

Order now with /products!";
        }

        if (strpos($message, 'chatgpt') !== false || strpos($message, 'gpt') !== false) {
            return "🤖 ChatGPT Plus - ₹399/month
✅ GPT-4 access
✅ Faster responses
✅ Priority during peak hours

Order: /products → AI Tools";
        }

        if (strpos($message, 'capcut') !== false) {
            return "🎨 CapCut Pro Lifetime - ₹149
✅ No watermark
✅ All premium effects
✅ Cloud storage
✅ One-time payment forever!

Order: /products → Editing Software";
        }

        return "👋 Hello! I'm your AI assistant from Team Hydra Shop.

I can help with:
🛍️ Products & prices
🛒 Orders & delivery
💰 Payments (UPI: teamhydra@kotak)
🆘 Support & refunds
🤝 Reseller program

What do you need help with? Or browse: /products";
    }

    /**
     * Detect if message is product-related
     */
    public function isProductQuery($message) {
        $keywords = ['netflix', 'prime', 'chatgpt', 'midjourney', 'capcut', 'canva', 'spotify', 'youtube', 'product', 'buy', 'price', 'subscription', 'cost', '₹'];
        $message = strtolower($message);
        foreach ($keywords as $keyword) {
            if (strpos($message, $keyword) !== false) return true;
        }
        return false;
    }

    /**
     * Update system prompt
     */
    public function updateSystemPrompt($newPrompt) {
        return Helpers::updateSetting('ai_system_prompt', $newPrompt);
    }
}
