<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Facades\Hash;

return new class extends Component
{
    use WithFileUploads;

    public string $name = '';
    public string $email = '';
    public string $password = '';
    public string $password_confirmation = '';
    public string $role = 'admin';
    public $avatar = null;

    public function save(): void
    {
        $this->validate([
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'confirmed', Password::min(8)],
            'role'     => ['required', 'string', 'exists:roles,name'],
            'avatar'   => ['nullable', 'image', 'max:2048'],
        ]);

        $avatarPath = null;
        if ($this->avatar) {
            $avatarPath = $this->avatar->store('avatars', 'public');
        }

        $user = User::create([
            'name'     => $this->name,
            'email'    => $this->email,
            'password' => Hash::make($this->password),
            'avatar'   => $avatarPath,
        ]);

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

        session()->flash('success', 'User created successfully.');
        $this->redirect(route('admin.users'), navigate: true);
    }

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function with(): array
    {
        return [
            'roles' => Role::orderBy('name')->pluck('name'),
        ];
    }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/c7eef3c0.blade.php', $data);
    }
};
