<?php

namespace App\Livewire\Users;

use App\Livewire\Concerns\WithSorting;
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, WithSorting;

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

    public function mount(): void
    {
        if (!request()->has('sortBy')) {
            $this->sortBy = 'name_ar';
        }
        if (!request()->has('sortDir')) {
            $this->sortDir = 'asc';
        }
    }

    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($this->sortBy, $this->sortDir);

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