<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\CryptoAsset;
use App\Models\Notification;
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
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\Support\Facades\DB;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
use Illuminate\Support\Str;

class RegisteredUserController extends Controller
{
    public function create(Request $request): View
    {
        $referral_code = $request->ref;
        $referrer = null;
        
        if ($referral_code) {
            $referrer = User::where('referral_code', $referral_code)->first();
        }
        
        return view('auth.register', compact('referral_code', 'referrer'));
    }

    public function verifyReferralCode(Request $request)
    {
        $referrer = User::where('referral_code', $request->referral_code)->first();
        
        return response()->json([
            'valid' => !is_null($referrer),
            'referrer' => $referrer ? $referrer->name : null
        ]);
    }

    /**
     * Generate 12-word recovery phrase
     */
    private function generateRecoveryPhrase($words = 12)
    {
        $wordList = [
            'apple','river','stone','planet','gold','silver','cloud',
            'forest','light','dream','ocean','storm','fire','earth',
            'wind','shadow','star','moon','sun','sky'
        ];

        $phrase = [];

        for ($i = 0; $i < $words; $i++) {
            $phrase[] = $wordList[array_rand($wordList)];
        }

        return implode(' ', $phrase);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'referral_code' => ['nullable', 'string', 'exists:users,referral_code'],
        ]);

        try {
            DB::beginTransaction();

            $referrer = null;
            if ($request->referral_code) {
                $referrer = User::where('referral_code', $request->referral_code)
                                ->lockForUpdate()
                                ->first();
            }

            // 👇 Generate recovery phrase here
            $recoveryPhrase = $this->generateRecoveryPhrase();

            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'referral_code' => 'REF' . strtoupper(Str::random(8)),
                'referred_by' => $referrer ? $referrer->id : null,
                'referral_count' => 0,
                'recovery_phrase' => $recoveryPhrase, // ✅ ADDED
            ]);

            if ($referrer) {
                $referrer->referral_count += 1;
                $referrer->save();

                if (setting('referral_enabled') && 
                    (setting('referral_bonus_type') === 'instant' || 
                    (setting('referral_bonus_type') === 'after_kyc' && $referrer->kyc_status === 'approved'))) {
                    
                    $bonus_amount = setting('referral_bonus_amount', 0);
                    
                    $referrerCryptoAsset = CryptoAsset::firstOrCreate(
                        ['user_id' => $referrer->id]
                    );

                    $referrerCryptoAsset->increment('usdt_trc20_balance', $bonus_amount);

                    Notification::createNotification([
                        'user_id' => $referrer->id,
                        'type' => 'referral_bonus',
                        'title' => 'Referral Bonus Received',
                        'message' => "You have received a referral bonus of $${bonus_amount} USDT for referring {$user->name}",
                        'extra_data' => json_encode([
                            'amount' => $bonus_amount,
                            'referred_user' => $user->name
                        ])
                    ]);
                }
            }

            $cryptoAsset = CryptoAsset::create([
                'user_id' => $user->id
            ]);
            $cryptoAsset->generateAddressesIfNull();
    	
            Mail::to($user->email)->queue(new WelcomeEmail($user));

            $admins = User::where('is_admin', 1)->pluck('email');
            Mail::to($admins)->queue(new \App\Mail\NewUserRegistered($user));

            DB::commit();

            event(new Registered($user));
            Auth::login($user);

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

        } catch (\Exception $e) {
            DB::rollBack();

            \Log::error('Registration failed: '.$e->getMessage());

            return back()
                ->withInput($request->except('password'))
                ->withErrors(['registration' => 'Registration failed: '.$e->getMessage()]);
        }
    }
}