<?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 App\Models\Setting;
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
        ]);
    }

    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();
        }

        $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
        ]);

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

            // Handle instant referral bonus if enabled and referrer is KYC verified
            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);

                // Notify referrer about the bonus
                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));

        DB::commit();

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

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

    } catch (\Exception $e) {
        DB::rollBack();
        return back()
            ->withInput($request->except('password'))
            ->withErrors(['registration' => 'Registration failed. Please try again.']);
    }
}
}