<?php
/**
 * AI Usage Log Endpoint
 * GET /api/v1/ai-usage/log
 *
 * Returns paginated log of all AI requests.
 */

use App\Core\Database;
use App\Middleware\RoleMiddleware;

$decoded = RoleMiddleware::require(['super_admin', 'admin']);

$db = Database::getInstance();

$page     = max(1, (int) ($_GET['page'] ?? 1));
$perPage  = min(50, max(10, (int) ($_GET['per_page'] ?? 20)));
$offset   = ($page - 1) * $perPage;
$tenantId = $decoded['tenant_id'];
$isSuperAdmin = $decoded['role'] === 'super_admin';

$tenantCondition = $isSuperAdmin ? "" : "WHERE a.tenant_id = ?";
$params = $isSuperAdmin ? [] : [$tenantId];

// Count
$countSql = "SELECT COUNT(*) FROM ai_usage_log a $tenantCondition";
$countStmt = $db->prepare($countSql);
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

// Fetch
$sql = "SELECT
            a.id, a.action_type, a.model_name,
            a.prompt_tokens, a.completion_tokens, a.total_tokens,
            a.estimated_cost, a.created_at
        FROM ai_usage_log a
        $tenantCondition
        ORDER BY a.created_at DESC
        LIMIT $perPage OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll(\PDO::FETCH_ASSOC);

// Translate action types
$actionLabels = [
    'invoice_extraction' => 'استخراج فاتورة',
    'voice_transcribe'   => 'تحويل صوت لنص',
    'voice_intent'       => 'تحليل أمر صوتي',
    'report_generation'  => 'توليد تقرير',
    'chatbot'            => 'محادثة ذكية',
];

foreach ($logs as &$log) {
    $log['action_label'] = $actionLabels[$log['action_type']] ?? $log['action_type'];
    $log['estimated_cost'] = round((float) $log['estimated_cost'], 6);
}

json_success([
    'logs'       => $logs,
    'pagination' => [
        'page'      => $page,
        'per_page'  => $perPage,
        'total'     => $total,
        'pages'     => ceil($total / $perPage),
    ],
]);
