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

class Admin::NewslettersController < ApplicationController
	before_filter :authenticate_admin!

	
	layout "admin"
	navigation :newsletters


	def index
		@newsletters = Newsletter.order('created_at DESC')
		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éé."
			@newsletters = Newsletter.order('created_at DESC')
			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).deliver

	



		redirect_to(admin_newsletters_path, :notice => "La newsletter a bien été envoyée à l'email de test")
	end
	

	def send_newsletter
		@newsletter = Newsletter.find(params[:id])
		@i = 0
		@inscrits = Inscrit.where(:enabled => true)
		@inscrits.each do |inscrit|
			General.send_newsletter(inscrit.email,@newsletter, inscrit).deliver
		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
