class Admin::UnitsController < ApplicationController
  before_action :set_unit, except: [:index, :new, :create]

  def index
    @units = Unit.all
  end

  def new
    @unit = Unit.new
  end

  def create
    @unit = Unit.new(unit_params)
    if @unit.save
      flash[:notice] = "#{t('unit.name').capitalize} \"#{@unit.name.capitalize}\" #{t('notice.success')} #{t('notice.create')}"
      redirect_to admin_units_path
    else
      render :new
    end
  end

  def edit
    @units = Unit.find(params[:id])
  end

  def update
    if @unit.update(unit_params)
      redirect_to admin_units_path
      flash[:notice] = "#{t('unit.name').capitalize} \"#{@unit.name.capitalize}\" #{t('notice.success')} #{t('notice.edit')}"
    else
      render :edit
      flash[:notice] = "#{t('notice.error')}: #{t('add.error')}"
    end
  end

  def destroy
    @unit.destroy
    redirect_to admin_units_path
    flash[:notice] = "#{t('unit.name').capitalize} \"#{@unit.name.capitalize}\" #{t('notice.success')} #{t('notice.delete')}"
  end

    private

    def unit_params
      params.require(:unit).permit(:name, :abbreviation)
    end

    def set_unit
      @unit = Unit.find(params[:id])
    end
end
