<?php
if ($method !== 'POST') {
    json_response(['error' => 'Method not allowed'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['prompt']) || empty(trim($input['prompt']))) {
    json_response(['error' => 'Prompt is required'], 400);
}

$gpt = new GPTClient();

$prompt = trim($input['prompt']);
$type = $input['type'] ?? 'external';
$language = $input['language'] ?? 'en';
$length = $input['length'] ?? 'medium';
$style = $input['style'] ?? 'professional';

// Enhance the prompt with additional context
$enhancedPrompt = buildEnhancedPrompt($prompt, $type, $language, $length, $style);

try {
    $generatedArticle = $gpt->generateArticle($enhancedPrompt, $type, $language);

    if ($generatedArticle) {
        json_response([
            'success' => true,
            'article' => $generatedArticle
        ]);
    } else {
        json_response([
            'success' => false,
            'error' => 'Failed to generate article content'
        ], 500);
    }
} catch (Exception $e) {
    error_log("AI Generation error: " . $e->getMessage());
    json_response([
        'success' => false,
        'error' => 'AI service temporarily unavailable'
    ], 500);
}

function buildEnhancedPrompt($originalPrompt, $type, $language, $length, $style) {
    $lengthMap = [
        'short' => '300-500 words',
        'medium' => '500-800 words',
        'long' => '800-1200 words'
    ];

    $styleDescriptions = [
        'professional' => 'professional, authoritative, and informative',
        'casual' => 'casual, friendly, and conversational',
        'technical' => 'technical, detailed, and precise',
        'creative' => 'creative, engaging, and imaginative'
    ];

    $typeContext = $type === 'internal'
        ? 'This is for an internal corporate blog, focusing on knowledge sharing and strategic insights for team members.'
        : 'This is for an external marketing blog, focusing on audience engagement, SEO optimization, and brand promotion.';

    $targetLength = $lengthMap[$length] ?? '500-800 words';
    $styleDescription = $styleDescriptions[$style] ?? 'professional and informative';

    return "Write a blog article about: {$originalPrompt}

Context: {$typeContext}

Requirements:
- Length: {$targetLength}
- Writing style: {$styleDescription}
- Target audience: " . ($type === 'internal' ? 'Internal team members and stakeholders' : 'General public and potential customers') . "
- Include relevant subheadings (H2, H3) to structure the content
- Make it engaging and valuable for readers
- Ensure proper formatting with HTML tags
- Include practical insights or actionable information

The article should be well-researched, informative, and tailored for the specified audience and purpose.";
}
?>