<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Password;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Validation\Rules\Password as PasswordRule;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
     */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showResetForm(Request $request)
    {
        $token      = $request->route()->parameter('token');
        $email      = $this->getEmailByToken($token);
        $checkToken = $this->broker()->validateReset(['token' => $token, 'email' => $email]);

        if (in_array($checkToken, [$this->broker()::INVALID_TOKEN, $this->broker()::INVALID_USER])) {
            return $this->notValidView();
        }

        return view('auth.passwords.reset')->with(
            ['token' => $token]
        );
    }

    public function notValidView()
    {
        return view('partials.error', [
            'error' => trans($this->broker()::INVALID_TOKEN)
        ]);
    }

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function reset(Request $request)
    {
        $request->validate($this->rules(), $this->validationErrorMessages());

        $email    = $this->getEmailByToken($request->token);
        $response = $this->broker()->reset(
            $this->credentials($request, $email),
            function ($user, $password) {
                $this->resetPassword($user, $password);
            }
        );

        return $response == Password::PASSWORD_RESET
        ? $this->sendResetResponse($request, $response)
        : $this->sendResetFailedResponse($request, $response);
    }

    protected function rules()
    {
        return [
            'token'    => 'required',
            // 'email'    => 'required|email',
            'password' => [
                'required', 'confirmed', 'max:16', PasswordRule::min(8)
                    ->letters()
                    ->mixedCase()
                    ->numbers()
            ]
        ];
    }

    protected function getEmailByToken($token)
    {
        $prefix = config('srm_config.installer.table_prefix', 'srm_');
        return DB::table($prefix . 'password_resets')
            ->select('email')
            ->where('token', Hash::check($token, 'token'))
            ->first()->email;
    }

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
     * @param  string  $password
     * @return void
     */
    protected function resetPassword($user, $password)
    {
        $this->setUserPassword($user, $password);

        $user->setRememberToken(Str::random(60));

        $user->setLastChangePasswordIPAddress(request()->server("REMOTE_ADDR"));

        $user->save();

        $user->sendPasswordResetConfirmationNotification($user);
    }

    protected function credentials(Request $request, $email)
    {
        return array_merge(['email' => $email], $request->only(
            'password', 'password_confirmation', 'token'
        ));
    }

}
