<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
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\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(Request $request): View
    {
        if ($request->has('ref')) {
            session(['referrer' => $request->query('ref')]);
        }
    
        return view('auth.register');
    }
    
    public function store(Request $request): RedirectResponse
    {
        if(get_setting('maintenance_status') == 'on') {
            throw ValidationException::withMessages([
                'error' => 'Website is under Maintenance, only Admins can login.',
            ]);
        }
        if (!session()->has('cdata')) {
            throw ValidationException::withMessages([
                'captcha' => 'The captcha verification failed. Please try again.',
            ]);
        }
    
        $functionData = session('cdata');
        $captchaResponse = $request->input($functionData['ctoken']);
        $isVerified = verify_ccaptcha($functionData, $captchaResponse);
    
        if (!$isVerified) {
            throw ValidationException::withMessages([
                'captcha' => 'The captcha verification failed. Please try again.',
            ]);
        }
        $ipAddress = $request->ip();
        if (User::where('ip_address', $ipAddress)->exists()) {
            throw ValidationException::withMessages([
                'error' => 'Your IP address has already been used for registration.',
            ]);
        }

        $request->validate([
            'name' => ['required', 'string', 'max:255', 'regex:/^\S*$/', 'unique:'.User::class],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);
    
        $allowed_mails = get_setting('allowed_mails');
        
        if (is_string($allowed_mails)) {
            $allowed_mails = trim($allowed_mails, '[]"');
            $allowed_mails = explode(',', $allowed_mails);
        } else {
            $allowed_mails = [];
        }
        
        $email_domain = substr(strrchr($request->email, "@"), 1);
        
        if (!empty($allowed_mails) && !in_array($email_domain, $allowed_mails)) {
            throw ValidationException::withMessages([
                'error' => 'The email domain is not allowed for registration.',
            ]);
        }
    
        $referrerId = session('referrer') ? User::where('id', session('referrer'))->value('id') : null;
    
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'Member',
            'balance' => 0.000000,
            'deposited' => 0.000000,
            'available_deposit' => 0.000000,
            'total_earned' => 0.000000,
            'today_earned' => 0.000000,
            'ip_address' => $ipAddress,
            'last_login_ip' => $ipAddress,
            'country' => 'Unknown',
            'last_active' => now()->timestamp,
            'referred_by' => $referrerId ?? 0,
        ]);
    
        session()->forget('referrer');
    
        event(new Registered($user));
    
        Auth::login($user);
    
        return redirect()->route('dashboard');
    }

}
