<?php

namespace App\Livewire\Portal;

use App\Domain\Document\Models\Document;
use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Models\ServiceRequest;
use App\Livewire\Portal\Concerns\PortalScreen;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

/**
 * The account: who this is, what documents are on file, what has been asked
 * for, and the controls that belong to the person rather than the academy.
 */
#[Layout('layouts.portal')]
#[Title('حسابي')]
class PortalAccount extends Component
{
    use PortalScreen;

    /** profile | documents | requests | settings */
    #[Url(as: 'tab')]
    public string $tab = 'profile';

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

    public function updatedTab(): void
    {
        if (! in_array($this->tab, ['profile', 'documents', 'requests', 'settings'], true)) {
            $this->tab = 'profile';
        }
    }

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

        return view('livewire.portal.portal-account', [
            'profiles' => $this->portal()->switchableProfiles(),
            'user' => $user,

            'documents' => $this->tab === 'documents'
                ? Document::where('documentable_type', Participant::class)
                    ->whereIn('documentable_id', $familyIds)
                    ->with('documentable.person')
                    ->orderByDesc('created_at')
                    ->get()
                : collect(),

            'requests' => $this->tab === 'requests'
                // The closure is load-bearing: an unwrapped orWhere lets the
                // first branch escape the tenant global scope, which is the
                // exact shape of the bug in PermissionService::224.
                ? ServiceRequest::where(function ($q) use ($user, $familyIds) {
                    $q->where('user_id', $user?->id)->orWhereIn('participant_id', $familyIds);
                })
                    ->with('participant.person')
                    ->orderByDesc('created_at')
                    ->limit(30)
                    ->get()
                : collect(),
        ]);
    }
}
