<?php

namespace App\Livewire\Users;

use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('المستخدمين')]
class UserList extends Component
{
    use WithPagination;

    #[Url]
    public string $search = '';
    public string $role = '';
    public bool $showInactive = false;

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

    public function toggleActive(string $uuid): void
    {
        $user = User::where('uuid', $uuid)->firstOrFail();
        $newStatus = $user->status === 'active' ? 'inactive' : 'active';
        $user->update(['status' => $newStatus]);
    }

    public function render()
    {
        $query = User::query()
            ->with('primaryRole')
            ->when($this->search, function ($q) {
                $q->where(function ($q2) {
                    $q2->where('name_ar', 'ilike', "%{$this->search}%")
                       ->orWhere('name', 'ilike', "%{$this->search}%")
                       ->orWhere('email', 'ilike', "%{$this->search}%");
                });
            })
            ->when($this->role, fn ($q) => $q->where('role_id', $this->role))
            ->when(!$this->showInactive, fn ($q) => $q->where('status', 'active'))
            ->orderBy('name_ar');

        return view('livewire.users.user-list', [
            'users' => $query->paginate(20),
            'roles' => \App\Domain\Identity\Models\Role::orderBy('level', 'desc')->get(['id', 'name_ar']),
        ]);
    }
}
