<?php

namespace App\Livewire\Admin\User;

use Livewire\Component;
use App\Models\Admin\User;
use Illuminate\Support\Str;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Validate;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;

class CreateUserForm extends Component
{
    #[Validate('required|email|unique:users,email')]
    public $email = '';

    #[Validate('required|min:2')]
    public $name = '';

    #[Validate('required|min:8')]
    public $password = '';

    #[Validate('required|exists:roles,name')]
    public $role = '';



    #[Computed()]
    public function countries()
    {
        return DB::table('countries')->get();
    }

  

    #[Computed()]
    public function roles()
    {
        $currentUser = Auth::user();

        $rolesQuery = Role::where('name', '<>', 'super-admin');

        if (!$currentUser->hasRole('admin') && !$currentUser->hasRole('super-admin')) {
            $rolesQuery->where('name', '<>', 'admin');
        }

        $allowedRoles = $rolesQuery->get();

        return $allowedRoles;
    }

    public function randomPassword()
    {
        $this->password = Str::random(8);
    }

    public function save()
    {
        $this->validate();

        $user = User::create([
            'name' => $this->name,
            'email' => $this->email,
            'password' => bcrypt($this->password),
        ]);

        $user->assignRole($this->role);

        activity()->performedOn($user)->causedBy(auth()->id())->log('Kullanıcı oluşturuldu');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Kullanıcı başarıyla oluşturuldu.', 'icon' => 'success'
        ]);

        $this->reset();
    }

    public function saveAndRedirect()
    {
        $this->save();

        $this->redirectRoute('admin.users.index');
    }

    public function render()
    {
        return view('livewire.admin.user.create-user-form');
    }
}
