<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Vendor;
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
    {
        $role = $request->input('role', 'customer');

        // Base validation for all users
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:' . User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'role' => ['required', 'in:customer,vendor'],
        ];

        // Additional validation for vendors
        if ($role === 'vendor') {
            $rules['shop_name'] = ['required', 'string', 'max:255'];
            $rules['shop_description'] = ['required', 'string', 'min:50', 'max:1000'];
            $rules['phone'] = ['required', 'string', 'max:20'];
            $rules['city'] = ['required', 'string', 'max:100'];
            $rules['country'] = ['required', 'string', 'max:100'];
            $rules['business_type'] = ['required', 'in:individual,company'];
        }

        $request->validate($rules);

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

        // Assign role
        $user->assignRole($role);

        // If vendor, create vendor record
        if ($role === 'vendor') {
            Vendor::create([
                'user_id' => $user->id,
                'shop_name' => $request->shop_name,
                'description' => $request->shop_description,
                'phone' => $request->phone,
                'city' => $request->city,
                'country' => $request->country,
                'status' => 'pending',
                'commission_rate' => 10.00,
            ]);
        }

        event(new Registered($user));

        Auth::login($user);

        // Redirect based on role
        if ($role === 'vendor') {
            return redirect()->route('vendor.pending')
                ->with('success', 'Your vendor application has been submitted and is pending approval.');
        }

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