<?php
use CAE\Lib\Database;
use CAE\Lib\Response;

$filename = $_POST['filename'] ?? '';
$url = $_POST['url'] ?? '';
$domain = $_POST['domain'] ?? '';

if (empty($filename) && empty($url)) {
    Response::error('Filename or URL is required');
}

try {
    // Using Gemini 3.1 Pro Preview for the most advanced multimodal (Vision + Text) capabilities
    $platform = 'gemini';
    $model = 'gemini-3.1-pro-preview';
    $endpoint = "https://api.dataforseo.com/v3/ai_optimization/{$platform}/llm_responses/live";

    $short_url = (strlen($url) > 150) ? substr($url, 0, 147) . '...' : $url;
    
    $user_prompt = "Analyze image: {$short_url}. Context domain: {$domain}. Suggest Alt Text (describe visual content, max 125 chars, no 'image of') and SEO Title (catchy, max 60 chars). Return ONLY a JSON object: {\"alt\":\"...\", \"title\":\"...\"}";

    $post_data = [["user_prompt" => $user_prompt, "model_name" => $model]];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $endpoint);
    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 ($response === false) {
        throw new Exception("CURL Error");
    }

    $ai_data = json_decode($response, true);
    $alt = '';
    $title = '';

    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 = $item['sections'][0]['text'];
                
                if (preg_match('/\{.*\}/is', $ai_text, $matches)) {
                    $json_data = json_decode($matches[0], true);
                    if ($json_data) {
                        $alt = $json_data['alt'] ?? '';
                        $title = $json_data['title'] ?? '';
                    }
                }
                
                if (empty($alt) || empty($title)) {
                    $ai_text = str_replace(['{', '}', '"'], '', $ai_text);
                    $lines = explode(',', $ai_text);
                    foreach($lines as $line) {
                        $parts = explode(':', $line);
                        if (count($parts) >= 2) {
                            $key = strtolower(trim($parts[0]));
                            $val = trim($parts[1]);
                            if ($key === 'alt') $alt = $val;
                            if ($key === 'title') $title = $val;
                        }
                    }
                }
                break;
            }
        }
    }

    if (empty($alt)) $alt = ucwords(str_replace(['-', '_'], ' ', $filename));
    if (empty($title)) $title = ucwords(str_replace(['-', '_'], ' ', $filename));

    // Store in History Table
    try {
        $db = Database::getInstance();
        $db->insert('image_optimization_history', [
            'user_id'           => 1, // Defaulting to 1 as per Content Engine's current state (usually single user or session handled elsewhere)
            'original_filename' => $filename,
            'source_url'        => $url,
            'target_domain'     => $domain,
            'suggested_alt'     => $alt,
            'suggested_title'   => $title
        ]);
    } catch (Exception $db_e) {
        // Silently log or ignore
    }

    Response::success([
        'alt' => $alt,
        'title' => $title
    ]);

} catch (Exception $e) {
    Response::error($e->getMessage());
}
