<?php

namespace App\Modules\BaseAuth\Controllers;

use App\Http\Controllers\Controller;
use App\Models\System\Verification;
use App\Models\User;
use App\Modules\BaseAuth\Models\AuthEvent;
use App\Modules\BaseLocale\Middleware\SetLocale;
use App\Modules\OtpVerification\Rules\OtpVerificationRule;
use App\Modules\PhoneNumberVerification\Rules\PhoneNumberVerificationRule;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /**
     * Middleware
     */
    public function __construct()
    {
        $middleware = [];

        if (module('BaseLocale')->isEnabled()) {
            array_push($middleware, SetLocale::class);
        }

        $this->middleware($middleware)->except('logout');
    }

    /**
     * Show registration page
     */
    public function showNovaRegisterpageForm(): View
    {
        return view('module.base-auth::pages.register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        if ($request->has('phone')) {
            $request->merge([
                'phone' => unMaskTurkmenNumber($request->string('phone')),
            ]);
        }

        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        Auth::guard()->login($user);

        if (config('module.base-auth.store_auth_events')) {
            storeAuthEvent(AuthEvent::REGISTER, $request);
        }

        if (config('module.base-auth.sms_verification')) {
            sendSMSVerification((string) $user->phone);

            return response()->json([
                'url' => route('sms-verification'),
            ]);
        }

        return response()->json([
            'url' => config('module.base-auth.redirect_path'),
        ]);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array<string, int|string>  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', new PhoneNumberVerificationRule, 'unique:users,phone'],
            'username' => ['required', 'string', 'alpha_dash:ascii', 'max:255', 'unique:users,username'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array<string, int|string>  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'phone' => $data['phone'],
            'username' => $data['username'],
            'password' => Hash::make((string) $data['password']),
            'must_fill_profile' => true,
        ]);

        return $user;
    }

    /**
     * Sms verification
     */
    public function smsVerification(): View
    {
        return view('module.base-auth::pages.sms-verification', ['phone' => Auth::user()?->phone]);
    }

    /**
     * Change users phone number
     */
    public function changePhone(Request $request): JsonResponse
    {
        if ($request->has('phone')) {
            $request->merge(['phone' => unMaskTurkmenNumber($request->string('phone'))]);
        }

        $request->validate([
            'phone' => ['required', new PhoneNumberVerificationRule, 'unique:users,phone'],
        ]);

        /** @var User */
        $user = Auth::user();

        $user->update([
            'phone' => $request->phone,
        ]);

        storeAuthEvent(AuthEvent::PHONE_CHANGED, $request);

        sendSMSVerification((string) $user->phone);

        return response()->json([
            'url' => route('sms-verification'),
        ]);
    }

    /**
     * Verify sms code
     */
    public function verifySmsCode(Request $request): RedirectResponse
    {
        /** @var User */
        $user = Auth::user();

        $request->validate([
            'code' => ['bail', 'required', 'integer', new OtpVerificationRule($user->phone)],
        ]);

        $user->update([
            'phone_verified_at' => now(),
        ]);

        storeAuthEvent(AuthEvent::PHONE_VERIFICATION, $request);

        return redirect(config()->string('module.base-auth.redirect_path'));
    }

    /**
     * Resend verification
     */
    public function resendVerification(): RedirectResponse
    {
        sendSMSVerification((string) user()->phone);

        return to_route('sms-verification');
    }
}
