<?php

namespace App\Http\Controllers;

use App\Models\ApiCallLog;
use App\Models\UserApiKey;
use App\Models\User;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function dashboard()
    {
        $stats = [
            'total_calls_today' => ApiCallLog::whereDate('created_at', today())->count(),
            'active_keys' => UserApiKey::where('is_active', true)->count(),
            'total_users' => User::count(),
            'top_endpoints' => ApiCallLog::selectRaw('endpoint, count(*) as count')
                ->groupBy('endpoint')
                ->orderByDesc('count')
                ->limit(10)
                ->get(),
            'total_calls' => ApiCallLog::count(),
            'calls_last_7_days' => ApiCallLog::where('created_at', '>=', now()->subDays(7))->count(),
            //'my_api_key' => UserApiKey::where('key', '', auth()->user()->id)->first(),
            'users' => User::with(['apiKeys' => function ($query) {
            $query->withCount('apiCallLogs');
        }])->get(),

        ];

        return view('admin.dashboard', compact('stats'));
    }

    public function logs()
    {
        $logs = ApiCallLog::with('userApiKey.user')
            ->orderByDesc('created_at')
            ->paginate(50);

        return view('admin.logs', compact('logs'));
    }
}