<?php
if (!defined('APP_STARTED')) {
    die('No direct access');
}

/**
 * Analyse NLP via GPT (PHP 5 compatible)
 */
function aiAnalyze($message, $context = array()) {

    $apiKey = getenv('OPENAI_API_KEY');
    if (!$apiKey) {
        return array('intent' => 'unknown');
    }

    // contexte sécurisé
    $mode = isset($context['mode']) ? $context['mode'] : 'none';

    $prompt = <<<PROMPT
Tu es un assistant IA pour un site d'annonces.

Analyse le message utilisateur et retourne UNIQUEMENT un JSON valide.

INTENTS:
- greeting
- search
- add
- continue_add
- help
- unknown

Champs possibles :
- category
- city
- min_price
- max_price
- keywords
- titre
- description
- categorie
- ville
- prix
- tel

Contexte:
"$mode"

Message:
"$message"
PROMPT;

    $payload = array(
        "model" => "gpt-4o-mini",
        "messages" => array(
            array("role" => "system", "content" => "Tu réponds uniquement en JSON valide"),
            array("role" => "user", "content" => $prompt)
        ),
        "temperature" => 0.2
    );

    $ch = curl_init("https://api.openai.com/v1/chat/completions");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer ".$apiKey,
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);
    curl_close($ch);

    $json = json_decode($response, true);

    if (!isset($json['choices'][0]['message']['content'])) {
        return array('intent' => 'unknown');
    }

    return json_decode($json['choices'][0]['message']['content'], true);
}
