class Admin::UsersController < Admin::AdminController

  before_action :set_user, only: %i[ edit update destroy ]

  helper_method :sorting_technique


   # GET /users
  def index
    @users = User.public_send(sorting_technique, params[:reverse].present?)
                 .simple_search(params[:q])
                 .page(params[:page] || 1)
  end


  # GET /users/new
  def new
    @user = User.new
  end


  # GET /users/1/edit
  def edit
  end


  # POST /users or /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to edit_admin_user_url(@user), notice: t(:'users.created') }
      else
        format.html { render :new, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1 or /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to edit_admin_user_url(@user), notice: t(:'users.updated') }
      else
        format.html { render :edit, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1 or /users/1.json
  def destroy
    @user.destroy!

    respond_to do |format|
      format.html { redirect_to url_for(action: :index), notice: t(:'users.destroyed') }
    end
  end


private



  def sorting_technique
    params[:sort].presence_in(%w(by_name by_email by_last_modified)) || :by_name
  end


  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end


  # Only allow a list of trusted parameters through.
  def user_params
    params.require(:user).permit(
      :enabled_at,
      :title,
      :role,
      :phone,
      :firstname,
      :lastname,
      :email,
      :password,
      :password_confirmation
    )
  end

end
