<?php

namespace App\Livewire\HR;

use App\Domain\HR\Enums\CompensationModel;
use App\Domain\HR\Enums\TrainerStatus;
use App\Domain\HR\Models\Trainer;
use App\Domain\Identity\Services\PermissionService;
use App\Domain\Training\Models\Activity;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('المدربين')]
class TrainerList extends Component
{
    use WithPagination;

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

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

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

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

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

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

    public function render()
    {
        $query = Trainer::with(['employee.person', 'employee.branch', 'person'])
            ->latest();

        $query = app(PermissionService::class)->applyScope($query, auth()->user(), 'trainers.list');

        if ($this->search) {
            $search = $this->search;
            $query->where(function ($q) use ($search) {
                $q->where('trainer_number', 'ilike', "%{$search}%")
                    ->orWhereHas('employee.person', function ($pq) use ($search) {
                        $pq->where('name_ar', 'ilike', "%{$search}%")
                            ->orWhere('name', 'ilike', "%{$search}%");
                    })
                    ->orWhereHas('person', function ($pq) use ($search) {
                        $pq->where('name_ar', 'ilike', "%{$search}%")
                            ->orWhere('name', 'ilike', "%{$search}%");
                    });
            });
        }

        if ($this->status) {
            $query->where('status', $this->status);
        }

        if ($this->compensationModel) {
            $query->where('compensation_model', $this->compensationModel);
        }

        $activities = Activity::where('is_active', true)->orderBy('name_ar')->get(['id', 'name_ar', 'color']);

        return view('livewire.hr.trainer-list', [
            'trainers' => $query->paginate(20),
            'statuses' => TrainerStatus::cases(),
            'compensationModels' => CompensationModel::cases(),
            'activities' => $activities,
        ]);
    }
}
