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

class Admin::MailTemplatesController < ApplicationController
	before_filter :auth_admin

	layout "admin"


	before_filter :find_mail_templates

  
  def new
        
      
  		@mail_template = MailTemplate.new()
      
  end
    
  def create
    @mail_template = MailTemplate.new(params.require(:mail_template).permit!)
    if @mail_template.save
     redirect_to admin_mail_templates_path(), notice: '' 
    
    else
        render action: "new"
 
    end
  end
  


	def index 
    respond_to do |format|
      format.html
    
    
    
      format.csv { 
      
        @file = ""
      
        elements = {
        

          "locale" => "locale",
          "key" => "key",
          "value" => "value",
          
        
        }
      
   
      
        headers = []
        attributes = []
      
        elements.each do |key, value|
          headers << key
          attributes << value
        end
      
        @csv = CSV.generate(:headers => true, :col_sep => ";", :encoding => "UTF-8") do |csv|
          csv << headers
        
          MailTemplate.all.each do |trans|
        
              csv << attributes.map{ |attr| eval("trans."+attr.to_s) }

          end
        
        end
      
    send_data @csv, :filename => "export-mail_templates-#{Date.today.to_s.to_slug}.csv", :type => 'text/csv; header=present' }
	
  end
  end



	def edit
		@mail_template = MailTemplate.find(params[:id])
	end


	

	def update
		@mail_template = MailTemplate.find(params[:id])


		
	
		
		
			if @mail_template.update_attributes(params.require(:mail_template).permit!)
				
        redirect_to :action => :index
			
				flash[:notice] = "Le template à été modifié avec succès."
				
      end
			

    
    
    
    

	end

	protected
	
	def find_mail_templates    
    
    @mail_templates = MailTemplate.all #.order("key ASC")
		

	
  end
  
end
