<?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/AccessibilityService.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['content'])) {
        throw new Exception('Content is required for accessibility analysis');
    }

    $aiService = new AccessibilityService();
    $result = $aiService->analyzeAccessibility(
        $data['content'],
        $data['standards'] ?? ['WCAG_2_1']
    );

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

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

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

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