<?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\Validation\ValidationException;
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 ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            // Business Details
            'business_name' => ['required', 'string', 'max:255'],
            'ntn_cnic' => ['nullable', 'string', 'max:13'],
            'province' => ['required', 'string', 'max:100'],
            'address' => ['nullable', 'string', 'max:500'],
            'business_email' => ['nullable', 'email', 'max:255'],
            'business_phone' => ['nullable', 'string', 'max:50'],

            // User Details
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $business = \App\Models\Business::create([
            'name' => $request->business_name,
            'business_name' => $request->business_name,
            'ntn_cnic' => $request->ntn_cnic,
            'province' => $request->province,
            'address' => $request->address,
            'email' => $request->business_email,
            'phone' => $request->business_phone,
            'is_active' => false,
        ]);

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

        $business->update(['owner_id' => $user->id]);

        // Assign default pre-seeded 'Admin' role
        $user->assignRole('Admin');

        event(new Registered($user));

        return redirect()->route('login')->with('status', 'Your business has been registered successfully. It will be active once approved by the administrator.');
    }
}
