<?php


namespace App\Http\Controllers;

use Auth;
use Validator;
use Request;
use Illuminate\Support\Facades\Hash;
use App\Repositories\UserRepository;



class UserDeleteController extends Controller
{


    protected $userRepo;

    /**
     * UserController constructor.
     * @param UserRepository $userRepo
     */
    public function __construct(UserRepository $userRepo)
    {
        $this->middleware('auth');
        $this->userRepo = $userRepo;
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function deleteAccount(){
        return view('user.delete_account');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function deleteAccountAction(Request $request)
    {
        $user = Auth::user();

        $rules = array(
            'old_password' => 'required|old_password:' . Auth::user()->password,
        );

        Validator::extend('old_password', function ($attribute, $value, $parameters, $validator) {

            return Hash::check($value, current($parameters));

        });

        $validator = Validator::make(Request::all(), $rules);

        if ($validator->fails()) {

            // get the error messages from the validator
            $messages = $validator->messages();
            // redirect our user back to the form with the errors from the validator
            return view('user.delete_account')->withErrors($validator);

        }else{
            $this->userRepo->deleteUser($user);
            //make delete
            Auth::logout();
            \Session()->flash('alert-danger', __('account deleted'));
            return redirect(route('home'));
        }
    }
}