<?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\Support\Facades\Mail;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use App\Models\Company;
use Illuminate\View\View;
use App\Services\ActionNotificationService;
use App\Mail\SignupWelcomeMail;

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

    /**
     * Handle an incoming registration request.
     *
     * @throws ValidationException
     */
    public function store(Request $request, ActionNotificationService $notifications): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'owner',
        ]);


        event(new Registered($user));

        // Send welcome email to the new owner/user
        Mail::to($user->email)->queue(new SignupWelcomeMail($user, 'web'));

        // Send notification email to admins
        $notifications->notifyAction(
            'Web Signup',
            $user,
            [
                'channel' => 'web',
                'role' => $user->role,
                'email' => $user->email,
            ]
        );

        Auth::login($user);

        // Redirect to onboarding stepper after registration
        return redirect()->route('onboard.show');
    }
}
