<?php
// Savit API: Run a Research Prompt
// Ported from api-run-prompt.php

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

use CAE\Lib\Database;
use CAE\Lib\SeoApiHelper;

$prompt_id = $_POST['prompt_id'] ?? null;
$platform_label = $_POST['platform'] ?? 'ChatGPT';
$model_version = $_POST['model_version'] ?? '';
$country_code = $_POST['country_code'] ?? 'IN';
$web_search_supported = ($_POST['web_search_supported'] === 'true' || $_POST['web_search_supported'] === true || $_POST['web_search_supported'] == 1);

if (!$prompt_id || !$model_version) {
    echo json_encode(['success' => false, 'error' => 'Invalid parameters']);
    exit();
}

$platform_map = [
    'ChatGPT' => 'chat_gpt',
    'Claude' => 'claude',
    'Gemini' => 'gemini',
    'Perplexity' => 'perplexity',
    'Google AI Mode' => 'google_ai_mode'
];

$platform = $platform_map[$platform_label] ?? 'chat_gpt';

$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';

try {
    $db = Database::getInstance();
    
    // Update country code for future runs
    $db->update('brand_prompts', ['country_code' => $country_code], 'id = :id', ['id' => (int)$prompt_id]);

    // Fetch prompt and project details
    $prompt = $db->fetch(
        "SELECT p.prompt_text, p.brand_id, b.business_name, b.website_url 
         FROM brand_prompts p 
         JOIN projects b ON p.brand_id = b.id 
         WHERE p.id = ?",
        [(int)$prompt_id]
    );

    if (!$prompt) throw new Exception("Prompt not found");

    $prompt_text = $prompt['prompt_text'];
    $project_id = (int)$prompt['brand_id'];

    // Fetch name variations
    $name_variations = $db->fetchAll("SELECT variation_name FROM brand_variations WHERE brand_id = ?", [$project_id]);
    $name_variations = array_column($name_variations, 'variation_name');
    $name_variations[] = $prompt['business_name'];

    // Fetch domain variations
    $domain_variations = $db->fetchAll("SELECT variation_domain FROM domain_variations WHERE brand_id = ?", [$project_id]);
    $domain_variations = array_column($domain_variations, 'variation_domain');
    $domain_variations[] = $prompt['website_url'];

    // Call DataforSEO API
    if ($platform === 'google_ai_mode') {
        $url = "https://api.dataforseo.com/v3/serp/google/ai_mode/live/advanced";
        $task = [
            "keyword" => $prompt_text,
            "location_name" => $location_name,
            "language_name" => "English",
            "device" => "desktop",
            "visual_elements" => true,
            "calculate_rectangles" => true
        ];
    } else {
        $url = "https://api.dataforseo.com/v3/ai_optimization/{$platform}/llm_responses/live";
        $task = [
            "user_prompt" => $prompt_text,
            "model_name" => $model_version
        ];

        if ($web_search_supported) {
            $task["web_search"] = true;
            if ($platform === 'chat_gpt') {
                $task["web_search_country_iso_code"] = $country_code;
            }
        }
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, DATAFORSEO_LOGIN . ":" . DATAFORSEO_PASSWORD);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([$task]));
    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 || !$response) {
        throw new Exception("DataforSEO API Error (HTTP $http_code)");
    }

    $result_data = json_decode((string)$response, true);
    if (!isset($result_data['tasks'][0]['result'][0])) {
        throw new Exception("Invalid API response");
    }

    $result_item = $result_data['tasks'][0]['result'][0];
    
    $ai_response_text = "No text response available.";
    $references = [];
    $snapshot_url = $result_item['screenshot_url'] ?? null;

    if ($platform === 'google_ai_mode') {
        if (isset($result_item['items'])) {
            foreach ($result_item['items'] as $item) {
                if ($item['type'] === 'ai_overview') {
                    $ai_response_text = $item['text'] ?? $item['markdown'] ?? "AI Overview generated.";
                    $references = $item['links'] ?? $item['references'] ?? [];
                    break;
                }
            }
        }
    } else {
        $ai_response_text = $result_item['items'][0]['sections'][0]['text'] ?? $result_item['answer'] ?? $result_item['text'] ?? $result_item['content'] ?? $ai_response_text;
        if (isset($result_item['items'])) {
            foreach ($result_item['items'] as $item) {
                if (isset($item['sections'])) {
                    foreach ($item['sections'] as $section) {
                        if (isset($section['annotations'])) $references = array_merge($references, $section['annotations']);
                    }
                }
                if (isset($item['references'])) $references = array_merge($references, $item['references']);
            }
        }
        if (empty($references)) $references = $result_item['references'] ?? $result_item['sources'] ?? [];
    }
    
    $extracted_links = [];
    $rank = 1;
    foreach ($references as $ref) {
        $url = $ref['url'] ?? '';
        $extracted_links[] = [
            'rank' => $rank++,
            'title' => $ref['title'] ?? 'No Title',
            'url' => $url,
            'domain' => parse_url($url, PHP_URL_HOST) ?? 'Unknown'
        ];
    }

    // Deduplicate
    $unique_links = [];
    $seen_urls = [];
    foreach ($extracted_links as $link) {
        if (!empty($link['url']) && !in_array($link['url'], $seen_urls)) {
            $seen_urls[] = $link['url'];
            $unique_links[] = $link;
        }
    }
    $extracted_links = $unique_links;

    // Analytics
    $clean_response = strtolower((string)$ai_response_text);
    $brand_mentions = 0;
    foreach ($name_variations as $name) {
        if (!empty($name)) $brand_mentions += substr_count($clean_response, strtolower((string)$name));
    }

    $domain_citations_count = 0;
    $normalized_domains = [];
    foreach ($domain_variations as $domain) {
        $d = strtolower(preg_replace('/^https?:\/\/(www\.)?/', '', rtrim((string)$domain, '/')));
        if ($d) $normalized_domains[] = $d;
    }

    foreach ($extracted_links as $link) {
        $link_compare = strtolower(preg_replace('/^https?:\/\/(www\.)?/', '', $link['url']));
        foreach ($normalized_domains as $domain) {
            if (strpos($link_compare, $domain) !== false) {
                $domain_citations_count++;
                break;
            }
        }
    }

    // Save Run
    $db->beginTransaction();
    $full_model_name = $platform_label . " (" . $model_version . ")";
    $run_id = $db->insert('prompt_runs', [
        'prompt_id'    => (int)$prompt_id,
        'model'        => $full_model_name,
        'ai_response'  => $ai_response_text,
        'snapshot_url' => $snapshot_url
    ]);

    foreach ($extracted_links as $link) {
        $db->insert('prompt_run_links', [
            'run_id' => $run_id,
            'rank'   => $link['rank'],
            'title'  => $link['title'],
            'url'    => $link['url'],
            'domain' => $link['domain']
        ]);
    }

    // Update prompt stats
    $seo_data = SeoApiHelper::getSeoMetrics($prompt_text, $location_name);
    $vol = $seo_data['volume'] ?? (strlen($prompt_text) * 5 + 10);
    
    // Simple Visibility Score calculation
    $vis_score = min(100, ($brand_mentions * 15) + ($domain_citations_count * 25));

    $db->update('brand_prompts', [
        'brand_mentions'   => $brand_mentions,
        'domain_citations' => $domain_citations_count,
        'total_citations'  => count($extracted_links),
        'visibility_score' => (int)$vis_score,
        'ai_volume'        => (int)$vol
    ], 'id = :id', ['id' => (int)$prompt_id]);

    $db->commit();

    echo json_encode([
        'success' => true,
        'ai_response' => nl2br(htmlspecialchars((string)$ai_response_text)),
        'links' => $extracted_links,
        'brand_mentions' => $brand_mentions,
        'domain_citations' => $domain_citations_count,
        'snapshot_url' => $snapshot_url
    ]);

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