<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\SubscriptionPayment;
use App\Models\SubscriptionPlan;
use App\Models\SubscriptionRequest;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function __invoke()
    {
        $today = Carbon::today();

        $totalCompanies = Company::count();
        $activeCompanies = Company::where('status', 'active')->count();
        $suspendedCompanies = Company::where('status', 'suspended')->count();
        $totalUsers = User::whereNotNull('company_id')->count();

        $expiringSoon = Company::query()
            ->whereNotNull('licence_expire_on')
            ->whereBetween('licence_expire_on', [$today, $today->copy()->addDays(30)])
            ->count();

        $pendingOfflineRequests = SubscriptionRequest::query()
            ->where('status', 'pending')
            ->count();

        $revenueThisMonth = (float) SubscriptionPayment::query()
            ->where('status', 'completed')
            ->whereMonth('paid_at', now()->month)
            ->whereYear('paid_at', now()->year)
            ->sum('amount');

        $revenueAll = (float) SubscriptionPayment::query()
            ->where('status', 'completed')
            ->sum('amount');

        $newThisMonth = Company::query()
            ->whereYear('created_at', now()->year)
            ->whereMonth('created_at', now()->month)
            ->count();

        $recentCompanies = Company::with('subscriptionPlan')
            ->orderByDesc('created_at')
            ->limit(8)
            ->get();

        $expiringCompanies = Company::with('subscriptionPlan')
            ->whereNotNull('licence_expire_on')
            ->whereBetween('licence_expire_on', [$today, $today->copy()->addDays(30)])
            ->orderBy('licence_expire_on')
            ->limit(8)
            ->get();

        $pendingRequests = SubscriptionRequest::with(['company', 'subscriptionPlan'])
            ->where('status', 'pending')
            ->orderByDesc('created_at')
            ->limit(6)
            ->get();

        $planCounts = Company::query()
            ->select('subscription_plan_id', DB::raw('count(*) as total'))
            ->groupBy('subscription_plan_id')
            ->get()
            ->keyBy('subscription_plan_id');

        $companiesByPlan = SubscriptionPlan::query()
            ->orderBy('base_price_yearly')
            ->orderBy('name')
            ->get()
            ->map(fn (SubscriptionPlan $plan) => [
                'id' => $plan->id,
                'plan' => $plan->name,
                'yearly' => $plan->effectiveYearlyPrice(),
                'seats' => $plan->employee_limit,
                'total' => (int) ($planCounts->get($plan->id)->total ?? 0),
                'is_custom' => (bool) $plan->is_custom,
            ]);

        $recentPayments = SubscriptionPayment::with(['company', 'subscriptionPlan'])
            ->orderByDesc('created_at')
            ->limit(6)
            ->get();

        return view('superadmin.dashboard', compact(
            'totalCompanies',
            'activeCompanies',
            'suspendedCompanies',
            'totalUsers',
            'expiringSoon',
            'pendingOfflineRequests',
            'revenueThisMonth',
            'revenueAll',
            'newThisMonth',
            'recentCompanies',
            'expiringCompanies',
            'pendingRequests',
            'companiesByPlan',
            'recentPayments'
        ));
    }
}
