<?php
/**
 * AI Usage Statistics
 * GET /v1/dashboard/ai-usage
 * Returns token consumption and cost breakdown
 */

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

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

try {
    // Overall stats
    $overall = AI::getUsageStats();

    // Today's usage
    $todayStmt = $db->query("
        SELECT 
            COUNT(*) as requests,
            COALESCE(SUM(total_tokens), 0) as tokens,
            COALESCE(SUM(cost_jod), 0) as cost_jod
        FROM ai_usage_log
        WHERE DATE(created_at) = CURDATE()
    ");
    $today = $todayStmt->fetch();

    // This month
    $monthStmt = $db->query("
        SELECT 
            COUNT(*) as requests,
            COALESCE(SUM(total_tokens), 0) as tokens,
            COALESCE(SUM(cost_jod), 0) as cost_jod
        FROM ai_usage_log
        WHERE MONTH(created_at) = MONTH(NOW()) AND YEAR(created_at) = YEAR(NOW())
    ");
    $month = $monthStmt->fetch();

    // Daily breakdown (last 30 days)
    $dailyStmt = $db->query("
        SELECT 
            DATE(created_at) as date,
            COUNT(*) as requests,
            SUM(total_tokens) as tokens,
            SUM(cost_jod) as cost_jod
        FROM ai_usage_log
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date DESC
    ");
    $daily = $dailyStmt->fetchAll();

    json_success([
        'overall' => [
            'total_requests' => (int)($overall['total_requests'] ?? 0),
            'total_tokens' => (int)($overall['total_tokens'] ?? 0),
            'total_cost_usd' => round((float)($overall['total_cost_usd'] ?? 0), 4),
            'total_cost_jod' => round((float)($overall['total_cost_jod'] ?? 0), 4),
            'avg_tokens_per_invoice' => round((float)($overall['avg_tokens_per_request'] ?? 0)),
            'avg_cost_per_invoice_jod' => round((float)($overall['avg_cost_jod_per_request'] ?? 0), 6),
        ],
        'today' => [
            'requests' => (int)($today['requests'] ?? 0),
            'tokens' => (int)($today['tokens'] ?? 0),
            'cost_jod' => round((float)($today['cost_jod'] ?? 0), 4),
        ],
        'this_month' => [
            'requests' => (int)($month['requests'] ?? 0),
            'tokens' => (int)($month['tokens'] ?? 0),
            'cost_jod' => round((float)($month['cost_jod'] ?? 0), 4),
        ],
        'daily_breakdown' => $daily,
    ], 'إحصائيات استخدام الذكاء الاصطناعي');

} catch (\Exception $e) {
    error_log("AI Usage Stats Error: " . $e->getMessage() . " | " . $e->getTraceAsString());
    safe_error($e, 'dashboard/ai_usage', 'خطأ في جلب إحصائيات الذكاء الاصطناعي.');
}
