<?php

namespace App\Http\Controllers\Auth;

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

class RegisteredUserController extends Controller
{
    public function create(Request $request): View
    {
        $refCode = $request->query('ref');

        return view('auth.auth', [
            'activeTab' => 'register',
            'refCode'   => $refCode
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        /*
        |--------------------------------------------------------------------------
        | Validate Cloudflare Turnstile
        |--------------------------------------------------------------------------
        */
        $response = $request->input('cf-turnstile-response');
        $secret   = config('services.turnstile.secret');

        $verify = Http::asForm()
            ->timeout(15)
            ->post(
                'https://challenges.cloudflare.com/turnstile/v0/siteverify',
                [
                    'secret'   => $secret,
                    'response' => $response,
                    'remoteip' => $request->ip(),
                ]
            );

        if (!$verify->json('success')) {

            return back()
                ->withErrors([
                    'cf_turnstile' => 'Verifikasi keamanan gagal. Silakan coba lagi.'
                ])
                ->withInput();
        }

        /*
        |--------------------------------------------------------------------------
        | Validate Input
        |--------------------------------------------------------------------------
        */
        $request->validate([

            'name' => [
                'required',
                'string',
                'max:255'
            ],

            'email' => [
                'required',
                'string',
                'lowercase',
                'email',
                'max:255',
                'regex:/^[a-zA-Z0-9._%+-]+@gmail\.com$/',
                'unique:users,email'
            ],

            'phone' => [
                'required',
                'string',
                'regex:/^08[0-9]{8,13}$/',
                'unique:users,phone'
            ],

            'password' => [
                'required',
                'confirmed',
                Rules\Password::defaults()
            ],

        ], [

            'email.unique' => 'Email sudah terdaftar.',
            'email.regex'  => 'Gunakan email Gmail yang valid.',

            'phone.unique' => 'Nomor HP sudah digunakan.',
            'phone.regex'  => 'Format nomor HP tidak valid.',

            'password.confirmed' => 'Konfirmasi password tidak cocok.',
        ]);

        /*
        |--------------------------------------------------------------------------
        | Cari Referrer
        |--------------------------------------------------------------------------
        */
        $referrerId = null;

        if ($request->filled('ref')) {

            $refUser = User::where(
                'referral_code',
                $request->ref
            )->first();

            if ($refUser) {
                $referrerId = $refUser->id;
            }
        }

        /*
        |--------------------------------------------------------------------------
        | Create User
        |--------------------------------------------------------------------------
        */
        try {

            $user = User::create([
                'name'        => $request->name,
                'email'       => $request->email,
                'phone'       => $request->phone,
                'password'    => Hash::make($request->password),
                'referrer_id' => $referrerId,
            ]);

        } catch (QueryException $e) {

            return back()
                ->withInput()
                ->withErrors([
                    'email' => 'Email sudah digunakan.'
                ]);
        }

        /*
        |--------------------------------------------------------------------------
        | Simpan Referral
        |--------------------------------------------------------------------------
        */
        if ($referrerId) {

            Referral::create([
                'user_id'          => $referrerId,
                'referred_user_id' => $user->id,
                'deposit_amount'   => 0,
                'bonus'            => 0,
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | Login User
        |--------------------------------------------------------------------------
        */
        event(new Registered($user));

        Auth::login($user);

        \Log::info('REGISTER_SUCCESS', [
            'user' => $user->email,
            'ip'   => $request->ip(),
            'path' => $request->path(),
        ]);

        /*
        |--------------------------------------------------------------------------
        | APK atau WEB
        |--------------------------------------------------------------------------
        */
        $home = str_starts_with(
            $request->path(),
            'apk/'
        )
            ? '/apk/dashboard'
            : '/dashboard';

        return redirect($home);
    }
}