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

// Get request body
$data = json_decode(file_get_contents("php://input"), true);
$symptoms = trim($data["symptoms"] ?? "");

if (!$symptoms) {
    echo json_encode(["error" => ["message" => "No symptoms provided."]]);
    exit;
}

// Your 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 UHD platform. Provide general medical guidance, possible conditions, and self-care advice. Always include a disclaimer that this is not a medical diagnosis and recommend consulting a doctor."
        ],
        [
            "role" => "user",
            "content" => $symptoms
        ]
    ],
    "temperature" => 0.4,
    "max_tokens" => 800
];

// 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),
    CURLOPT_TIMEOUT => 30
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo json_encode(["error" => ["message" => curl_error($ch)]]);
} else {
    echo $response;
}

curl_close($ch);
?>