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

class Admin::NewslettersController < ApplicationController
	before_filter :authenticate_admin!

	
	layout "admin"
	navigation :newsletters


	def index
		@newsletters = Newsletter.order('subject ASC')
		if request.xhr?
			render :layout => false
			
		end
	end

	def new

	
		@newsletter = Newsletter.new()
	end
	
	def create

		@newsletter = Newsletter.new(params[:newsletter])

		puts params[:newsletter][:subject]
		if @newsletter.save
			flash[:notice] = "La newsletter à bien été créé."
			
			respond_to do |format|
				format.js
				format.html{ redirect_to admin_newsletters_path}
			end
			
		else
			
			respond_to do |format|
				format.js { render :action => :new}
			end
					
		end
	end


	def edit

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

	end

	def update
	
		
		@newsletter = Newsletter.find(params[:id])
		
		if @newsletter.update_attributes(params[:newsletter])
			flash[:notice] = "La newsletter à bien été modifié."
			
			respond_to do |format|
				format.html { redirect_to(admin_newsletters_path()) }
				format.js
			end
			
		else
			respond_to do |format|
				format.html { render :action => :edit}
				format.js { render :action => :edit}
			end		
		end
	end


	def destroy
		@newsletter = Newsletter.find(params[:id])
		@newsletter.destroy
	
	
		flash[:notice] = "La newsletter à bien été supprimé."
	end
  

	def send_test

		@newsletter = Newsletter.find(params[:id])
		@email = params[:email].to_s

		General.send_newsletter(@email,@newsletter.subject, @newsletter.content).deliver

	



		redirect_to(admin_newsletters_path, :notice => "La newsletter a bien été envoyée à l'email de test")
	end
	
	def select_recipients
	    @newsletter = Newsletter.find(params[:id])
		if !params[:search]
			params[:search] = {}
			params[:search][:classe_in] = ['']
			params[:search][:foyer_city_in] = ['']
		end
		params[:search].delete(:foyer_delegue_is_true) if params[:search][:foyer_delegue_is_true] and params[:search][:foyer_delegue_is_true] == 0
		@search = Studient.search(params[:search])
	    @studients = @search.all

	    respond_to do |format|
	      format.html 
	      format.js 
	    end


	  end
	
	def send_newsletter
		@newsletter = Newsletter.find(params[:id])
		@i = 0
		if params[:confirmed_emails]
			
			params[:confirmed_emails].uniq.each do |email|
				puts "mail envoyé à "+email.to_s
				
				General.send_newsletter(email,@newsletter.subject, @newsletter.content).deliver
				@i +=1
			end
		end
		@newsletter.sended = true
		@newsletter.send_at = Time.now
		@newsletter.save
		
		redirect_to(admin_newsletters_path, :notice => "La newsletter a la séléction d'emails ("+@i.to_s+" envois.)")
	end
	

end
