<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Cargar config
$config_file = __DIR__ . '/../config.php';
if(file_exists($config_file)) require_once $config_file;

$input = json_decode(file_get_contents('php://input'), true);
$question = isset($input['question']) ? trim($input['question']) : '';

if(empty($question)) {
    echo json_encode(['error' => 'Pregunta vacía']);
    exit;
}

$api_key = defined('CLAUDE_API_KEY') ? CLAUDE_API_KEY : '';
if(empty($api_key)) {
    echo json_encode(['response' => 'Configura tu Claude API Key en ⚙ Configurar APIs para activar AVI.']);
    exit;
}

$system_prompt = "Eres AVI, el asistente inteligente de DIMARK, una agencia de marketing digital en Medellín, Colombia, especializada en Meta Ads, Google Ads, SEO, WordPress y Shopify. Eres experto en marketing digital, análisis de campañas y optimización. Responde siempre en español, de forma concisa y accionable. DIMARK es partner oficial de Google Ads y Meta Ads.";

$payload = [
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 600,
    'system' => $system_prompt,
    'messages' => [
        ['role' => 'user', 'content' => $question]
    ]
];

$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'x-api-key: ' . $api_key,
        'anthropic-version: 2023-06-01'
    ],
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => true
]);

$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if($http_code !== 200) {
    echo json_encode(['response' => 'Error al conectar con AVI. Verifica tu API Key.']);
    exit;
}

$data = json_decode($result, true);
$response = isset($data['content'][0]['text']) ? $data['content'][0]['text'] : 'Sin respuesta de AVI.';
echo json_encode(['response' => $response]);
