<?php
session_start();
if (!isset($_SESSION['patient_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 (same as doctor's)
$apiKey = "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";

$payload = [
    "model" => "llama-3.3-70b-versatile",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a friendly health assistant for patients. Provide general health information, explain medical terms simply, and offer wellness advice. Always remind that you are not a doctor and they should consult a physician for serious concerns."
        ],
        [
            "role" => "user",
            "content" => $question
        ]
    ],
    "temperature" => 0.7
];

$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);
curl_close($ch);

$result = json_decode($response, true);
if (isset($result['choices'][0]['message']['content'])) {
    echo json_encode(['answer' => $result['choices'][0]['message']['content']]);
} else {
    echo json_encode(['answer' => 'I am having trouble responding. Please try again.']);
}
?>