
class MealsController < ApplicationController
  before_action :user_is_admin?
  before_action :set_meal, only: %i[ show edit update destroy ]
  before_action :set_plan, only: %i[ index ]
  layout "admin"

  def index
    @meals = @plan.meals.order(:number)
    @complements = Program.where(tipo: "meal").order(:number)
  end

  def show
  end

  def new
    @meal = Meal.new
  end

  def edit
  end

  def create
    @meal = Meal.new(meal_params)

    if @meal.save
      redirect_to @meal, notice: "Comida creada."
    else
      render :new, status: :unprocessable_entity
    end
  end

  def update
    if @meal.update(meal_params)
      redirect_to @meal, notice: "Comida actualizada."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @meal.destroy
    redirect_to meals_url, notice: "Comida eliminada."
  end

  private

    def set_meal
      @meal = Meal.find(params[:id])
    end

    def set_plan
      @plan = Plan.find(params[:plan_id])
    end

    def meal_params
      params.require(:plan).permit(:title, :number, :body,
        meal_portions_attributes: [:_destroy, :id, :quantity, :meal_id, :portion_id, :number,
          substitutes_attributes: [:_destroy, :id, :portion_id, :quantity]
        ])
    end

end