<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use Validator;
use App\User;
use Hash;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    public function getIndex(){
        $users = User::paginate(10);
        return view('users.index')
            ->with('title', "Users")
            ->with('users', $users);
    }

    public function postCreate(Request $request){
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:50',
            'email' => 'required|email|max:50|unique:users',
            'password' => 'required|confirmed|min:6',           
        ]);

        if (!$validator->fails()) {
            $user = new User;
            $user -> name   = $request -> name;
            $user -> email  = $request -> email;  
            $user -> password  = Hash::make($request -> password);      
            $user -> save();   
            return back();          
        }else{
            return back() -> withErrors($validator);
        }
    }

    public function getEdit($id){
        $user = User::find($id);       
        return view('users.edit')
            ->with('user', $user);
    }

    public function postEdit(Request $request, $id){

        $validator = Validator::make($request->all(), [
            'name' => 'required|max:50',
            'password' => 'required|confirmed|min:6',           
        ]);

        $user = User::find($id);

        if (!$validator->fails()) {
            $user -> name   = $request -> name;
            $user -> password  = Hash::make($request -> password);
            $user -> save(); 
            return back() ->withErrors('User has been updated.');          
        }else{
            return back() -> withErrors($validator);
        }
        
    }

    public function getDestroy($id){
        $user = User::find($id);
        if($user){
            $user -> delete();
            return back();
        }
        return back();
    }

    public function getConfig(){
        return view('users.config');
    }
}