<?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\OtpVerification\Models\OtpVerification;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ResetPasswordController extends Controller
{
    /**
     * Reset password page
     */
    public function index(): View
    {
        return view('module.base-auth::pages.reset-password');
    }

    /**
     * Store new password
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'username' => ['required', 'string', 'max:250', 'exists:users,username'],
            'verification' => ['nullable', 'integer', Rule::requiredIf(fn () => $request->filled('step-verification'))],
            'step-sms' => ['nullable'],
            'step-verification' => ['nullable'],
            'step-password' => ['nullable'],
            'password' => ['bail', 'nullable', 'string', 'min:8', 'confirmed', Rule::requiredIf(fn () => $request->filled('step-password'))],
        ]);

        /** @var User */
        $user = User::where('username', $request->username)->first();

        if ($request->filled('step-sms') && $request->isNotFilled('step-verification') && $request->isNotFilled('step-password')) {
            return $this->sendVerification($request, $user);
        }

        if ($request->filled('step-verification') && $request->isNotFilled('step-password')) {
            return $this->verify($request, $user);
        }

        if ($request->filled('step-password')) {
            return $this->updatePassword($request, $user);
        }

        return response()->json();
    }

    /**
     * Send verification code
     */
    public function sendVerification(Request $request, User $user): JsonResponse
    {
        sendSMSVerification((string) $user->phone);

        return response()->json([
            'step' => 1,
            'message' => __('We send you a verification code to').' ****'.substr((string) $user->phone, 4),
        ]);
    }

    /**
     * Verify phone number
     */
    public function verify(Request $request, User $user): JsonResponse
    {
        $verification = OtpVerification::where('username', $user->phone)
            ->where('code', $request->verification)
            ->first();

        if (! $verification) {
            return response()->json([
                'errors' => [
                    'verification' => [
                        __('Incorrect verification code'),
                    ],
                ],
                'message' => __('Incorrect verification code'),
            ]);
        }

        return response()->json([
            'step' => 2,
            'message' => __("Now you can set your password, but please make sure that you don't forget it!"),
        ]);
    }

    /**
     * Update password
     */
    public function updatePassword(Request $request, User $user): JsonResponse
    {
        $user->update(['password' => bcrypt($request->string('password'))]);

        storeAuthEvent(AuthEvent::PASSWORD_RESET, request());

        return response()->json([
            'step' => 3,
            'message' => __('Your password has been updated'),
        ]);
    }
}
