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

    $aiService = new LearningPathService();
    $result = $aiService->generateLearningPath(
        $data['course_content'],
        $data['student_level'] ?? 'intermediate'
    );

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

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

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

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