<?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/EssayEvaluationService.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['essay_content'])) {
        throw new Exception('Essay content is required');
    }

    if (empty($data['question_content'])) {
        throw new Exception('Question content is required for evaluation');
    }

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

    // Evaluate essay
    $evaluation = $aiService->evaluateEssay(
        $data['essay_content'],
        $data['question_content'],
        $data['rubric'] ?? null
    );

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

    $tokens = (strlen($data['essay_content']) + strlen($data['question_content'])) / 4;
    $cost = $tokens * 0.00002;

    $stmt->execute([
        $userId,
        $tokens,
        $cost,
        json_encode([
            'essay_length' => strlen($data['essay_content']),
            'question_length' => strlen($data['question_content'])
        ])
    ]);

    echo json_encode([
        'success' => true,
        'data' => $evaluation,
        'meta' => [
            'feature' => 'essay_evaluation',
            'tokens_estimated' => $tokens,
            'cost_estimated' => $cost
        ]
    ]);

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