<?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 App\Livewire\Concerns\WithSorting;
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, WithSorting;

    #[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']);

        if ($this->sortBy === 'name_ar') {
            $query->join('employees', 'trainers.employee_id', '=', 'employees.id')
                  ->join('people', 'employees.person_id', '=', 'people.id')
                  ->orderBy('people.name_ar', $this->sortDir)
                  ->select('trainers.*');
        } else {
            $query->orderBy($this->sortBy, $this->sortDir);
        }

        $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,
        ]);
    }
}
