<?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 updatedShowInactive(): 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 deleteUser(string $uuid): void
    {
        $this->authorize('users.delete');
        $user = User::where('uuid', $uuid)->firstOrFail();

        if ($user->person_id) {
            $user->person?->update(['user_id' => null]);
        }

        $user->delete();
        session()->flash('success', 'تم حذف المستخدم بنجاح');
    }

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