<?php

namespace Modules\Member;

use Modules\Dashboard\Block;
use App\Member\Membership;
use Illuminate\Database\Eloquent\Builder;

class AgeGroupCountBlock extends Block
{

    public $groups;

    /**
     * @return Builder<Membership>
     */
    protected function memberQuery(): Builder
    {
        return Membership::select('subactivities.slug', 'subactivities.name')
            ->selectRaw('COUNT(member_id) AS count')
            ->join('activities', 'memberships.activity_id', 'activities.id')
            ->join('subactivities', 'memberships.subactivity_id', 'subactivities.id')
            ->isAgeGroup()
            ->isMember()
            ->active()
            ->groupBy('subactivities.slug', 'subactivities.name')
            ->orderBy('subactivity_id');
    }

    /**
     * @return Builder<Membership>
     */
    protected function leaderQuery(): Builder
    {
        return Membership::selectRaw('"leiter" AS slug, "Leiter" AS name, COUNT(member_id) AS count')
            ->join('activities', 'memberships.activity_id', 'activities.id')
            ->join('subactivities', 'memberships.subactivity_id', 'subactivities.id')
            ->active()
            ->isLeader();
    }

    public function mount(): void
    {
        $this->groups = [
            ...$this->memberQuery()->get(),
            ...$this->leaderQuery()->get(),
        ];
    }

    public function title(): string
    {
        return 'Gruppierungs-Verteilung';
    }

    public function groupColor(string $slug): string
    {
        return data_get([
            'biber' => 'text-biber',
            'woelfling' => 'text-woelfling',
            'jungpfadfinder' => 'text-jungpfadfinder',
            'pfadfinder' => 'text-pfadfinder',
            'rover' => 'text-rover',
            'leiter' => 'text-leiter',
        ], $slug);
    }

    public function render(): string
    {
        return <<<'HTML'
            <div>
                @foreach($groups as $group)
                <div class="flex mt-2 items-center leading-none text-gray-100">
                    <x-ui::sprite class="w-4 h-4 mr-2 {{ $this->groupColor($group->slug) }}" src="lilie"></x-ui::sprite>
                    <span class="grow">{{$group->name}}</span>
                    <span>{{$group->count}}</span>
                </div>
                @endforeach
            </div>
        HTML;
    }
}