<?php

namespace App\Livewire\Portal;

use App\Domain\Event\Models\Event;
use App\Domain\Event\Models\EventRegistration;
use App\Domain\Identity\Models\Branch;
use App\Domain\Training\Models\TrainingProgram;
use App\Domain\Website\Models\WebsiteNews;
use App\Livewire\Portal\Concerns\PortalScreen;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

/**
 * Everything the academy publishes: programmes, events, news, branches.
 *
 * The content here is the same `website_news` and `events` the public site
 * reads — deliberately. A second CMS for the app would be a second migration
 * surface forever, and the channel column (S10) is what decides which of the
 * two a given item appears on.
 */
#[Layout('layouts.portal')]
#[Title('الأكاديمية')]
class PortalAcademy extends Component
{
    use PortalScreen;

    /** news | events | programs | branches */
    #[Url(as: 'tab')]
    public string $tab = 'news';

    public function mount(): void
    {
        $this->authorizePortal();
    }

    public function updatedTab(): void
    {
        if (! in_array($this->tab, ['news', 'events', 'programs', 'branches'], true)) {
            $this->tab = 'news';
        }
    }

    public function render()
    {
        $familyIds = $this->familyParticipantIds();

        return view('livewire.portal.portal-academy', [
            'news' => $this->tab === 'news'
                ? WebsiteNews::whereNotNull('published_at')
                    ->where('published_at', '<=', now())
                    ->forChannel('app')
                    ->orderByDesc('published_at')
                    ->limit(20)
                    ->get()
                : collect(),

            'events' => $this->tab === 'events'
                ? Event::where('status', 'published')
                    ->where(fn ($q) => $q->whereNull('ends_at')->orWhere('ends_at', '>=', now()))
                    ->orderBy('starts_at')
                    ->limit(20)
                    ->get()
                : collect(),

            // event_registrations linked only a person_id, so "which of my
            // children is registered" was unanswerable as modelled. S1 added
            // participant_id; this is the first screen that needs it.
            'myRegistrations' => $this->tab === 'events'
                ? EventRegistration::whereIn('participant_id', $familyIds)
                    ->pluck('status', 'event_id')
                : collect(),

            'programs' => $this->tab === 'programs'
                ? TrainingProgram::where('is_active', true)
                    ->with('activity')
                    ->orderBy('name_ar')
                    ->limit(30)
                    ->get()
                : collect(),

            'branches' => $this->tab === 'branches'
                ? Branch::where('is_active', true)->orderByDesc('is_main')->get()
                : collect(),
        ]);
    }
}
