# -*- encoding : utf-8 -*-

class Admin::SurveyTypesController < ApplicationController
  layout "admin"
  before_filter :auth_admin
  
  def index
    @surveys = SurveyType.all
    
  end
  
  def show

    @survey = SurveyType.find(params[:id])
    #render :layout => "application"
  end
  
  def export
    @survey = SurveyType.find(params[:id])
    
    @survey_sets = @survey.survey_sets.where(:is_fill => true)
    
    @survey_sets = @survey_sets.where("created_at < ?", Date.parse("2017/06/27").beginning_of_day)
    
    respond_to do |format|
          format.html
          
          
          
          format.csv { 
            
            @file = ""
           
           
             headers = []
            headers << "id"
            headers << "date"
            @survey.items.each do |survey_item|
              headers << survey_item.title
                
        
              if survey_item.questions_type == 3
                survey_item.answers.each do |survey_item_answer|
                  headers << survey_item_answer.label_text
                end
              end
            end
           

            
            @csv = CSV.generate(:headers => true, :col_sep => ";") do |csv|
              csv << headers
              
              
              
              
              @survey_sets.each do |survey_set|
                line = []
                
                line << survey_set.id
                line << survey_set.created_at
                survey_set.survey_type.items.each do |survey_item|
                  question_set = survey_set.question_sets.find_by_survey_item_id(survey_item.id)
                  line <<question_set.content
      
      
                  if survey_item.questions_type == 3
                    survey_item.answers.each do |survey_item_answer|
                    
                      answer_set = question_set.answer_sets.find_by_survey_item_answer_id(survey_item_answer.id)
                      rep = ""
                      if answer_set
                        if answer_set.content?
                          rep = answer_set.content
                        else
                          rep = "oui" if answer_set.is_checked
                        end
                      end
                      line << rep
          
                    end
                  end
                end
                csv << line
              end
            
              
            
            end
              
              
            
            
            send_data @csv.encode('iso-8859-1', :undef => :replace, :replace => ''), :filename => "export-survey-#{Date.today.to_s.to_slug}.csv", :type => 'text/csv; charset=iso-8859-1; header=present' }
    end
    
    
    
    
    
    
    
  end
  
end
