<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Middleware\OnlyFullVersion;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;

class ForgotPasswordController extends Controller
{


    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */

    use SendsPasswordResetEmails;

    public function __construct()
    {
        $this->middleware(OnlyFullVersion::class);
    }

    /**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function sendResetLinkEmail(Request $request)
    {
        $this->validateFields($request);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $this->credentials($request)
        );

        return $response == Password::RESET_LINK_SENT
            ? $this->sendResetLinkResponse($request, $response)
            : $this->sendResetLinkFailedResponse($request, $response);
    }

    /**
     * Validate the email for the given request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateFields(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email', 'max:255'],
            'security_answer' => ['required', 'string', 'max:255']
        ]);
    }

    protected function validateEmail(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email', 'max:255'],
        ]);
    }

    protected function credentials(Request $request)
    {
        return $request->only(['email', 'security_answer']);
    }


    /**
     * Get the response for a successful password reset link.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $response
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    protected function sendResetLinkResponse(Request $request, $response)
    {
        return $request->wantsJson()
            ? new JsonResponse(['message' => trans($response)], 200)
            : back()->with('status', trans($response));
    }

    /**
     * Get the response for a failed password reset link.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $response
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function sendResetLinkFailedResponse(Request $request, $response)
    {
        if ($request->wantsJson()) {
            throw ValidationException::withMessages([
                'email' => [trans($response)],
                'security_answer' => [trans($response)],
            ]);
        }

        return back()
            ->withInput($request->only('email'))
            ->withErrors(['email' => trans($response)]);
    }

    public function getSecurityQuestion(Request $request)
    {
        $this->validateEmail($request);

        $user = $this->broker()->getUser(["email" => $request->email]);
        if ($user) {
            $security_question = $this->getSecurityQuestionByIndex($user->Security_question_index) != false ? $this->getSecurityQuestionByIndex($user->Security_question_index) : $this->securityQuestionNotFound();
            return response()->json([
                'message' => 'success',
                'data' => [
                    'security_question' => $security_question
                ]
            ]);
        }
        return $this->sendFailedSecurityQuestionResponse($request, 'passwords.user');
    }

    public function sendFailedSecurityQuestionResponse(Request $request, $response)
    {
        throw ValidationException::withMessages([
            'email' => [trans($response)],
        ]);
    }

    public function getSecurityQuestionByIndex($index)
    {
        try {

            $questions = config('srm_config.dashboard.security_questions');
            return isset($questions[$index]) ? $questions[$index] : false;
        } catch (\Exception $e) {

            return false;
        }
    }

    public function securityQuestionNotFound()
    {
        throw ValidationException::withMessages([
            'email' => [trans('passwords.security_not_found')],
        ]);
    }
}
