class Store::OrdersController < Store::StoreController
  include ActionView::Helpers::TextHelper
  include ArtfullyOseHelper
  
  def update
    handler = OrderHandler.new(current_cart, current_member)
    handler.handle_tickets(params)    
    handler.handle_donation(params, @store_organization)
    handler.handle_memberships(params, current_member)
    handler.handle_passes(params)
    handler.handle_discount(params)
    handler.apply_pass(params)

    flash[:alert] = handler.error unless handler.error.blank?

    redirect_to store_order_path
  end

  def show

    @special_instructions_hash = {}
    current_cart.tickets.each do |ticket|
      event = ticket.event
      if event.show_special_instructions?
        @special_instructions_hash[event.id] = event.special_instructions_caption
      end
    end

    if member_signed_in?
      params[:first_name] ||= current_member.person.first_name
      params[:last_name]  ||= current_member.person.last_name
      params[:email]      ||= current_member.person.email
      params[:phone]      ||= current_member.person.phones.first.try(:number)

      params[:address]    ||= {}
      params[:address][:address1] = current_member.person.address.try(:address1)
      params[:address][:country] = current_member.person.address.try(:country)
      params[:address][:city] = current_member.person.address.try(:city)
      params[:address][:state] = current_member.person.address.try(:state)
      params[:address][:zip] = current_member.person.address.try(:zip)

    end
  end

  def destroy
    current_cart.clear!
    flash[:notice] = "Your cart is empty."
    redirect_to (session[:last_event_id].blank? ? store_order_path : store_old_storefront_event_url(session[:last_event_id]))
  end

  private

    #
    # The storefront javascript depends on this total_string to determine 
    # if this is a free order or not. Don't re-word this string without also
    # addressing the javascript in store.js
    #
    def total_string
      "#{pluralize(current_cart.items.length, 'item')}, #{number_as_cents current_cart.total}"
    end

    def event
      current_cart.tickets.first.event
    end
end