class NewSuppliersController < ApplicationController
  def index
    new
    render 'new'
  end

  def new
    @new_supplier = NewSupplier.new
    @new_supplier.current_employee = current_employee
    @page = Page.find_by_name_and_locale('suppliers-signup', I18n.locale.to_s)
    @page ||= Page.new(title: 'Signup as a restaurant')
  end

  def create
    @new_supplier = NewSupplier.new(params[:new_supplier])
    @new_supplier.current_employee = current_employee

    if @new_supplier.existing_employee?
      if @new_supplier.supplier_name.present? && @new_supplier.new_supplier_name?
        save_new_supplier
      else
        sign_in @new_supplier.employee
        if @new_supplier.employee.suppliers.size < 2
          session[:supplier_id] = @new_supplier.employee.suppliers.first.try(:id)
          redirect_to supplier_root_path
        else
          render "choose_supplier"
        end
      end
    else
      save_new_supplier
    end
  end

  def choose_supplier

  end

  private

  def save_new_supplier
    if @new_supplier.save
      sign_in @new_supplier.employee unless current_employee
      Notifier.new_supplier(@new_supplier.supplier.try(:id), @new_supplier.employee.id).deliver_later
      session[:supplier_id] = @new_supplier.supplier.try(:id)
      redirect_to supplier_root_path(anchor: '/pages/introduction')
    else
      @page = Page.find_by_name_and_locale('suppliers-signup', I18n.locale.to_s)
      @page ||= Page.new(title: 'Signup as a restaurant')
      render 'new'
    end
  end
end
