<?php

namespace App\Livewire\Auth;

use App\Enum\Currency;
use App\Enum\UserAccountType;
use App\Enum\UserTradingPlatform;
use App\Mail\EmailVerificationCode;
use App\Mail\Welcome;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Livewire\Component;

class Register extends Component
{
    public $contact_time;
    public $name, $email, $phone;
    public $gender, $country, $registration_token;
    public $password, $password_confirmation;
    public bool $agree = false;

    protected $messages = [
        'agree.accepted' => 'You must agree to the Terms and Conditions to continue.',
    ];

    public function mount() {}

    public function register()
    {
        // 🪤 Honeypot Protection
        if (!empty($this->contact_time)) {
            session()->flash('error', 'Suspicious activity detected. Please try again later.');
            return $this->redirectRoute('register', navigate: true);
        }

        $this->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'phone' => 'nullable|string|max:255',
            'gender' => 'nullable|string|max:255',
            'country' => 'required|string|max:255',
            'registration_token' => 'required|string|max:255|exists:settings,registration_token',
            'password' => 'required|confirmed',
            'agree' => 'accepted',
        ], [
            'registration_token.exists' => 'Invalid registration token.',
        ]);

        try {
            DB::beginTransaction();

            $data = [
                'name' => $this->name,
                'email' => $this->email,
                'email_code' => getRandomNumber(6),
                'email_code_expires_at' => now()->addMinutes(60),
                'phone' => $this->phone,
                'gender' => $this->gender,
                'country' => $this->country,
                'registration_token' => $this->registration_token,
                'password' => $this->password,
                'password_plain' => $this->password,
                'api_key' => generateApiKey(),
                'secret_key' => generateSecretKey(),
            ];

            Setting::updateOrCreate([
                'id' => 1,
            ], [
                'registration_token' => generateRegistrationToken(),
            ]);

            $user = User::create($data);

            Auth::login($user);

            Mail::to($user->email)->queue(new EmailVerificationCode($user));
            Mail::to($user->email)->later(now()->addSeconds(30), new Welcome($user));

            DB::commit();

            return redirect()->route('verify.email')->with('success', 'A verification code has been sent to your email address. Please enter the code to verify your account.');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            session()->flash('error', config('app.messages.error'));
            return;
        }
    }

    public function render()
    {
        return view('livewire.auth.register');
    }
}
