<?php

namespace App\Livewire\Admin;

use App\Models\Company;
use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;

class Users extends Component
{
    use WithPagination;

    public $search;
    
    protected $paginationTheme = 'bootstrap'; // or 'tailwind'

    // public function updatedSearch()
    // {
    //     $this->resetPage('userPage');
    // }

    public function render()
    {
        $users = User::with('company')->where('role_id', 2)
            ->where(function ($query) {
                if ($this->search != '') {
                    $query->where(function($q){
                        $q->where('first_name', 'like', "%" . $this->search . "%")
                        ->orWhere('last_name', 'like', "%" . $this->search . "%")
                        ->orWhere('email', 'like', "%" . $this->search . "%");
                    })->orWhereHas('company', function($q){
                        $q->where('name', 'like', "%" . $this->search . "%");
                    });
                }
            })
            ->orderBy('id', 'desc')->paginate(10);
        
        return view('livewire.admin.users', compact('users'));
    }

    public function delete($id){
        $user = User::with('company')->find($id);
        if($user){
            if($user->company != null){
                $data = Company::with('jobs', 'forums', 'products')->find($user->company->id);
                if($data){
                    $data->delete();
                    $this->dispatch("recordDeleted");
                }
            }
            $user->delete();
        }
        
    }

    public function updateStatus($id){
        $data = User::find($id);
        $data->is_block = $data->is_block == 1 ? 0 : 1;
        $data->save();
    }
}
