class OnboardingsController < ApplicationController
  before_action :set_owner, only: [:index, :submit_onboarding]

  def index
    # Make sure to set @owner first. If not found, you should redirect or handle the error appropriately.
    set_owner
  
    if @owner
      # Initialize onboarding items for each form if they don't exist yet for the owner.
      @forms = Form.all
      @forms.each do |form|
        @owner.onboarding_items.find_or_initialize_by(form: form)
      end
      # After building or finding the onboarding items, load them for the view.
      # This ensures we're only working with items related to the current owner.
      @onboarding_items = @owner.onboarding_items.includes(:form)
    else
      # Handle the scenario where @owner is not found. Redirect or show an error.
      redirect_to root_path, alert: "Owner not found."
    end
  end

  def create
    # Assuming `onboarding_items_params` method will handle mass assignment
    @onboarding_item = @owner.onboarding_items.build(onboarding_items_params)
    
    if @onboarding_item.save
      redirect_to polymorphic_path([@owner, :onboardings]), notice: 'Onboarding item was successfully created.'
    else
      # This assumes you have an instance variable @forms for the form dropdown in the view
      @forms = Form.all
      render :index, status: :unprocessable_entity
    end
  end
  
  def submit_onboarding
    @owner = find_owner
    onboarding_items_params.values.each do |item_params|
      item = OnboardingItem.find_or_initialize_by(id: item_params.delete(:id))
      item.assign_attributes(item_params)
      item.owner = @owner
      item.save
    end
    redirect_to polymorphic_path(@owner), notice: 'Onboarding information updated successfully.'
  end
  

  private
  
  def set_owner
    params.each do |name, value|
      if name =~ /(.+)_id$/
        model_name = name.match(/(.+)_id$/)[1].classify
        @owner = model_name.constantize.find(value)
        break
      end
    end
    unless @owner
      redirect_to root_path, alert: "Owner not found."
    end
  end

  def onboarding_items_params
    params.permit(onboarding_items: [:id, :note, :date_completed]).fetch(:onboarding_items, {})
  end

  def find_owner
  # Check each expected owner type and find the corresponding record
    if params[:participant_id]
      @owner = Participant.find(params[:participant_id])
    elsif params[:employer_id]
      @owner = Employer.find(params[:employer_id])
    elsif params[:worker_id]
      @owner = Worker.find(params[:worker_id])
    elsif params[:vendor_id]
      @owner = Vendor.find(params[:vendor_id])
    else
    # Handle the case where no recognized owner parameter is provided
      redirect_to root_path, alert: "Owner not found."
    return nil
    end
  end
end