<?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/PerformanceAnalysisService.php';

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

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

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

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

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

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

    if (!$data || empty($data['performance_data'])) {
        throw new Exception('Performance data is required');
    }

    $aiService = new PerformanceAnalysisService();
    $result = $aiService->analyzePerformance(
        $data['performance_data'],
        $data['period'] ?? 'month'
    );

    $tokens = strlen(json_encode($data['performance_data'])) / 4;
    $cost = $tokens * 0.00002;

    $stmt = $db->prepare("
        INSERT INTO ai_usage_logs (user_id, feature, tokens_used, cost, metadata, created_at)
        VALUES (?, 'performance_analysis', ?, ?, ?, NOW())
    ");
    $stmt->execute([$userId, $tokens, $cost, json_encode(['data_points' => count($data['performance_data'])])]);

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

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