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

  def index
    @routines = @plan.routines
  end

  def show
  end

  def new
    @routine = Routine.new
  end

  def edit
  end

  def create
    @routine = Routine.new(routine_params)
    if @routine.save
      redirect_to @routine, notice: "La rutina ha sido creada."
    else
      render :new, status: :unprocessable_entity
    end
  end

  def update
    if @routine.update(routine_params)
      redirect_to @routine, notice: "La rutina ha sido actualizada."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @routine.destroy
    redirect_to routines_url, notice: "La rutina ha sido eliminada."
  end

  private

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

    def set_routine
      @routine = Routine.find(params[:id])
    end

    def routine_params
      params.require(:routine).permit(
        :title, :instructions, :description, :number, 
        routine_workouts_attributes:  [
          :id, :_destroy, :routine_id, :category, :category, :workout_id, :series, :notes, :repetitions, :workout_series, :number, :group_by_series, :charge
        ]
      )
    end

end