class UsersController < ApplicationController
  include SessionsHelper
  before_action :logged_in_user,  only: [ :index, :edit, :update, :destroy ]
  before_action :correct_user,    only: [ :edit, :update ]
  before_action :admin_user,      only: [ :destroy ]

  def index
    # @users = User.all
    # @users = User.order(:name).page(params[:page])
    @users = User.where(activated: true).page(params[:page])
  end

  def show
    @user = User.find(params[:id])
    redirect_to root_url and return unless @user.activated?
    # debugger
  end
  def new
    @user = User.new
    # debugger
  end

  def create
    @user = User.new(user_params)
    if @user.save
      # reset_session
      # log_in @user
      # flash[:success] = "Welcome to the Sample App!"
      # redirect_to @user
      # redirect_to user_url(@user)
      begin
        @user.send_activation_email
        flash[:info] = "Please check your email to activate your account."
        redirect_to root_url
      rescue => e
        logger.error "User creation failed: #{e.message}"
        flash[:danger] = "Something went wrong. Please try again."
        render "new", status: :unprocessable_entity
      end
    else
      render "new", status: :unprocessable_entity
    end
  end

  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
      # redirect_to user_url(@user)
    else
      render "edit"
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to users_url
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password,
                                 :password_confirmation)
  end

  def logged_in_user
    unless logged_in?
      store_location
      flash[:danger] = "Please log in."
      redirect_to login_url
    end
  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
