# encoding: utf-8
class Admin::SeminarSignupsController < OrbitAdminController
  include Admin::SeminarsHelper
  before_action ->(module_app = @app_title) { set_variables module_app }
  before_action :check_manager_for_seminar
  def initialize
    super
    @app_title = "seminar"
  end
  def check_manager_for_seminar
    OrbitHelper.set_params(params,current_user)
    access_level = OrbitHelper.user_access_level?
    if (access_level.nil? || access_level == "user")
      @seminar = SeminarSignup.find(params[:id]).seminar_main rescue nil
      if (@seminar.organizer_id != current_user.member_profile_id rescue true)
        render_401
      end
    end
  end
  def edit
    OrbitHelper.set_params(params,current_user)
    params[:controller] = "admin/seminars"

    @seminar_signup = SeminarSignup.find(params[:id])
    @seminar = SeminarMain.find(@seminar_signup.seminar_main_id)

    @form_index = 0 

  end

  def update
    
    @seminar_signup = SeminarSignup.find(params[:id])
    @seminar_signup.update_attributes(seminar_signup_params)

    if !params[:seminar_signup_values].nil?
      params[:seminar_signup_values].each_with_index do |r,i|
        field_value = r.last[:id].present?
        @custom_field_value = SeminarSignupValue.put_field_values(@seminar_signup, r.last, r.last[:id], field_value)
      end
      seminar_reviews = SeminarReview.where(:seminar_main_id=>@seminar_signup.seminar_main_id).to_a
      seminar_reviews.each{|sr| sr.save}
      @seminar = @seminar_signup.seminar_main
      unassigned_seminar_signup_ids = @seminar.seminar_signup_ids.map{|s| s.to_s}
      @seminar.seminar_reviews.each do |sr|
        unassigned_seminar_signup_ids = unassigned_seminar_signup_ids - sr.all_seminar_signup_ids
      end
      @seminar.unassigned_seminar_signup_ids = unassigned_seminar_signup_ids
      @seminar.save
    end

    redirect_to "/admin/seminars/#{@seminar_signup.seminar_main_id}/seminar_signup"

  end

  def destroy
    @seminar_signup = SeminarSignup.find(params[:id])

    @seminar_main_id = @seminar_signup.seminar_main_id

    @seminar_signup.destroy

    redirect_to "/admin/seminars/#{@seminar_main_id}/seminar_signup"
  end

  private

  def seminar_signup_params
    params.require(:seminar_signup).permit!
  end
end
