<?php

namespace App\Http\Controllers\Auth;

use App\Facade\Theme;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;

class ChangePasswordController extends Controller
{
    use ResetsPasswords;

    /**
     * Where to redirect users after a password reset.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function processChangePassword(Request $request)
    {
        $this->validate($request, ['password' => 'required|confirmed|min:6']);

        // Here we will attempt to reset the user's password. If it is successful we
        // will update the password on an actual user model and persist it to the
        // database. Otherwise we will parse the error and return the response.
        $response = $this->broker()->reset(
            $this->credentials($request), function ($user, $password) {
                $this->resetPassword($user, $password);
            }
        );

        // If the password was successfully reset, we will redirect the user back to
        // the application's home authenticated view. If there is an error we can
        // redirect them back to where they came from with their error message.
        return $response == Password::PASSWORD_RESET
            ? $this->sendResetResponse($response)
            : $this->sendResetFailedResponse($request, $response);
    }

    public function showChangePasswordForm(Request $request)
    {
        return Theme::render('auth.passwords.change_password');
    }

    protected function credentials(Request $request)
    {
        $data = $request->only('password', 'password_confirmation', 'token');
        $data['email'] = Auth::user()->email;

        // Create a token for the password broker to validate
        $data['token'] = $this->broker()->createToken($this->getUser());

        return $data;
    }

    protected function sendResetResponse($response)
    {
        return redirect($this->redirectPath())
            ->with('status', trans('passwords.changed'));
    }
}