<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class RegisteredUserController extends Controller
{
    /**
     * Show the registration page.
     */
    public function create(Request $request): Response
    {
        $package = $request->query('package_id') ? \App\Models\Package::find($request->query('package_id')) : null;

        return Inertia::render('auth/register', [
            'package' => $package,
        ]);
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $fullName = trim($request->first_name.' '.$request->last_name);


        $validated = $request->validate([
            'username' => ['required', 'string', 'max:255', 'unique:'.User::class],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'address' => ['required', 'string', 'max:500'],
            'phone' => ['required', 'string', 'max:20'],
            'privacy_consent' => ['accepted'],
            'package_id' => ['nullable', 'exists:packages,id'],
        ]);

        $shouldAutoVerify = App::environment('local');

        $user = User::create([
            'username' => $validated['username'],
            'email' => $validated['email'],
            'first_name' => $validated['first_name'],
            'last_name' => $validated['last_name'],
            'address' => $validated['address'],
            'phone' => $validated['phone'],
            'password' => Hash::make($validated['password']),
            'privacy_consent_at' => now(), // Neues Feld für Consent (füge Migration hinzu, falls nötig)
            'role' => 'user',
        ]);

        if ($shouldAutoVerify) {
            $user->forceFill(['email_verified_at' => now()])->save();
        }

        $tenant = Tenant::create([
            'user_id' => $user->id,
            'name' => $fullName,
            'slug' => Str::slug($fullName.'-'.now()->timestamp),
            'email' => $request->email,
            'is_active' => true,
            'is_suspended' => false,
            'subscription_tier' => 'free',
            'subscription_expires_at' => null,
            'settings' => json_encode([
                'branding' => [
                    'logo_url' => null,
                    'primary_color' => '#3B82F6',
                    'secondary_color' => '#1F2937',
                    'font_family' => 'Inter, sans-serif',
                ],
                'features' => [
                    'photo_likes_enabled' => false,
                    'event_checklist' => false,
                    'custom_domain' => false,
                    'advanced_analytics' => false,
                ],
                'custom_domain' => null,
                'contact_email' => $request->email,
                'event_default_type' => 'general',
            ]),
        ]);

        if (! $user->tenant_id) {
            $user->forceFill(['tenant_id' => $tenant->id])->save();
        }

        event(new Registered($user));

        // Send Welcome Email
        Mail::to($user)
            ->locale($user->preferred_locale ?? app()->getLocale())
            ->send(new \App\Mail\Welcome($user));

        if ($request->filled('package_id')) {
            $package = \App\Models\Package::find($request->package_id);
            if ($package && $package->price == 0) {
                // Assign free package
                \App\Models\TenantPackage::create([
                    'tenant_id' => $tenant->id,
                    'package_id' => $package->id,
                    'active' => true,
                    'price' => 0,
                ]);

                \App\Models\PackagePurchase::create([
                    'tenant_id' => $tenant->id,
                    'package_id' => $package->id,
                    'type' => $package->type === 'endcustomer' ? 'endcustomer_event' : 'reseller_subscription',
                    'price' => 0,
                    'purchased_at' => now(),
                    'provider' => 'free',
                    'provider_id' => 'free',
                ]);

                $tenant->update(['subscription_status' => 'active']);
                $user->update(['role' => 'tenant_admin']);
                Auth::login($user);
            } elseif ($package) {
                // Redirect to buy for paid package
                return redirect()->route('buy.packages', [
                    'locale' => session('preferred_locale', app()->getLocale()),
                    'packageId' => $package->id,
                ]);
            }
        }

        Auth::login($user);

        if ($shouldAutoVerify) {
            return Inertia::location(route('dashboard'));
        }

        session()->flash('status', 'registration-success');

        return Inertia::location(route('verification.notice'));
    }
}
