<?php

namespace App\Livewire\Evaluations;

use App\Domain\Training\Enums\EvaluationStatus;
use App\Domain\Training\Models\Evaluation;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('التقييمات')]
class EvaluationList extends Component
{
    use WithPagination;

    #[Url]
    public string $search = '';

    #[Url]
    public string $status = '';

    #[Url]
    public string $groupId = '';

    public function mount(): void
    {
        $this->authorize('evaluations.list');
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatus(): void
    {
        $this->resetPage();
    }

    public function updatedGroupId(): void
    {
        $this->resetPage();
    }

    public function render()
    {
        $query = Evaluation::query()
            ->with(['participant.person', 'group', 'evaluator'])
            ->when($this->search, fn ($q) => $q->whereHas('participant.person', fn ($pq) => $pq->where('name_ar', 'ilike', "%{$this->search}%")))
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->groupId, fn ($q) => $q->where('training_group_id', $this->groupId))
            ->orderByDesc('evaluation_date');

        $groups = \App\Domain\Training\Models\TrainingGroup::orderBy('name_ar')->get(['id', 'name_ar']);

        return view('livewire.evaluations.evaluation-list', [
            'evaluations' => $query->paginate(20),
            'groups' => $groups,
            'statuses' => EvaluationStatus::cases(),
        ]);
    }
}
