<?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/ContentAnalysisService.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 analysis');
    }

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

    // Perform content analysis
    $analysisTypes = $data['analysis_types'] ?? null;
    $result = $aiService->analyzeContent($data['content'], $analysisTypes);

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

    // Calculate approximate tokens (rough estimate)
    $tokens = strlen($data['content']) / 4; // Rough token estimation
    $cost = $tokens * 0.00002; // Approximate cost

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

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

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