require 'csv'

class EmailController < ApplicationController

  respond_to :csv

  def dump_emailables

    if params[:code] != Rails.application.config.email_dump_code
      render :text => "", :status => 404
      return
    end

    headers['Content-Disposition'] = "attachment; filename=\"user-list.csv\""
    headers['Content-Type'] ||= 'text/csv'

    @users = User.where(subscribe_email: true)

    # if specified, return only users that have redeemed or bought a JamTrack
    if params[:any_jam_track]
      @users = @users.select('DISTINCT users.id, email, first_name, last_name').joins(:sales => :sale_line_items).where("sale_line_items.product_type = 'JamTrack'")
    end
  end

  def dump_teachers

    if params[:code] != Rails.application.config.email_dump_code
      render :text => "", :status => 404
      return
    end

    headers['Content-Disposition'] = "attachment; filename=\"teacher-list.csv\""
    headers['Content-Type'] ||= 'text/csv'

    @users = User.joins(:teacher)

    render "dump_emailables.csv.erb"
  end
end