<?php

namespace App\Livewire\Auth;

use App\Models\Plan;
use App\Models\Subscription;
use App\Models\User;
use App\Services\MailService;
use App\Services\VerificationService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Livewire\Component;

class Register extends Component
{
    public $name;
    public $email;
    public $password;
    public $timezone = 'UTC';

    public function register()
    {
        $this->validate(
            [
                'name' => ['required'],
                'email' => ['required', 'email', 'unique:users,email'],
                'password' => ['required', 'min:6'],
            ],
            [
                // NAME
                'name.required' => t('auth.validation.name_required'),

                // EMAIL
                'email.required' => t('auth.validation.email_required'),
                'email.email' => t('auth.validation.email_invalid'),
                'email.unique' => t('auth.validation.email_taken'),

                // PASSWORD
                'password.required' => t('auth.validation.password_required'),
                'password.min' => t('auth.validation.password_min'),
            ]
        );

        // 🔥 Browser Sprache holen
        $locale = substr(request()->header('Accept-Language'), 0, 2);
        $locale = in_array($locale, array_keys(config('app.locales')))
            ? $locale
            : config('app.default_locale');

        // 🔥 Timezone absichern
        if (!in_array($this->timezone, timezone_identifiers_list())) {
            $this->timezone = 'UTC';
        }

        $user = User::create([
            'name' => $this->name,
            'email' => $this->email,
            'password' => Hash::make($this->password),
            'locale' => $locale,
            'timezone' => $this->timezone,
        ]);

        $plan = Plan::where('name', 'Free')
            ->where('active', true)
            ->firstOrFail();

        // SUBSCRIPTION ANLEGEN (eine Zeile pro User, wird bei Planwechsel nur geupdated)
        Subscription::create([
            'user_id'    => $user->id,
            'plan_id'    => $plan->id,
            'plan_name'  => $plan->name,
            'plan_slug'  => $plan->plan_key ?? Str::slug($plan->name),
            'price'      => $plan->price ?? 0,
            'interval'   => $plan->interval ?? 'monthly',
            'status'     => 'active',
            'starts_at'  => now(),
            'provider'   => null,
        ]);

        VerificationService::create($user, 'email');

        return redirect()->route('verify.notice', [
            'user' => $user->id
        ]);
    }

    public function render()
    {
        return view('livewire.auth.register')
            ->layout('layouts.blank');
    }
}
