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

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

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

if (!hasAnyRole(['instructor', 'admin', 'student'])) {
    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 summarization');
    }

    $aiService = new ContentSummarizationService();
    $result = $aiService->summarizeContent(
        $data['content'],
        $data['length'] ?? 'medium',
        $data['focus'] ?? null
    );

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

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

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