<?php
class GPTClient {
    private $apiKey;
    private $apiUrl;

    public function __construct() {
        $this->apiKey = GPT_API_KEY;
        $this->apiUrl = GPT_API_URL;
    }

    public function generateArticle($prompt, $type = 'external', $language = 'en') {
        try {
            $systemPrompt = $this->getSystemPrompt($type, $language);

            $data = [
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => $systemPrompt
                    ],
                    [
                        'role' => 'user',
                        'content' => $prompt
                    ]
                ],
                'max_tokens' => 2000,
                'temperature' => 0.7
            ];

            $response = $this->makeRequest($data);

            if ($response && isset($response['choices'][0]['message']['content'])) {
                $content = $response['choices'][0]['message']['content'];
                return $this->parseArticleContent($content);
            }

            return false;
        } catch (Exception $e) {
            error_log("GPT generate article error: " . $e->getMessage());
            return false;
        }
    }

    public function summarizeContent($content, $maxLength = 200) {
        try {
            $prompt = "Please summarize the following content in {$maxLength} characters or less:\n\n{$content}";

            $data = [
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $prompt
                    ]
                ],
                'max_tokens' => 100,
                'temperature' => 0.5
            ];

            $response = $this->makeRequest($data);

            if ($response && isset($response['choices'][0]['message']['content'])) {
                return trim($response['choices'][0]['message']['content']);
            }

            return false;
        } catch (Exception $e) {
            error_log("GPT summarize content error: " . $e->getMessage());
            return false;
        }
    }

    public function chatResponse($message, $context = []) {
        try {
            $messages = [
                [
                    'role' => 'system',
                    'content' => 'You are a helpful assistant for the Excellent Blog platform. Provide helpful, informative responses about blogging, content creation, and platform features.'
                ]
            ];

            if (!empty($context)) {
                foreach ($context as $ctx) {
                    $messages[] = $ctx;
                }
            }

            $messages[] = [
                'role' => 'user',
                'content' => $message
            ];

            $data = [
                'model' => 'gpt-3.5-turbo',
                'messages' => $messages,
                'max_tokens' => 500,
                'temperature' => 0.7
            ];

            $response = $this->makeRequest($data);

            if ($response && isset($response['choices'][0]['message']['content'])) {
                return trim($response['choices'][0]['message']['content']);
            }

            return false;
        } catch (Exception $e) {
            error_log("GPT chat response error: " . $e->getMessage());
            return false;
        }
    }

    private function getSystemPrompt($type, $language) {
        $langMap = [
            'zh-TW' => '繁體中文',
            'zh-CN' => '简体中文',
            'en' => 'English',
            'ja' => 'Japanese',
            'vi' => 'Vietnamese',
            'ms' => 'Malay'
        ];

        $langName = $langMap[$language] ?? '繁體中文';

        if ($type === 'internal') {
            return "You are a content writer for an internal corporate blog. Write professional, informative articles in {$langName} that are suitable for internal team consumption. Focus on insights, strategies, and knowledge sharing.

Please format your response as JSON with the following structure:
{
    \"title\": \"Article title\",
    \"content\": \"Full article content in HTML format\",
    \"excerpt\": \"Brief excerpt or summary\",
    \"meta_title\": \"SEO meta title\",
    \"meta_description\": \"SEO meta description\"
}";
        } else {
            return "You are a content writer for an external marketing blog. Write engaging, SEO-optimized articles in {$langName} that are suitable for public consumption and marketing purposes. Focus on value-driven content that attracts and engages readers.

Please format your response as JSON with the following structure:
{
    \"title\": \"Article title\",
    \"content\": \"Full article content in HTML format\",
    \"excerpt\": \"Brief excerpt or summary\",
    \"meta_title\": \"SEO meta title\",
    \"meta_description\": \"SEO meta description\"
}";
        }
    }

    private function parseArticleContent($content) {
        $decoded = json_decode($content, true);

        if ($decoded && isset($decoded['title']) && isset($decoded['content'])) {
            return [
                'title' => $decoded['title'],
                'content' => $decoded['content'],
                'excerpt' => $decoded['excerpt'] ?? '',
                'meta_title' => $decoded['meta_title'] ?? $decoded['title'],
                'meta_description' => $decoded['meta_description'] ?? $decoded['excerpt'] ?? ''
            ];
        }

        return [
            'title' => 'AI Generated Article',
            'content' => $content,
            'excerpt' => substr(strip_tags($content), 0, 200) . '...',
            'meta_title' => 'AI Generated Article',
            'meta_description' => substr(strip_tags($content), 0, 160) . '...'
        ];
    }

    private function makeRequest($data) {
        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->apiKey,
                'Content-Type: application/json'
            ],
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false
        ]);

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

        if (curl_errno($ch)) {
            error_log("cURL error: " . curl_error($ch));
            curl_close($ch);
            return false;
        }

        curl_close($ch);

        if ($httpCode !== 200) {
            error_log("GPT API error: HTTP {$httpCode} - {$response}");
            return false;
        }

        return json_decode($response, true);
    }

    public function generatePublicContent($params) {
        try {
            $startTime = microtime(true);

            // Build comprehensive prompt based on parameters
            $prompt = $this->buildPublicPrompt($params);
            $systemPrompt = $this->getPublicSystemPrompt($params);

            $maxTokens = $this->getMaxTokensForLength($params['length']);

            $data = [
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => $systemPrompt
                    ],
                    [
                        'role' => 'user',
                        'content' => $prompt
                    ]
                ],
                'max_tokens' => $maxTokens,
                'temperature' => $this->getTemperatureForStyle($params['style'])
            ];

            $response = $this->makeRequest($data);

            if ($response && isset($response['choices'][0]['message']['content'])) {
                $content = $response['choices'][0]['message']['content'];
                $result = $this->parsePublicContent($content, $params);

                $endTime = microtime(true);
                $result['generation_time'] = round($endTime - $startTime, 2);
                $result['tokens_used'] = $response['usage']['total_tokens'] ?? 0;

                return $result;
            }

            return ['success' => false, 'error' => 'No content generated'];

        } catch (Exception $e) {
            error_log("GPT generate public content error: " . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage(), 'error_code' => 'GENERATION_ERROR'];
        }
    }

    private function buildPublicPrompt($params) {
        $prompt = "Topic: {$params['topic']}\n";
        $prompt .= "Target Audience: {$params['audience']}\n";
        $prompt .= "Tone: {$params['tone']}\n";
        $prompt .= "Style: {$params['style']}\n";
        $prompt .= "Length: {$params['length']}\n";

        if (!empty($params['keywords']) && is_array($params['keywords'])) {
            $prompt .= "Keywords to include: " . implode(', ', $params['keywords']) . "\n";
        }

        $prompt .= "\nPlease write a comprehensive article about this topic.";

        return $prompt;
    }

    private function getPublicSystemPrompt($params) {
        $langMap = [
            'zh-TW' => '繁體中文',
            'zh-CN' => '简体中文',
            'en' => 'English',
            'ja' => 'Japanese',
            'vi' => 'Vietnamese',
            'ms' => 'Malay'
        ];

        $langName = $langMap[$params['language']] ?? 'English';

        $styleInstructions = [
            'informative' => 'Focus on providing factual, educational content with clear explanations.',
            'persuasive' => 'Write compelling content that convinces and influences the reader.',
            'narrative' => 'Tell a story or use storytelling elements to engage the reader.',
            'descriptive' => 'Use vivid descriptions and sensory details to paint a clear picture.',
            'technical' => 'Provide detailed technical information with accuracy and precision.',
            'casual' => 'Write in a conversational, friendly tone as if talking to a friend.'
        ];

        $lengthGuide = [
            'short' => '300-500 words',
            'medium' => '600-1000 words',
            'long' => '1200-2000 words'
        ];

        $style = $styleInstructions[$params['style']] ?? $styleInstructions['informative'];
        $length = $lengthGuide[$params['length']] ?? $lengthGuide['medium'];

        return "You are a professional content writer creating high-quality articles in {$langName}.

Writing Style: {$style}
Target Length: {$length}
Tone: {$params['tone']}
Target Audience: {$params['audience']}

Please format your response as JSON with the following structure:
{
    \"title\": \"Compelling article title\",
    \"content\": \"Full article content in HTML format with proper headings, paragraphs, and formatting\",
    \"summary\": \"Brief 2-3 sentence summary of the article\",
    \"meta_description\": \"SEO meta description (150-160 characters)\",
    \"keywords_used\": [\"keyword1\", \"keyword2\", \"keyword3\"]
}

Ensure the content is well-structured, engaging, and optimized for the specified audience and purpose.";
    }

    private function getMaxTokensForLength($length) {
        switch ($length) {
            case 'short':
                return 800;
            case 'medium':
                return 1500;
            case 'long':
                return 2500;
            default:
                return 1500;
        }
    }

    private function getTemperatureForStyle($style) {
        switch ($style) {
            case 'technical':
                return 0.3;
            case 'informative':
                return 0.5;
            case 'persuasive':
                return 0.7;
            case 'narrative':
            case 'casual':
                return 0.8;
            default:
                return 0.7;
        }
    }

    private function parsePublicContent($content, $params) {
        $decoded = json_decode($content, true);

        if ($decoded && isset($decoded['title']) && isset($decoded['content'])) {
            $wordCount = str_word_count(strip_tags($decoded['content']));

            return [
                'success' => true,
                'title' => $decoded['title'],
                'content' => $decoded['content'],
                'summary' => $decoded['summary'] ?? '',
                'meta_description' => $decoded['meta_description'] ?? '',
                'keywords_used' => $decoded['keywords_used'] ?? [],
                'word_count' => $wordCount
            ];
        }

        // Fallback parsing if JSON fails
        $wordCount = str_word_count(strip_tags($content));
        $lines = explode("\n", $content);
        $title = !empty($lines[0]) ? trim($lines[0]) : 'Generated Article';

        return [
            'success' => true,
            'title' => $title,
            'content' => nl2br(htmlspecialchars($content)),
            'summary' => substr(strip_tags($content), 0, 200) . '...',
            'meta_description' => substr(strip_tags($content), 0, 160) . '...',
            'keywords_used' => $params['keywords'] ?? [],
            'word_count' => $wordCount
        ];
    }
}

// Create AIWriter alias for backward compatibility
class AIWriter extends GPTClient {
    public function generatePublicContent($params) {
        return parent::generatePublicContent($params);
    }
}
?>