<?php

namespace App\Livewire\HR;

use App\Domain\HR\Enums\EmployeeStatus;
use App\Domain\HR\Enums\EmploymentType;
use App\Domain\HR\Models\Employee;
use App\Domain\Identity\Services\PermissionService;
use App\Domain\Shared\Traits\UsesBranchScope;
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 EmployeeList extends Component
{
    use WithPagination, WithSorting, UsesBranchScope;

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

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

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

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

    public function mount(): void
    {
        // Default the branch filter to whatever branch the user is working in.
        $this->branchId = $this->branchId ?: (string) ($this->getActiveBranchId() ?? '');
    }

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

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

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

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

    public function render()
    {
        $query = Employee::with(['person', 'branch'])
            ->orderBy($this->sortBy, $this->sortDir);

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

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

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

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

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

        return view('livewire.hr.employee-list', [
            'employees' => $query->paginate(20),
            'statuses' => EmployeeStatus::cases(),
            'employmentTypes' => EmploymentType::cases(),
            'branches' => \App\Domain\Identity\Models\Branch::orderBy('name_ar')->get(),
        ]);
    }
}
