<?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/TranslationService.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 translation');
    }

    if (empty($data['target_language'])) {
        throw new Exception('Target language is required');
    }

    $aiService = new TranslationService();
    $result = $aiService->translateContent(
        $data['content'],
        $data['target_language'],
        $data['context'] ?? 'educational'
    );

    $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 (?, 'translation', ?, ?, ?, NOW())
    ");
    $stmt->execute([$userId, $tokens, $cost, json_encode([
        'content_length' => strlen($data['content']),
        'target_language' => $data['target_language']
    ])]);

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

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