class PortionsController < ApplicationController
  before_action :user_is_editor?
  before_action :set_portion, only: [:edit, :update, :destroy]
  layout "admin"
  
  def index
    @portions = Portion.all
  end

  def show
    redirect_to portions_path
  end

  def new
    @portion = Portion.new
  end

  def edit
  end

  def create
    @portion = Portion.new(portion_params)
    @portion.id = Portion.all.order(id: :asc).last.id + 1
    if @portion.save
      redirect_to portions_path, notice: 'Alimento creado correctamente'
    else
      render :new
    end
  end

  def update
    if @portion.update(portion_params)
      redirect_to portions_path, notice: 'Alimento guardado correctamente'
    else
      render :edit
    end
  end

  def destroy
    @portion.meal_portions.delete_all
    @portion.destroy
    redirect_to portions_url, notice: 'Alimento eliminado'
  end

  private

    def set_portion
      @portion = Portion.find(params[:id])
    end

    def portion_params
      params.require(:portion).permit(:unit, :quantity, :name, :cals, :carbs, :proteins, :fats, :calories, :fiber, :category)
    end
end
