class ProgramsController < ApplicationController
  before_action :user_is_admin?
  before_action :set_program, only: [:show, :edit, :update, :destroy]
  layout "admin"
  
  def index
    @routines = Program.where(tipo: "routine").order(:number)
    @diets = Program.where(tipo: "diet").order(:number)
    @meals = Program.where(tipo: "meal").order(:number)
  end

  def sort
    ids = params["ids"].split("_")
    ids.each_with_index { |id, index| Program.find(id.to_i).update(number: index)  }
  end

  def new
    @plan = Plan.create(user_id: current_user.id)
    @program = Program.new({ tipo: params[:tipo], plan_id: @plan.id })
  end

  def create
    @program = Program.new(program_params)
    if @program.save
      @program.update(plan: Plan.create({ init: Date.yesterday, finish: Date.yesterday, trainer_id: current_user.id, user_id: current_user.id }))
      redirect_to "/plans/#{@program.plan.id}/edit" #, notice: "Programa #{@program.title} creado"
    else
      render :new
    end
  end

  def update
    if @program.update(program_params)
      redirect_to programs_path #, notice: 'Programa actualizado'
    else
      render :edit
    end
  end

  def destroy
    @program.destroy
    redirect_to programs_url #, notice: 'Programa eliminado'
  end

  private

    def set_program
      @program = Program.find(params[:id])
    end

    def program_params
      params.require(:program).permit(:plan_id, :title, :number, :tipo)
    end

end