<?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([
            'name' => ['required', 'string', 'max:255'],

            // ✅ phone (BD format) + unique
            'phone' => ['required', 'string', 'regex:/^01[3-9]\d{8}$/', 'unique:users,phone'],

            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ], [
            'name.required' => 'নাম লিখুন',
            'phone.required' => 'মোবাইল নম্বর দিন',
            'phone.regex' => 'সঠিক মোবাইল নম্বর দিন (01XXXXXXXXX)',
            'phone.unique' => 'এই মোবাইল নম্বরটি আগে থেকেই ব্যবহার করা হয়েছে',
            'password.required' => 'পাসওয়ার্ড দিন',
            'password.confirmed' => 'পাসওয়ার্ড মিলছে না',
        ]);

        $user = User::create([
            'name' => $request->name,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),

            // ✅ If your users table still has email column but you don't use it:
            // 'email' => null,
        ]);

        event(new Registered($user));

        Auth::login($user);

        return redirect(route('dashboard', absolute: false));
    }
}
