<?php

namespace App\Livewire\Dashboard\User;

use App\Models\User;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public $search;
    public $is_super_admin;

    protected $queryString = ['search'];

    public function mount()
    {
        // Verificar si el usuario autenticado es super_admin
        $this->is_super_admin = Auth::user()->role === 'super_admin';
    }

    public function updatingSearch()
    {
        $this->resetPage(); // Resetea la paginación al buscar
    }

    public function render()
    {
        $users = User::query()
            // Si no es super_admin, filtra por la compañía del usuario autenticado
            ->when(!$this->is_super_admin, function ($query) {
                $query->where('company_id', Auth::user()->company_id);
            })
            ->when($this->search, function ($query) {
                $query->where(function ($query) {
                    $query->where('name', 'like', '%' . $this->search . '%')
                          ->orWhere('email', 'like', '%' . $this->search . '%');
                });
            })
            ->orderBy('id', 'desc')
            ->paginate(10);

        return view('livewire.dashboard.user.index', [
            'users' => $users,
            'is_super_admin' => $this->is_super_admin
        ])->layout('layouts.app');
    }

    public function delete(User $user)
    {
        $user->delete();
        $this->dispatch('deleted');
    }
}
