<?php

namespace App\Http\Controllers\Auth;

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
    {
        $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'phone' => ['required', 'string', 'max:20'],
            'cni' => ['nullable', 'string', 'unique:users'],
            'gender' => ['required', 'in:homme,femme'],
            'nationality' => ['required', 'string', 'max:255'],
            'residence' => ['required', 'string', 'max:255'],
            'address' => ['required', 'string'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'cni' => $request->cni,
            'gender' => $request->gender,
            'nationality' => $request->nationality,
            'residence' => $request->residence,
            'address' => $request->address,
            'password' => Hash::make($request->password),
            'role' => 'membre',
            'status' => 'pending', // Nécessite validation admin
        ]);

        event(new Registered($user));

        // Ne pas connecter automatiquement, attendre validation admin
        return redirect()->route('login')
            ->with('success', 'Votre inscription a été soumise avec succès. Vous recevrez un email une fois votre compte validé par un administrateur.');
    }
}
