<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\Company;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();
        abort_unless($user->is_admin, 403);

        $group = $user->company->group;
        $companies = collect();

        if ($group) {
            $companies = Company::with(['subscription', 'admin'])
                ->withCount('users')
                ->where('company_group_id', $group->id)
                ->orderBy('name')
                ->get();
        } else {
            $user->company->load(['subscription', 'admin']);
            $user->company->loadCount('users');
            $companies = collect([$user->company]);
        }

        $stats = [
            'total'    => $companies->count(),
            'active'   => $companies->where('status', 'active')->count(),
            'expired'  => $companies->where('status', 'expired')->count(),
            'inactive' => $companies->whereIn('status', ['suspended', 'trial'])->count(),
        ];

        $groups = $group ? collect([$group->load(['companies' => fn ($q) => $q->orderBy('name')])]) : collect();

        return view('subscription.index', compact('stats', 'companies', 'groups', 'group'));
    }
}
