ActiveAdmin.register JamRuby::User, :as => 'Referrals' do

  menu :label => 'Referrals', :parent => 'Affiliates'

  config.sort_order = 'created_at DESC'
  config.batch_actions = false
  config.clear_action_items!
  config.filters = true

  filter :affiliate_referral
  filter :email

  ## scope("Has Signups", default: true) { |scope| scope.where('visits != 0 or signups != 0').order('day desc') }

  index do
    column 'User' do |oo| link_to(oo.name, oo.admin_url, {:title => oo.name}) end
    column 'User Email' do |oo| oo.email end
    column 'Created' do |oo| oo.created_at end
    column 'Partner ID' do |oo| oo.affiliate_referral.id end
    column 'Partner Name' do |oo| oo.affiliate_referral.display_name end
    column 'Partner User' do |oo| link_to(oo.affiliate_referral.partner_user.name, admin_user_path(oo.affiliate_referral.partner_user.id), { :title => oo.affiliate_referral.partner_user.name }) end
  end

  controller do

  def scoped_collection
    rel = end_of_association_chain
      .includes([:affiliate_referral])
      .order('created_at DESC')
    if (ref_id = params[AffiliatePartner::PARAM_REFERRAL]).present?
      qq = ['affiliate_referral_id = ?', ref_id]
    else
      qq = ['affiliate_referral_id IS NOT NULL']
    end
    @users ||= rel.where(qq)
  end

  end
end
