class Www::ComplaintsController < WwwController

  before_filter :load_states, :load_occupations, :load_institutions, :build_breadcrumb, :applications_category
  before_filter :redirect_to_sac

  def new
    @complaint = Complaint.new
    if params[:institution_id]
      @complaint.institution_id = params[:institution_id].to_i
    end
    @complaint.textcaptcha
  end

  def create

    @complaint = Complaint.new(params[:complaint])
    @complaint.confirmed = true

    if @complaint.save

      @complaint.deliver_complaint
      redirect_to confirm_www_complaint_path(@complaint)

    else
      unless @complaint.state_id.blank?
        @cities = State.find(@complaint.state_id).cities.order(:name)
      end
      unless @complaint.occurred_state_id.blank?
        @occurred_cities = State.find(@complaint.occurred_state_id).cities.order(:name)
      end
      render action: :new
    end
  end

  def please_confirm

    if session[:complaint_id]
      @complaint = Complaint.find(session[:complaint_id])
      session.delete :complaint_id
    else
      render_404
    end
  end

  def confirm
    @complaint = Complaint.find params[:id]
    #
    # if @complaint
    #   # occurred state_id is required
    #   @complaint.occurred_state_id = @complaint.occurred_city.state.id
    #   @complaint.confirmed = true
    #   @complaint.save
    #   @complaint.deliver_complaint
    #   # Expire token
    #   @complaint.get_confirm_email_token.use!
    # else
    #   render_404
    # end
  end

  def redirect_to_sac
    redirect_to "https://www.atencionciudadana.sv/"
  end

  private

    def load_states
      @states = State.order(:name)
    end

    def load_occupations
      @occupations = Occupation.order(:name)
    end

    def load_institutions
      @institutions = Institution.where(at_complaints: true).order(:name)
    end

    def build_breadcrumb
      add_breadcrumb I18n.t('www.layout.home'), www_root_path
      add_breadcrumb t('www.complaints.new.title')
    end

end
