<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\GeneralSetting;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class RegisteredUserController extends Controller
{
    public function create(Request $request)
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        $settings = GeneralSetting::firstOrCreate(['id' => 1], [
            'verify_fee' => 300,
            'bondhonpay_api_key' => '',
            'site_name' => 'TASK EARNING',
            'site_description' => 'TASK EARNING - Build your career smartly.',
            'background_color' => '#ffffff',
            'icon_color' => '#0B5D1E',
            'hover_color' => '#0F7A2E',
            'text_color' => '#0f172a',
            'facebook_link' => null,
            'youtube_link' => null,
            'whatsapp_link' => null,
            'telegram_link' => null,
            'support_general' => null,
            'support_verify' => null,
            'support_withdraw' => null,
            'support_technical' => null,
            'logo' => null,
            'favicon' => '/favicon.png',
            'banner' => null,
            'reselling_banner' => null,
        ]);

        $referralCode = $request->query('ref');

        return view('auth.register', compact('settings', 'referralCode'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'mobile' => ['required', 'regex:/^01[3-9]\d{8}$/', 'unique:users,mobile'],
            'password' => ['required', 'string', 'min:4', 'confirmed'],
            'referral_code' => ['required', 'string', 'exists:users,referral_code'],
        ], [
            'password.min' => 'পাসওয়ার্ড কমপক্ষে ৪ অক্ষরের হতে হবে।',
            'referral_code.required' => 'রেফার কোড দিতে হবে।',
            'referral_code.exists' => 'এই রেফার কোডটি সঠিক নয়।',
        ]);

        $inputRefCode = trim((string) $data['referral_code']);
        $referrer = User::where('referral_code', $inputRefCode)->first();
        if (!$referrer) {
            return back()
                ->withErrors(['referral_code' => 'রেফার কোড সঠিক নয়।'])
                ->withInput();
        }

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'mobile' => $data['mobile'],
            'password' => Hash::make($data['password']),
            'referral_code' => $this->generateUniqueReferralCode(),
            'referred_by' => (string) $referrer->referral_code,
        ]);

        Auth::login($user);

        // Dashboard এ ঢুকলেই popup show হবে (dashboard view এ session('show_telegram_popup') দেখবে)
        $request->session()->flash('show_telegram_popup', true);

        return redirect()->route('dashboard')->with('success', 'রেজিস্ট্রেশন সফল হয়েছে।');
    }

    private function generateUniqueReferralCode()
    {
        do {
            $code = rand(100000, 999999);
        } while (User::where('referral_code', $code)->exists());

        return $code;
    }
}
