<?php

namespace App\Livewire;

use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;

class EmployeeTable extends Component
{
    use WithPagination;

    public string $search = '';
    public string $department_id = '';
    public string $designation_id = '';
    public string $status = '';

    protected $queryString = [
        'search' => ['except' => ''],
        'department_id' => ['except' => ''],
        'designation_id' => ['except' => ''],
        'status' => ['except' => ''],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function render()
    {
        $query = User::with(['department', 'designation', 'reportingManager'])
            ->forTenantDirectory();
        if (auth()->user()->company_id) {
            $query->where('company_id', auth()->user()->company_id);
        }
        if ($this->search) {
            $query->where(function ($q) {
                $q->where('name', 'like', '%' . $this->search . '%')
                    ->orWhere('employee_number', 'like', '%' . $this->search . '%')
                    ->orWhere('email', 'like', '%' . $this->search . '%');
            });
        }
        if ($this->department_id) {
            $query->where('department_id', $this->department_id);
        }
        if ($this->designation_id) {
            $query->where('designation_id', $this->designation_id);
        }
        if ($this->status) {
            $query->where('status', $this->status);
        }
        $employees = $query->orderBy('name')->paginate(15);

        return view('livewire.employee-table', [
            'employees' => $employees,
            'departments' => \App\Models\Department::orderBy('name')->get(),
            'designations' => \App\Models\Designation::orderBy('name')->get(),
        ]);
    }
}
