<?php
// Check if request is POST (AJAX from frontend)
if($_SERVER['REQUEST_METHOD'] === 'POST'){
    header('Content-Type: application/json');
    $input = json_decode(file_get_contents('php://input'), true);
    $question = $input['question'] ?? '';

    if(!$question){
        echo json_encode(['answer'=>'No question received']);
        exit;
    }

    // Groq API call
    $apiKey = "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"; // Replace with your Groq Free API Key

    $payload = [
        "model" => "llama-3.3-70b-versatile",
        "messages" => [
            ["role"=>"system","content"=>"You are a helpful AI tutor for StudyTrack students."],
            ["role"=>"user","content"=>$question]
        ]
    ];

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

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

    if(!$response){
        echo json_encode(['answer'=>'Failed to get response from Groq API']);
        exit;
    }

    $data = json_decode($response, true);
    $answer = $data['choices'][0]['message']['content'] ?? 'No answer';

    echo json_encode(['answer'=>$answer]);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>StudyTrack AI Tutor</title>
<style>
  body { font-family: Arial, sans-serif; background:#f7f7f7; display:flex; justify-content:center; align-items:center; height:100vh; }
  #chat-container { width:400px; background:#fff; border-radius:8px; box-shadow:0 4px 10px rgba(0,0,0,0.1); padding:20px; }
  #chat-box { height:300px; overflow-y:auto; border:1px solid #ddd; padding:10px; border-radius:5px; background:#fafafa; margin-bottom:10px; }
  .message { margin:5px 0; }
  .user { color:blue; font-weight:bold; }
  .bot { color:green; font-weight:bold; }
  input { width:calc(100% - 70px); padding:10px; border-radius:5px; border:1px solid #ccc; }
  button { padding:10px 15px; border:none; border-radius:5px; background:blue; color:#fff; cursor:pointer; }
</style>
</head>
<body>

<div id="chat-container">
  <h2>StudyTrack AI Tutor</h2>
  <div id="chat-box"></div>
  <input type="text" id="user-input" placeholder="Ask your question..." />
  <button onclick="sendMessage()">Send</button>
</div>

<script>
const chatBox = document.getElementById('chat-box');
const userInput = document.getElementById('user-input');

async function sendMessage() {
    const text = userInput.value.trim();
    if(!text) return;
    
    // Show user message
    const userMsg = document.createElement('div');
    userMsg.className = 'message user';
    userMsg.innerText = "You: " + text;
    chatBox.appendChild(userMsg);
    
    userInput.value = '';
    chatBox.scrollTop = chatBox.scrollHeight;

    // Call same page (POST)
    const res = await fetch('', {
        method:'POST',
        headers:{ 'Content-Type':'application/json' },
        body: JSON.stringify({ question: text })
    });

    const data = await res.json();

    // Show bot message
    const botMsg = document.createElement('div');
    botMsg.className = 'message bot';
    botMsg.innerText = "AI: " + data.answer;
    chatBox.appendChild(botMsg);
    chatBox.scrollTop = chatBox.scrollHeight;
}
</script>

</body>
</html>