<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class RegisterController extends Controller {
    public function showForm() {
        return auth()->check() ? redirect()->route('dashboard') : view('auth.register');
    }

    public function register(Request $request) {
        $request->validate([
            'name'     => 'required|string|max:100',
            'email'    => 'required|email|unique:users,email',
            'password' => 'required|min:8|confirmed',
        ]);

        // Generate unique referral code
        do { $code = strtoupper(Str::random(8)); } while (\App\Models\User::where('referral_code', $code)->exists());

        $referrerId = null;
        if ($request->filled('ref')) {
            $referrer = \App\Models\User::where('referral_code', $request->ref)->first();
            if ($referrer) $referrerId = $referrer->id;
        }

        $user = \App\Models\User::create([
            'name'          => $request->name,
            'email'         => $request->email,
            'password'      => \Hash::make($request->password),
            'referral_code' => $code,
            'referred_by'   => $referrerId,
        ]);

        if ($referrerId) {
            \App\Models\Referral::create([
                'referrer_id'   => $referrerId,
                'referred_id'   => $user->id,
                'reward_amount' => 50,
                'status'        => 'pending',
            ]);
        }

        \Auth::login($user);
        \App\Models\CartItem::where('session_id', $request->session()->getId())
            ->update(['user_id' => $user->id]);

        try {
            \Mail::to($user->email)->send(new \App\Mail\WelcomeMail($user));
        } catch (\Throwable) {}

        return redirect()->route('dashboard');
    }
}
