<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    /**
     * Index method
     *
     * @return response()
     */
    public function index()
    {
        if(Auth::check()){
            return redirect()->route("dashboard");
        }
        return view('auth.login');
    }  
      
    /**
     * Registration
     *
     * @return response()
     */
    public function registration()
    {
        return view('auth.register');
    }
      
    /**
     * Login post 
     *
     * @return response()
     */
    public function postLogin(Request $request)
    {
        $request->validate([
            'email' => 'required',
            'password' => 'required',
        ]);
   
        // $user= User::where('email',$request->email)->first();
        // $user->password= Hash::make($request->password);
        // $user->save();

        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            return redirect()->route('dashboard')
                        ->withSuccess('You have Successfully loggedin');
        }
  
        return redirect()->route("login")->withErrors('Oppes! You have entered invalid credentials');
    }
      
    /**
     * Registration post
     *
     * @return response()
     */
    public function postRegistration(Request $request)
    {  
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);
           
        $data = $request->all();
        $check = $this->create($data);
         
        return redirect()->route("dashboard")->withSuccess('Great! You have Successfully loggedin');
    }
    
    /**
     * Dashboard
     *
     * @return response()
     */
    public function dashboard()
    {
        if(Auth::check()){
            return view('dashboard');
        }
  
        return redirect()->route("login")->withSuccess('Opps! You do not have access');
    }
    
    /**
     * Create user
     *
     * @return response()
     */
    public function create(array $data)
    {
      return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password'])
      ]);
    }

    # Change Password
    public function changePassword(Request $request)
    {
        # Validation
        $validator = Validator::make($request->all(), [
            'old_password' => 'required',
            'new_password' => 'required|confirmed',
        ]);

        if ($validator->fails()){
            $errors = $validator->errors();
            return $this->returnErrorResponse($errors->first());

        }

        try{
            #Match The Old Password
            if(!Hash::check($request->old_password, auth()->user()->password)){
                return $this->returnErrorResponse("Old password doesn't match");
            }

            #Update the new Password
            $update = User::whereId(auth()->user()->id)->update([
                'password' => Hash::make($request->new_password)
            ]);

            if($update){
                return $this->returnResponse();
            }
            return $this->returnErrorResponse();
        }catch(\Exception $e){
            return $this->returnErrorResponse();
        }
    }
    
    /**
     * Logout
     *
     * @return response()
     */
    public function logout() {
        Session::flush();
        Auth::logout();
  
        return redirect()->route('login');
    }
}
