<?php
// FILE PATH: Teacher/generate_ai.php
session_start();
require_once "../config/database.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['topic'])) {
    
    // 1. YOUR API KEY (Ensure no spaces before or after)
    $apiKey = "AIzaSyBBNo_dOJM9J1J6XKQIve9QUvRNMgjLz78"; 
    
    $topic = htmlspecialchars($_POST['topic']);
    $count = (int)$_POST['count'];

    // 2. THE STABLE URL (v1/gemini-1.5-flash)
    $url = "https://generativelanguage.googleapis.com/v1/models/gemini-2.5-flash:generateContent?key=" . $apiKey;

    $prompt = "Generate $count multiple-choice questions about '$topic'. 
               Format:
               Question?
               A. Option
               B. Option
               C. Option
               D. Option
               ANSWER: [Letter]
               
               One empty line between questions. No bold, no intro.";

    $payload = [
        "contents" => [
            ["parts" => [["text" => $prompt]]]
        ]
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Give it time to think

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        echo "Connection Error: " . $curlError;
        exit;
    }

    $result = json_decode($response, true);

    // 3. LOGICAL CHECK OF THE RESPONSE
    if ($httpCode === 200 && isset($result['candidates'][0]['content']['parts'][0]['text'])) {
        $text = $result['candidates'][0]['content']['parts'][0]['text'];
        // Remove any markdown code blocks the AI might wrap the text in
        echo trim(str_replace(['```', 'html', 'text'], '', $text));
    } else {
        // This will tell us if it's a Key issue, a Model issue, or a Billing issue
        $errMsg = $result['error']['message'] ?? "Unknown Error Occurred";
        echo "System Error (Code $httpCode): " . $errMsg;
        
        if ($httpCode === 403) {
            echo " | Suggestion: Check if your API Key is restricted in Google AI Studio.";
        }
        if ($httpCode === 404) {
            echo " | Suggestion: Try changing the URL model to 'gemini-1.5-pro'.";
        }
    }
}