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

class Admin::NewslettersController < ApplicationController

	before_filter :auth_admin
	
	layout "admin"
	


	before_filter :find_newsletters

	def index 

	end


	def cible
		
		render :layout => false
		
	end
	
	
	def new
	
		@newsletter = Newsletter.new(:published_at => Time.now)

	end


	def edit
	
		@newsletter = Newsletter.find(params[:id])
    
		
	end


	def create
		
		@newsletter = Newsletter.new(newsletter_params)

		
		if @newsletter.save
			flash[:notice] = "L'newsletter à été ajouté avec succès."
			self.find_newsletters
		
		else
			render :action => "new" 

		end

	end


	def update
	
		@newsletter = Newsletter.find(params[:id])
	
  
    if params[:newsletter]
  		if @newsletter.update_attributes(newsletter_params)
  			flash[:notice] = "L'newsletter à été modifié avec succès."
  		else
  			render :action => "edit"
  		end
      
      
    elsif params[:tag_id]
      @newsletter.tag_by_tag_ids(params[:tag_id])
    end
    
  
  
		
	end


	def destroy
	
		@newsletter = Newsletter.find(params[:id])
		@newsletter.destroy

	end
	
	protected
	
	def find_newsletters
		date_regex = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/i 
		if params[:start] and params[:start] =~ date_regex
			start = Date.parse(params[:start]).beginning_of_day 
			params[:start]= start.strftime('%d/%m/%Y')
		else
			params[:start] = ""
		end
		if params[:stop] and params[:stop] =~ date_regex
			stop = Date.parse(params[:stop]).end_of_day 
			params[:stop]= stop.strftime('%d/%m/%Y')
		 else
		 	params[:stop] = ""
		end
		
		@newsletters = Newsletter.order('published_at DESC')
		@newsletters = @newsletters.after(start) if start
		@newsletters = @newsletters.before(stop) if stop
		per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 5000
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
		@newsletters = @newsletters.page(page).per(per_page)

		#@newsletters = Event.order('start_at, stop_at').after(start).before(stop)
	end
	
  private
    def newsletter_params
      params.require(:newsletter).permit(:category_id, :enabled, :published_at, :title, :slug, :tags_cache, :description, :image_file_id)
      
  
      
      
    end

  
end
