<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\User;
use App\Models\SubscriptionPlan;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function __invoke()
    {
        $totalCompanies = Company::count();
        $activeCompanies = Company::where('status', 'active')->count();
        $totalUsers = User::whereNotNull('company_id')->count();
        $trialCompanies = Company::whereNotNull('trial_ends_at')
            ->where('trial_ends_at', '>', Carbon::now())
            ->count();
        $expiringSoon = Company::where('status', 'active')
            ->whereNotNull('licence_expire_on')
            ->whereBetween('licence_expire_on', [Carbon::today(), Carbon::today()->addDays(30)])
            ->count();
        $newThisMonth = Company::whereMonth('created_at', Carbon::now()->month)->count();

        $recentCompanies = Company::with('subscriptionPlan')
            ->orderByDesc('created_at')
            ->limit(10)
            ->get();

        $planCounts = Company::select('subscription_plan_id', DB::raw('count(*) as total'))
            ->groupBy('subscription_plan_id')
            ->get()
            ->keyBy('subscription_plan_id');
        $companiesByPlan = SubscriptionPlan::orderBy('base_price_monthly')->get()
            ->map(fn ($plan) => ['plan' => $plan->name, 'total' => $planCounts->get($plan->id)->total ?? 0]);

        $plans = SubscriptionPlan::where('active', true)->orderBy('base_price_monthly')->get();

        return view('superadmin.dashboard', compact(
            'totalCompanies',
            'activeCompanies',
            'totalUsers',
            'trialCompanies',
            'expiringSoon',
            'newThisMonth',
            'recentCompanies',
            'companiesByPlan',
            'plans'
        ));
    }
}
