<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AnalyticsEvent;
use App\Models\DailyUserActivity;
use App\Models\FileUpload;
use App\Models\ImageGeneration;
use App\Modules\Users\Models\User;
use App\Models\UserFeedback;
use App\Models\UserSubscription;
use App\Modules\Ai\Models\AiRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

/**
 * لوحة تحليلات Public Beta — مؤشرات نمو واستخدام.
 */
final class AnalyticsDashboardController extends Controller
{
    public function __invoke(): View
    {
        $today = now()->toDateString();
        $dauToday = DailyUserActivity::query()->whereDate('activity_date', $today)->count();

        $dauWeekUnique = (int) (DB::selectOne(
            'select count(distinct user_id) as c from daily_user_activity where activity_date >= ?',
            [now()->subDays(7)->toDateString()]
        )->c ?? 0);

        $usersTotal = User::query()->count();
        $newUsersWeek = User::query()->where('created_at', '>=', now()->subDays(7))->count();

        $aiMonth = AiRequest::query()->where('created_at', '>=', now()->startOfMonth())->count();
        $imagesMonth = ImageGeneration::query()->where('created_at', '>=', now()->startOfMonth())->count();
        $filesTotal = FileUpload::query()->count();

        $subsActive = UserSubscription::query()
            ->where('status', UserSubscription::STATUS_ACTIVE)
            ->where('starts_at', '<=', now())
            ->where(function ($w): void {
                $w->whereNull('ends_at')->orWhere('ends_at', '>=', now());
            })
            ->count();

        $topEvents = DB::table('analytics_events')
            ->where('created_at', '>=', now()->subDays(14))
            ->selectRaw('name, COUNT(*) as c')
            ->groupBy('name')
            ->orderByDesc('c')
            ->limit(12)
            ->get();

        $feedbackWeek = UserFeedback::query()->where('created_at', '>=', now()->subDays(7))->count();

        return view('admin.analytics', [
            'dauToday' => $dauToday,
            'dauWeekUnique' => $dauWeekUnique,
            'usersTotal' => $usersTotal,
            'newUsersWeek' => $newUsersWeek,
            'aiMonth' => $aiMonth,
            'imagesMonth' => $imagesMonth,
            'filesTotal' => $filesTotal,
            'subsActive' => $subsActive,
            'topEvents' => $topEvents,
            'feedbackWeek' => $feedbackWeek,
        ]);
    }
}
