<?php

namespace App\Livewire\Admin;

use App\Domain\Shared\Models\Academy;
use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('لوحة المدير العام')]
class SuperAdminPanel extends Component
{
    public function mount(): void
    {
        $this->authorize('super_admin.access');
    }

    public function render()
    {
        // Deliberately cross-tenant, and deliberately narrow with it.
        //
        // `academies` is the tenant root: it carries no academy scope and no
        // branch scope, so a plain query is already every academy. Only `users`
        // needs an opt-out, and only from the academy scope — the route sits in
        // config('branch_scope.unscoped_routes'), so branch enforcement is off
        // here regardless. The blanket withoutGlobalScopes() this replaces also
        // dropped SoftDeletingScope, which quietly counted deleted academies and
        // deleted users into the headline totals.
        //
        // The withCount opt-out is the one that was actually load-bearing: a
        // relation count builds a fresh User query, so the academy scope applied
        // inside it and every academy except the one being viewed reported zero
        // users.
        $academies = Academy::query()
            ->withCount(['users' => fn ($q) => $q->withoutGlobalScope('academy')])
            ->get();

        return view('livewire.admin.super-admin-panel', [
            'academies' => $academies,
            'totalUsers' => User::withoutGlobalScope('academy')->count(),
            'totalAcademies' => Academy::query()->count(),
        ]);
    }
}
