<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Check if this is a valid request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['success' => false, 'error' => 'Only POST method allowed'], 405);
}

try {
    // API Key authentication
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_POST['api_key'] ?? null;

    if (!$apiKey) {
        json_response(['success' => false, 'error' => 'API key is required'], 401);
    }

    // Validate API key (you can implement a more sophisticated validation)
    if (!validateApiKey($apiKey)) {
        json_response(['success' => false, 'error' => 'Invalid API key'], 403);
    }

    // Get request parameters
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

    $topic = $input['topic'] ?? '';
    $language = $input['language'] ?? 'en';
    $style = $input['style'] ?? 'informative';
    $length = $input['length'] ?? 'medium';
    $keywords = $input['keywords'] ?? [];
    $audience = $input['audience'] ?? 'general';
    $tone = $input['tone'] ?? 'professional';

    // Validate required parameters
    if (empty($topic)) {
        json_response(['success' => false, 'error' => 'Topic is required'], 400);
    }

    // Validate parameters
    $validLanguages = ['zh-TW', 'zh-CN', 'en', 'ja', 'vi', 'ms'];
    $validStyles = ['informative', 'persuasive', 'narrative', 'descriptive', 'technical', 'casual'];
    $validLengths = ['short', 'medium', 'long'];
    $validTones = ['professional', 'friendly', 'formal', 'casual', 'enthusiastic', 'neutral'];

    if (!in_array($language, $validLanguages)) {
        json_response(['success' => false, 'error' => 'Invalid language. Supported: ' . implode(', ', $validLanguages)], 400);
    }

    if (!in_array($style, $validStyles)) {
        json_response(['success' => false, 'error' => 'Invalid style. Supported: ' . implode(', ', $validStyles)], 400);
    }

    if (!in_array($length, $validLengths)) {
        json_response(['success' => false, 'error' => 'Invalid length. Supported: ' . implode(', ', $validLengths)], 400);
    }

    if (!in_array($tone, $validTones)) {
        json_response(['success' => false, 'error' => 'Invalid tone. Supported: ' . implode(', ', $validTones)], 400);
    }

    // Initialize AI Writer
    $aiWriter = new AIWriter();

    // Prepare AI generation parameters
    $aiParams = [
        'topic' => $topic,
        'language' => $language,
        'style' => $style,
        'length' => $length,
        'keywords' => is_array($keywords) ? $keywords : explode(',', $keywords),
        'audience' => $audience,
        'tone' => $tone
    ];

    // Generate content using AI
    $result = $aiWriter->generatePublicContent($aiParams);

    if ($result['success']) {
        // Log API usage for analytics
        logApiUsage($apiKey, $topic, $language, $result['word_count'] ?? 0);

        json_response([
            'success' => true,
            'data' => [
                'title' => $result['title'],
                'content' => $result['content'],
                'summary' => $result['summary'] ?? '',
                'word_count' => $result['word_count'] ?? 0,
                'keywords_used' => $result['keywords_used'] ?? [],
                'meta_description' => $result['meta_description'] ?? '',
                'generated_at' => date('Y-m-d H:i:s'),
                'language' => $language,
                'style' => $style,
                'tone' => $tone
            ],
            'usage' => [
                'tokens_used' => $result['tokens_used'] ?? 0,
                'generation_time' => $result['generation_time'] ?? 0
            ]
        ]);
    } else {
        json_response([
            'success' => false,
            'error' => $result['error'] ?? 'Failed to generate content',
            'error_code' => $result['error_code'] ?? 'GENERATION_FAILED'
        ], 500);
    }

} catch (Exception $e) {
    error_log("Public AI Writer API error: " . $e->getMessage());
    json_response([
        'success' => false,
        'error' => 'Internal server error',
        'error_code' => 'INTERNAL_ERROR'
    ], 500);
}

function validateApiKey($apiKey) {
    try {
        $database = new Database();
        $db = $database->getConnection();

        // First check hardcoded demo keys for backward compatibility
        $demoKeys = [
            'ak_f67f201b0829a5106d7db52c6f1b120f6d69ed6ef76d9c48',
            'demo_key_12345',
            'test_api_key_67890',
            'public_demo_key'
        ];

        if (in_array($apiKey, $demoKeys)) {
            return true;
        }

        // Check database for API key
        $query = "SELECT id, usage_limit, usage_count, is_active, expires_at
                  FROM api_keys
                  WHERE api_key = :api_key AND is_active = 1";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':api_key', $apiKey);
        $stmt->execute();

        $keyData = $stmt->fetch();

        if (!$keyData) {
            return false;
        }

        // Check if expired
        if ($keyData['expires_at'] && strtotime($keyData['expires_at']) < time()) {
            return false;
        }

        // Check usage limit (if not unlimited)
        if ($keyData['usage_limit'] > 0 && $keyData['usage_count'] >= $keyData['usage_limit']) {
            return false;
        }

        // Update usage count and last used time
        $updateQuery = "UPDATE api_keys
                        SET usage_count = usage_count + 1, last_used_at = NOW()
                        WHERE api_key = :api_key";
        $updateStmt = $db->prepare($updateQuery);
        $updateStmt->bindParam(':api_key', $apiKey);
        $updateStmt->execute();

        return true;

    } catch (Exception $e) {
        error_log("API key validation error: " . $e->getMessage());
        return false;
    }
}

function logApiUsage($apiKey, $topic, $language, $wordCount) {
    try {
        $database = new Database();
        $db = $database->getConnection();

        $query = "INSERT INTO api_usage_logs (api_key, endpoint, topic, language, word_count, used_at)
                  VALUES (:api_key, 'ai-writer', :topic, :language, :word_count, NOW())";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':api_key', $apiKey);
        $stmt->bindParam(':topic', $topic);
        $stmt->bindParam(':language', $language);
        $stmt->bindParam(':word_count', $wordCount);
        $stmt->execute();
    } catch (Exception $e) {
        error_log("API usage logging error: " . $e->getMessage());
    }
}
?>