<?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\HR\Services\EmployeeService;
use App\Domain\Identity\Services\PermissionService;
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;

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

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

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

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

    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 delete(string $uuid, EmployeeService $service): void
    {
        $this->authorize('employees.delete');

        $employee = Employee::where('uuid', $uuid)->firstOrFail();
        $employee->delete();

        session()->flash('success', __('تم حذف الموظف بنجاح'));
    }

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

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