<?php
/**
 * WebChat API
 * Handles AI chat interactions with OpenAI and Ollama
 */

require_once __DIR__ . '/../config/config.php';

class WebChatService {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }

    /**
     * Send message to AI and get response
     */
    public function chat($userId, $message, $sessionId = null) {
        // Get current model configuration
        $modelConfig = $this->getModelConfig();

        if (!$modelConfig) {
            return [
                'success' => false,
                'message' => 'AI model not configured'
            ];
        }

        // Generate session ID if not provided
        if (!$sessionId) {
            $sessionId = uniqid('chat_', true);
        }

        // Save user message
        $this->saveChatLog($userId, $sessionId, 'user', $message, null, 0, $modelConfig['model'], $modelConfig['provider']);

        try {
            // Send to appropriate provider
            if ($modelConfig['provider'] === 'openai') {
                $response = $this->chatWithOpenAI($message, $modelConfig);
            } else if ($modelConfig['provider'] === 'ollama') {
                $response = $this->chatWithOllama($message, $modelConfig);
            } else {
                throw new Exception('Unknown provider: ' . $modelConfig['provider']);
            }

            // Save assistant response
            $this->saveChatLog(
                $userId,
                $sessionId,
                'assistant',
                $message,
                $response['message'],
                $response['tokens'] ?? 0,
                $modelConfig['model'],
                $modelConfig['provider']
            );

            return [
                'success' => true,
                'message' => $response['message'],
                'session_id' => $sessionId,
                'provider' => $modelConfig['provider'],
                'model' => $modelConfig['model'],
                'tokens' => $response['tokens'] ?? 0
            ];

        } catch (Exception $e) {
            error_log('WebChat error: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Failed to get AI response: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Chat with OpenAI
     */
    private function chatWithOpenAI($message, $config) {
        $apiKey = env('OPENAI_API_KEY');

        if (!$apiKey) {
            throw new Exception('OpenAI API key not configured');
        }

        $model = $config['model'] ?? 'gpt-4o-mini';

        $data = [
            'model' => $model,
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'You are a helpful AI assistant for BlogPostAI system. Help users with questions about social media posting, content management, and system configuration.'
                ],
                [
                    'role' => 'user',
                    'content' => $message
                ]
            ],
            'temperature' => 0.7,
            'max_tokens' => 1000
        ];

        $ch = curl_init('https://api.openai.com/v1/chat/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new Exception('OpenAI API error: HTTP ' . $httpCode . ' - ' . $response);
        }

        $result = json_decode($response, true);

        if (!isset($result['choices'][0]['message']['content'])) {
            throw new Exception('Invalid OpenAI response format');
        }

        return [
            'message' => $result['choices'][0]['message']['content'],
            'tokens' => $result['usage']['total_tokens'] ?? 0
        ];
    }

    /**
     * Chat with Ollama
     */
    private function chatWithOllama($message, $config) {
        $serverId = $config['ollama_server_id'] ?? null;

        if (!$serverId) {
            throw new Exception('Ollama server not configured');
        }

        // Get server info
        $stmt = $this->db->prepare("SELECT ip, port FROM ollama_servers WHERE id = ?");
        $stmt->execute([$serverId]);
        $server = $stmt->fetch();

        if (!$server) {
            throw new Exception('Ollama server not found');
        }

        $model = $config['model'] ?? 'llama2';
        $url = "http://{$server['ip']}:{$server['port']}/api/generate";

        $data = [
            'model' => $model,
            'prompt' => $message,
            'stream' => false,
            'options' => [
                'temperature' => 0.7,
                'num_predict' => 1000
            ]
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new Exception('Ollama API error: HTTP ' . $httpCode . ' - ' . $response);
        }

        $result = json_decode($response, true);

        if (!isset($result['response'])) {
            throw new Exception('Invalid Ollama response format');
        }

        return [
            'message' => $result['response'],
            'tokens' => 0 // Ollama doesn't return token count in this format
        ];
    }

    /**
     * Get current model configuration
     */
    private function getModelConfig() {
        $stmt = $this->db->prepare("
            SELECT `key`, value_encrypted
            FROM settings
            WHERE section = 'webchat'
            AND `key` IN ('PROVIDER', 'MODEL', 'OLLAMA_SERVER_ID')
        ");
        $stmt->execute();

        $config = [];
        while ($row = $stmt->fetch()) {
            $config[strtolower($row['key'])] = $row['value_encrypted'];
        }

        if (!isset($config['provider'])) {
            $config['provider'] = 'openai'; // default
        }

        if (!isset($config['model'])) {
            $config['model'] = $config['provider'] === 'openai' ? 'gpt-4o-mini' : 'llama2';
        }

        return $config;
    }

    /**
     * Save chat log to database
     */
    private function saveChatLog($userId, $sessionId, $role, $message, $response, $tokens, $model, $provider) {
        $stmt = $this->db->prepare("
            INSERT INTO chat_logs (user_id, session_id, role, message, response, tokens, model, provider)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $userId,
            $sessionId,
            $role,
            $message,
            $response,
            $tokens,
            $model,
            $provider
        ]);
    }

    /**
     * Get chat history
     */
    public function getChatHistory($userId, $sessionId = null, $limit = 50) {
        if ($sessionId) {
            $stmt = $this->db->prepare("
                SELECT role, message, response, tokens, model, provider, created_at
                FROM chat_logs
                WHERE user_id = ? AND session_id = ?
                ORDER BY created_at ASC
                LIMIT ?
            ");
            $stmt->execute([$userId, $sessionId, $limit]);
        } else {
            $stmt = $this->db->prepare("
                SELECT role, message, response, tokens, model, provider, created_at, session_id
                FROM chat_logs
                WHERE user_id = ?
                ORDER BY created_at DESC
                LIMIT ?
            ");
            $stmt->execute([$userId, $limit]);
        }

        return $stmt->fetchAll();
    }

    /**
     * Clear chat history
     */
    public function clearChatHistory($userId, $sessionId = null) {
        if ($sessionId) {
            $stmt = $this->db->prepare("
                DELETE FROM chat_logs
                WHERE user_id = ? AND session_id = ?
            ");
            $stmt->execute([$userId, $sessionId]);
        } else {
            $stmt = $this->db->prepare("
                DELETE FROM chat_logs
                WHERE user_id = ?
            ");
            $stmt->execute([$userId]);
        }

        return ['success' => true, 'message' => 'Chat history cleared'];
    }
}
