<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\User;
use App\Notifications\WelcomeEmail;
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
    {
        // Validări de bază
        $rules = [
            'user_type' => ['required', 'in:individual,company'],
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'phone' => ['required', 'string', 'max:20'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'terms_accepted' => ['required', 'accepted'],
        ];

        // Validări suplimentare pentru persoană juridică
        if ($request->user_type === 'company') {
            $rules = array_merge($rules, [
                'company_cui' => ['required', 'string', 'max:50'],
                'company_name' => ['required', 'string', 'max:255'],
                'company_reg_com' => ['required', 'string', 'max:100'],
                'company_address' => ['required', 'string', 'max:255'],
                'company_number' => ['required', 'string', 'max:20'],
                'company_city' => ['required', 'string', 'max:100'],
                'company_county' => ['required', 'string', 'max:100'],
                'company_postal_code' => ['required', 'string', 'max:20'],
                'company_country' => ['required', 'string', 'max:100'],
            ]);
        }

        $validated = $request->validate($rules);

        // Obține planul gratuit
        $freePlan = Plan::where('slug', 'gratuit')->firstOrFail();

        // Creează numele complet
        $fullName = $validated['first_name'] . ' ' . $validated['last_name'];

        $user = User::create([
            'name' => $fullName,
            'first_name' => $validated['first_name'],
            'last_name' => $validated['last_name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'password' => Hash::make($validated['password']),
            'user_type' => $validated['user_type'],
            'role' => 'user',
            'plan_id' => $freePlan->id,
            'is_active' => true,
            'terms_accepted' => true,
            // Câmpuri companie (doar dacă e persoană juridică)
            'company_cui' => $request->user_type === 'company' ? $validated['company_cui'] : null,
            'company_name' => $request->user_type === 'company' ? $validated['company_name'] : null,
            'company_reg_com' => $request->user_type === 'company' ? $validated['company_reg_com'] : null,
            'company_address' => $request->user_type === 'company' ? $validated['company_address'] : null,
            'company_number' => $request->user_type === 'company' ? $validated['company_number'] : null,
            'company_city' => $request->user_type === 'company' ? $validated['company_city'] : null,
            'company_county' => $request->user_type === 'company' ? $validated['company_county'] : null,
            'company_postal_code' => $request->user_type === 'company' ? $validated['company_postal_code'] : null,
            'company_country' => $request->user_type === 'company' ? $validated['company_country'] : null,
        ]);

        event(new Registered($user));

        // Trimite Welcome email
        $user->notify(new WelcomeEmail());

        Auth::login($user);

        // Verifică dacă email verification este activat
        $emailVerificationEnabled = \App\Models\Setting::get('email_verification_enabled', true);

        // Convert to boolean if it's a string
        if (is_string($emailVerificationEnabled)) {
            $emailVerificationEnabled = $emailVerificationEnabled === '1' || $emailVerificationEnabled === 'true';
        }

        if ($emailVerificationEnabled) {
            // Redirect către pagina de verificare email
            return redirect()->route('verification.notice');
        }        return redirect(route('dashboard', absolute: false));
    }
}
