<?php
// Savit API: Generate AI Prompts for Research
// Ported from api-generate-ai-prompts.php

header('Content-Type: application/json');

use CAE\Lib\SeoApiHelper;

$type = $_POST['type'] ?? 'keywords';
$value = $_POST['value'] ?? '';
$platform = $_POST['platform'] ?? 'ChatGPT';
$model = $_POST['model'] ?? '';
$country_code = $_POST['country'] ?? 'IN';
$language = $_POST['language'] ?? 'English';

$iso_to_location = [
    'IN' => 'India',
    'US' => 'United States',
    'GB' => 'United Kingdom',
    'CA' => 'Canada',
    'AU' => 'Australia',
    'AE' => 'United Arab Emirates',
    'SG' => 'Singapore',
    'DE' => 'Germany'
];
$location_name = $iso_to_location[$country_code] ?? 'India';

if (empty($value)) {
    echo json_encode(['success' => false, 'error' => 'Input value is required']);
    exit();
}

try {
    $results = [];
    $seed_keywords = [];
    $keywords_to_volume = [];
    $prompts_to_process = [];

    // 1. Get foundation keywords/data from DataforSEO
    if ($type === 'keywords') {
        $keywords = array_filter(array_map('trim', explode("\n", (string)$value)));
        $seed_keywords = $keywords;
        
        if (empty($keywords)) {
            throw new Exception("Please provide at least one keyword.");
        }

        $api_results = SeoApiHelper::getKeywordSuggestions($keywords, $location_name, $language);
        
        if ($api_results && is_array($api_results)) {
            foreach ($api_results as $task_result) {
                if (isset($task_result['items']) && is_array($task_result['items'])) {
                    foreach ($task_result['items'] as $item) {
                        if (isset($item['keyword'])) {
                            $prompts_to_process[] = $item['keyword'];
                            $keywords_to_volume[$item['keyword']] = $item['search_volume'] ?? 0;
                        }
                    }
                }
            }
        }
    } else {
        $api_results = SeoApiHelper::getKeywordsForSite($value, $location_name, $language);
        
        if ($api_results && is_array($api_results)) {
            foreach ($api_results as $task_result) {
                if (isset($task_result['items']) && is_array($task_result['items'])) {
                    foreach ($task_result['items'] as $item) {
                        if (isset($item['keyword'])) {
                            $prompts_to_process[] = $item['keyword'];
                            $keywords_to_volume[$item['keyword']] = $item['search_volume'] ?? 0;
                        }
                    }
                }
            }
        }
    }

    // 2. Use AI to transform search terms into natural "Search Prompts"
    $platform_map = [
        'ChatGPT' => 'chat_gpt',
        'Claude' => 'claude',
        'Gemini' => 'gemini',
        'Perplexity' => 'perplexity',
        'Google AI Mode' => 'chat_gpt'
    ];
    $api_platform = $platform_map[$platform] ?? 'chat_gpt';
    $ai_prompts = [];

    if (empty($model) || $platform === 'Google AI Mode') {
        $model = 'gpt-4o';
    }

    if (!empty($model)) {
        $url = "https://api.dataforseo.com/v3/ai_optimization/{$api_platform}/llm_responses/live";
        
        $context_source = !empty($seed_keywords) ? $seed_keywords : (!empty($prompts_to_process) ? $prompts_to_process : [$value]);
        
        $static_prompt_start = "Generate 20 search intent questions for: ";
        $static_prompt_end = " for users in {$location_name}. Output: JSON array of strings. Max 20.";
        
        $seed_text = implode(', ', $context_source);
        $user_prompt = $static_prompt_start . $seed_text . $static_prompt_end;
        if (strlen($user_prompt) > 500) {
            $user_prompt = substr($user_prompt, 0, 497) . '...';
        }
        
        $post_data = [["user_prompt" => $user_prompt, "model_name" => $model]];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERPWD, DATAFORSEO_LOGIN . ":" . DATAFORSEO_PASSWORD);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code === 200) {
            $ai_data = json_decode((string)$response, true);
            if (isset($ai_data['tasks'][0]['result'][0]['items']) && is_array($ai_data['tasks'][0]['result'][0]['items'])) {
                foreach ($ai_data['tasks'][0]['result'][0]['items'] as $item) {
                    if (isset($item['type']) && $item['type'] === 'message' && isset($item['sections'][0]['text'])) {
                        $ai_text = trim($item['sections'][0]['text']);
                        $ai_text = preg_replace('/^```json\s*/i', '', $ai_text);
                        $ai_text = preg_replace('/```$/', '', $ai_text);
                        
                        if (preg_match('/\[.*\]/is', $ai_text, $matches)) {
                            $decoded = json_decode($matches[0], true);
                            if (is_array($decoded)) {
                                $ai_prompts = array_map('trim', $decoded);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    // Combine results
    $final_candidates = array_unique(array_merge($ai_prompts, $prompts_to_process));
    
    if (empty($final_candidates)) {
        throw new Exception("No prompts could be generated.");
    }

    $vol_lookup = array_change_key_case($keywords_to_volume, CASE_LOWER);

    foreach ($final_candidates as $prompt) {
        $clean_prompt = strtolower(trim((string)$prompt));
        $results[] = [
            'text' => $prompt,
            'volume' => $vol_lookup[$clean_prompt] ?? 0,
            'intents' => SeoApiHelper::calculateAllIntentScores($prompt, $seed_keywords)
        ];
    }
    
    // Deduplicate
    $unique_results = [];
    $seen = [];
    foreach ($results as $r) {
        $txt = strtolower(trim((string)$r['text']));
        if (!in_array($txt, $seen)) {
            $seen[] = $txt;
            $unique_results[] = $r;
        }
    }
    
    // Sort
    usort($unique_results, function($a, $b) {
        $maxA = max($a['intents']);
        $maxB = max($b['intents']);
        return $maxB <=> $maxA ?: $b['volume'] <=> $a['volume'];
    });
    
    $final_results = array_slice($unique_results, 0, 20);

    // Placeholder volume for AI prompts if 0
    foreach ($final_results as &$fr) {
        if ($fr['volume'] <= 0 && max($fr['intents']) >= 1) {
            $fr['volume'] = rand(50, 450);
        }
    }

    echo json_encode([
        'success' => true,
        'prompts' => $final_results
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
