<?php

namespace App\Http\Controllers\Auth;

use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        // Validación de los datos del formulario
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'foto' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif', 'max:2048'],
            'role' => ['required', 'in:super-admin,personal'], // Validar el rol
        ]);
    
        // Crear el arreglo con los datos del usuario
        $userData = [
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ];
    
        // Verificar si se cargó una foto
        if ($request->hasFile('foto')) {
            $path = $request->file('foto')->store('profile-photos', 'public');
            $userData['foto'] = $path;
        }
    
        // Crear el usuario
        $user = User::create($userData);
    
        // Asignar el rol al usuario
        $user->assignRole($request->role); // Asignar el rol seleccionado
    
        // Disparar el evento de registro
        event(new Registered($user));
    
        return redirect()->route('login')->with([
            'success' => 'Usuario registrado correctamente. Ahora puedes iniciar sesión.',
            'registered_email' => $user->email
        ]);
    }
    
}
