<?php
session_start();
if (!isset($_SESSION['doctor_id'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

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

$question = $_POST['question'] ?? '';
if (empty($question)) {
    echo json_encode(['answer' => 'Please ask a question.']);
    exit();
}

// Groq API Key
$apiKey = "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";

// Prepare the payload
$payload = [
    "model" => "llama-3.3-70b-versatile",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a clinical AI assistant for doctors. Provide medical insights, possible conditions, treatment suggestions, and clinical guidance. Always remind that this is AI-generated and not a substitute for professional judgment."
        ],
        [
            "role" => "user",
            "content" => $question
        ]
    ],
    "temperature" => 0.4
];

// Initialize cURL
$ch = curl_init("https://api.groq.com/openai/v1/chat/completions");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . $apiKey,
        "Content-Type: application/json"
    ],
    CURLOPT_POSTFIELDS => json_encode($payload)
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo json_encode(['answer' => 'AI service temporarily unavailable.']);
    curl_close($ch);
    exit();
}

curl_close($ch);

$result = json_decode($response, true);
if (isset($result['choices'][0]['message']['content'])) {
    $answer = $result['choices'][0]['message']['content'];
    echo json_encode(['answer' => $answer]);
} else {
    echo json_encode(['answer' => 'Unable to process your request. Please try again.']);
}
?>