<?php
ob_start();
require_once __DIR__ . '/../config.php';

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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => 'Método no permitido. Solo se aceptan solicitudes POST.']);
        exit;
    }

    if (!defined('GEMINI_API_KEY') || empty(GEMINI_API_KEY)) {
        http_response_code(500);
        echo json_encode(['error' => 'La clave de API de Gemini no está configurada.']);
        exit;
    }
    
    $apiKey = GEMINI_API_KEY;
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(['error' => 'Formato de datos JSON inválido.']);
        exit;
    }
    
    // --- PROMPT (Mantenemos la versión en INGLÉS por mejor razonamiento) ---
    $prompt = "
    ROLE: Act as a Senior Direct Response Marketing Strategist. Your goal is to craft high-converting value propositions triggering immediate psychological buying impulses for a local B2C market.

    INPUT DATA:
    - Business: {$data['businessName']}
    - Context: {$data['businessDescription']}
    - Audience: {$data['clientTypes']}
    - Location: {$data['cities']}

    STRICT FORMATTING RULES:
    1. **NO MARKDOWN:** Do not use asterisks (**).
    2. **HTML ONLY:** Use `<strong>` for emphasis.
    3. **NO NEWLINES:** Single continuous string per field.

    TASK:
    Generate 2 Sales Angles (Pain/Relief & Status/Identity). For each angle provide SPANISH (ES) and ENGLISH (EN) versions.

    OUTPUT FORMAT:
    JSON object with keys: `option1_es`, `option1_en`, `option2_es`, `option2_en`.
    ";

    // --- CONEXIÓN API ---
    $apiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/' . GEMINI_MODEL . ':generateContent?key=' . $apiKey;
    
    $payload = [
        'contents' => [['parts' => [['text' => $prompt]]]],
        'generationConfig' => [
            'response_mime_type' => 'application/json',
            'response_schema' => [
                'type' => 'OBJECT',
                'properties' => [
                    'option1_es' => ['type' => 'STRING'],
                    'option1_en' => ['type' => 'STRING'],
                    'option2_es' => ['type' => 'STRING'],
                    'option2_en' => ['type' => 'STRING']
                ],
                'required' => ['option1_es', 'option1_en', 'option2_es', 'option2_en']
            ]
        ]
    ];
    
    $ch = curl_init($apiUrl);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($payload), CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_TIMEOUT => 90]);
    $response_ai = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($response_ai === false || $http_code !== 200) {
        http_response_code(502);
        echo json_encode(['error' => 'API Error', 'details' => json_decode($response_ai)]);
        exit;
    }

    $result_array = json_decode($response_ai, true);
    $raw_response_text = $result_array['candidates'][0]['content']['parts'][0]['text'] ?? '';
    $response_data = json_decode($raw_response_text, true);

    if ($response_data === null || !isset($response_data['option1_es'])) {
        http_response_code(500);
        echo json_encode(['error' => 'Invalid AI Response']);
        exit;
    }

    // --- 🛡️ IMPLEMENTACIÓN DEL PROTOCOLO DE LIMPIEZA NUCLEAR ---
    
    function cleanTextNuclear($text) {
        // 1. FASE CONSTRUCTIVA: Intentar salvar la negrita
        // Regex busca **texto** y lo convierte a <strong>texto</strong>
        // Se usa la flag 's' por si acaso la IA metió saltos de linea dentro de la negrita
        $text = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $text);
        
        // 2. FASE DESTRUCTIVA (NUCLEAR): Eliminar cualquier residuo
        // Si quedó algún asterisco suelto (*), o un markdown mal formado, se elimina.
        // Esto garantiza cumplimiento del estándar "Zero-Tolerance UI Garbage".
        $text = str_replace(['*', '#'], '', $text);
        
        // 3. FASE DE HIGIENE: Limpieza de espacios y saltos de línea
        $text = str_replace(["\r\n", "\r", "\n"], " ", $text); // Newlines a espacios
        $text = preg_replace('/\s+/', ' ', $text); // Espacios dobles a simples
        
        return trim($text);
    }

    // Ejecución del protocolo en todos los campos
    $response_data['option1_es'] = cleanTextNuclear($response_data['option1_es']);
    $response_data['option1_en'] = cleanTextNuclear($response_data['option1_en']);
    $response_data['option2_es'] = cleanTextNuclear($response_data['option2_es']);
    $response_data['option2_en'] = cleanTextNuclear($response_data['option2_en']);

    ob_end_clean();
    echo json_encode($response_data);
    exit;

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server Error: ' . $e->getMessage()]);
    exit;
} finally {
    while (ob_get_level() > 0) {
        ob_end_flush();
    }
}
?>