<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';
require_once '../../includes/ai/QuestionGenerationService.php';

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

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Authentication required']);
    exit;
}

// Check if user is instructor or admin
if (!hasAnyRole(['instructor', 'admin'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Access denied']);
    exit;
}

$db = getDB();
$userId = $_SESSION['user_id'];
$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        exit;
    }

    // Get JSON input
    $data = json_decode(file_get_contents('php://input'), true);

    if (!$data) {
        throw new Exception('Invalid JSON data');
    }

    // Validate required fields
    if (empty($data['content'])) {
        throw new Exception('Content is required for question generation');
    }

    if (empty($data['question_types'])) {
        throw new Exception('Question types are required');
    }

    // Initialize AI service
    $aiService = new QuestionGenerationService();

    // Generate questions
    $questions = $aiService->generateQuestions(
        $data['content'],
        $data['question_types'],
        $data['count'] ?? 5,
        $data['difficulty'] ?? 'medium'
    );

    // Log the generation request
    $stmt = $db->prepare("
        INSERT INTO ai_usage_logs (user_id, feature, tokens_used, cost, metadata, created_at)
        VALUES (?, 'question_generation', ?, ?, ?, NOW())
    ");

    $tokens = strlen($data['content']) / 4 + (count($questions) * 100);
    $cost = $tokens * 0.00002;

    $stmt->execute([
        $userId,
        $tokens,
        $cost,
        json_encode([
            'content_length' => strlen($data['content']),
            'question_types' => $data['question_types'],
            'count' => count($questions)
        ])
    ]);

    echo json_encode([
        'success' => true,
        'data' => $questions,
        'meta' => [
            'feature' => 'question_generation',
            'questions_generated' => count($questions),
            'tokens_estimated' => $tokens,
            'cost_estimated' => $cost
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => $e->getMessage(),
        'feature' => 'question_generation'
    ]);
}
?>