class Admin::Accounting::Paya::FormsController < Admin::Accounting::Controller
  def payform
    render_success :ok, json: form_service
  end

  def accountform
    render_success :ok, json: form_service
  end

  private
    def form_service
      Paya::FormService.call(current_school, action_name.to_sym, options)
    end

    def product_info
      @product_info ||= Paya::ProductService.new(current_school).find_product(:cc, :family)
    end

    def family
      @family ||= current_school.families.find_by(id: params[:family_id])
    end

    def contact
      @contact ||= family.contacts.find_by(id: params[:contact_id])
    end

    def options
      {}.tap do |props|
        props[:payment_method] = params[:payment_method]
        props[:family] = family

        if action_name.to_sym == :payform
          props[:subtotal] = params[:subtotal]
          props[:surcharge] = surcharge
          props[:product_transaction_id] = product_info['id']
        else
          props[:contact] = contact
        end
      end
    end

    def surcharge
      return unless product_info['surcharge']

      rate = product_info['surcharge']['surcharge_rate'].to_f
      return params[:subtotal].to_f * (rate / 100) unless rate.zero?

      product_info['surcharge']['surcharge_fee']
    end
end
