class UsersController < ApplicationController
  # # get users/new
  before_action :logged_in_user,only:[:index,:edit,:update,:destroy]
  before_action :correct_user,only:[:edit,:update]
  before_action :admin_user,only: :destroy


  def new
    @user = User.new
  end
  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page:params[:page])
    # debugger
  end
  
 def index
  @users = User.paginate(page:params[:page])
 end
  
  def create
   # debugger
   @user = User.new(user_params)
   if @user.save
    # GET "/users/#{@user.id}"
    # redirect_to userpath(@user)
    # redirect_to userpath(@user.id)
    # redirect_to userpath(1)
    @user.send_activation_email
    flash[:info] = "Please check your email to activate your account."
    redirect_to root_url    #success (valid params)
   else
    #failure (invalid params)
    render 'new'
   end
  end
  # GET /users/[id]/edit
  def edit
    @user = User.find(params[:id])
    
  end
  def update
    @user = User.find(params[:id])
    if @user.update(user_params)
    flash[:success] = "Profile updated" 
    redirect_to @user
    else
      render 'edit'
    end
  end
  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to users_path
  end
  
  
  private 
 
  def user_params
    params.require(:user).permit(:name, :email,
   :password ,:password_confirmation)
  end


  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_url) unless current_user?(@user)
  end
  def admin_user
    redirect_to(root_url) unless current_user.admin?
    
  end
  
  
end
