class ContactsController < ApplicationController
  before_action :authenticate, only: [:export] if Rails.env.production?

  def new
    @student = Contact.new
    @teacher = Contact.new
    @states  = State.all
    @empty   = []
  end

  def state_cities

    @state = State.find(params[:id])
    @cities = {}

    @state.cities.each do |c|
      @cities[c.id] = c.name
    end

    respond_to do |format|
      format.json { render json: @cities }
    end

  end

  def create
    @states  = State.all
    @empty   = []

    if params[:contact][:kind].to_s == "Estudiante"
      @teacher = Contact.new
      @student = Contact.new(item_params)
      if @student.save
        redirect_to thanks_contacts_url
      else
        render action: :new
      end
    else
      @teacher = Contact.new(item_params)
      @student = Contact.new
      if @teacher.save
        redirect_to thanks_contacts_url
      else
        render action: :new
      end
    end
  end

  def thanks
  end

  def export
    @items = Contact.all
    respond_to do |format|
      format.html
      format.csv { send_data @items.to_csv, filename: "contacts-#{Date.today}.csv" }
    end
  end

  protected
    def authenticate
      authenticate_or_request_with_http_basic do |username, password|
      username == "alphabetize" && password == "sdfeer547suyd"
    end
  end

  private
    def item_params
      params
        .require(:contact)
        .permit(:name, :phone, :gender, :state_id, :email, :city_id, :kind)
    end
end
