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

class SheetsController < ApplicationController
  
  before_filter :authenticate_admin!, except: [:show]
 
  layout "admin"

  require 'csv'
require 'iconv'

#  require_permission 'adherent.show'
#  require_permission 'adherent.add', :only => [:new, :create]
#  require_permission 'adherent.edit', :only => [:edit, :update]
#  require_permission 'adherent.delete', :only => [:destroy]
    



	def recus
		date = Date.today
		date = DateTime.new(2010, 1, 1).beginning_of_year
		
		@sheet_years = SheetYear.find(:all, :conditions => ["paid_at >= ? and paid_at <= ?",date ,date.end_of_year])
		@donates = Donate.find(:all, :conditions => ["paid_at >= ? and paid_at <= ?",date ,date.end_of_year])
		render :layout => false
	end
	


  def index


    if !params[:sheet_filter] and session[:sheet_filter_index] 
      params[:sheet_filter] =  session[:sheet_filter_index] 
    end

    if params[:sheet_filter]
      session[:sheet_filter_index] = params[:sheet_filter]



      
      
    end

    if params[:sheet_filter]
      @sheets =  Sheet.search_by_params(params[:sheet_filter])
    else
      @sheets = Sheet.all(:limit => 100)
    end

    

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @sheets }
      format.js {}
	  	format.csv { 


			report = StringIO.new
			CSV::Writer.generate(report, ';') do |csv|
				csv << ["Organisation", "Nom","Prénom", "Mail", "Téléphone", "Autre téléphone","Autre mail" ,"Adresse 1", "Adresse 2", "Adresse 3", "Code postal", "Ville", "Pays", "Compétences","notes", "Type de fiche", "2010 - Type d'adhésion", "2010 - montant cotisation", "2010 - nature réglement", "2010 - date de réglement", "2011 - Type d'adhésion", "2011 - montant cotisation", "2011 - nature réglement", "2011 - date de réglement" ]
				
				@sheets.sort{|u,v| ((u.person.surname if u.person) || u.corporate).to_s <=>(( v.person.surname if v.person )|| v.corporate).to_s}.each do |sheet|
					r = []
					
					r << sheet.corporate
		
					if sheet.person
						r << sheet.person.surname 
						r << sheet.person.firstname
						r << sheet.person.email
						r << sheet.person.phone
						
					else
						r << nil
						r << nil
						r << nil
						r << nil
					end
					
					r << sheet.other_phone
					r << sheet.other_mail
					r << sheet.address
					r << sheet.address2
					r << sheet.address3
					r << sheet.address3
					r << sheet.pc
					r << sheet.city
					r << sheet.country
					r << sheet.skills
					r << Sheet::SHEET_TYPE[sheet.sheet_type]
					
					if sheet_year = sheet.sheet_years.find(:first, :conditions => {:year => 2010})
						r << SheetYear::JOIN_TYPE[sheet_year.join_type]
						if !sheet_year.gift_year
							r << sheet_year.amount
						else
							r << "A adhérer en fin d'année précédente - adhésion offerte"
						end
						r << SheetYear::PAYMENT_TYPE[sheet_year.payment_type]
						r << sheet_year.paid_at
					else
					 	r << nil
						r << nil
						r << nil
						r << nil
					end
					
					if sheet_year = sheet.sheet_years.find(:first, :conditions => {:year => 2011})
						r << SheetYear::JOIN_TYPE[sheet_year.join_type]
						if !sheet_year.gift_year
							r << sheet_year.amount
						else
							r << "A adhérer en fin d'année précédente - adhésion offerte"
						end
						r << SheetYear::PAYMENT_TYPE[sheet_year.payment_type]
						r << sheet_year.paid_at
					else
					 	r << nil
						r << nil
						r << nil
						r << nil
					end
					
						
					csv << r
				end
			end
			report.rewind
			
			converter = Iconv.new('ISO-8859-15//IGNORE//TRANSLIT','UTF-8')
			send_data(	converter.iconv(report.read),:type => 'text/csv;',:filename => 'exporation-adherents.csv',:encoding => 'UTF-16')   
			
			
		}
    end
  end


  def show
    @sheet = Sheet.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.js
      format.xml  { render :xml => @sheet }
    end
  end


  def new
    @sheet = Sheet.new
    @sheet.people.build
  
  end

  def edit
    @sheet = Sheet.find(params[:id])
    respond_to do |format|
      format.html # new.html.erb
      format.js { render :layout => false }
    end
  end


  def create
    @sheet = Sheet.new(params[:sheet])

    respond_to do |format|
      if @sheet.save
        flash[:notice] = 'Sheet was successfully created.'
        format.html { redirect_to(@sheet) }
        format.js { render :action => "show" }
      else
        format.html { render :action => "new" }
        format.js { render :action => "new" }
        format.xml  { render :xml => @sheet.errors, :status => :unprocessable_entity }
      end
    end
  end


  def update
    @sheet = Sheet.find(params[:id])

    respond_to do |format|
      if @sheet.update_attributes(params[:sheet])
        flash[:notice] = 'Sheet was successfully updated.'
        format.html { redirect_to(@sheet) }
        format.js { render :action => "update", :layout => false }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.js { render :action => "edit", :layout => false }
        format.xml  { render :xml => @sheet.errors, :status => :unprocessable_entity }
      end
    end
  end


  def destroy
    @sheet = Sheet.find(params[:id])
    @sheet.destroy

    respond_to do |format|
      format.html { redirect_to(sheets_url) }
      format.xml  { head :ok }
    end
  end
  
  
  def stats

   
    
    @year = params[:year].to_i || Date.today.year
    
    @start_date = Date.new(@year, 1, 1 )
    @end_date = Date.new(@year, 12, 31 )


    @gift_years = {
      :nbr_foyers => SheetYear.count(:conditions => ['year = ? AND gift_year = ? ',@year, true]), 
      :nbr_familles => SheetYear.count(:conditions => ['year = ? AND gift_year = ? AND join_type = ?',@year, true,2]), 
      :nbr_associations =>  SheetYear.count(:conditions => ['year = ? AND gift_year = ? AND join_type = ?',@year, true,3]), 
      :nbr_individuel => SheetYear.count(:conditions => ['year = ? AND gift_year = ? AND join_type = ?',@year, true,1]), 
      :nbr_benefactors =>  SheetYear.count(:conditions => ['year = ? AND gift_year = ? AND benefactor = ?',@year, true,true])
  
      }
    @gift_years[:pouvoirs] = (@gift_years[:nbr_familles] + @gift_years[:nbr_associations])*2 + @gift_years[:nbr_individuel]
      
      
      @renewed_prev_year = {
        :nbr_foyers => SheetYear.count(:conditions => ['year = ? AND paid_at < ? ',@year, @start_date]), 
        :nbr_familles => SheetYear.count(:conditions => ['year = ? AND  paid_at < ?  AND join_type = ?',@year, @start_date,2]), 
        :nbr_associations =>  SheetYear.count(:conditions => ['year = ? AND  paid_at < ? AND join_type = ?',@year, @start_date,3]), 
        :nbr_individuel => SheetYear.count(:conditions => ['year = ? AND  paid_at < ?  AND join_type = ?',@year, @start_date,1]), 
        :nbr_benefactors =>  SheetYear.count(:conditions => ['year = ? AND  paid_at < ?  AND benefactor = ?',@year, @start_date,true])

        }
     @renewed_prev_year[:pouvoirs] = (@renewed_prev_year[:nbr_familles] + @renewed_prev_year[:nbr_associations])*2 + @renewed_prev_year[:nbr_individuel]
    @months= {}
    @months["0"] = {
      :cumul_foyers => @gift_years[:nbr_foyers].to_i + @renewed_prev_year[:nbr_foyers].to_i,
      :cumul_familles => @gift_years[:nbr_familles].to_i + @renewed_prev_year[:nbr_familles].to_i,
      :cumul_associations => @gift_years[:nbr_associations].to_i + @renewed_prev_year[:nbr_associations].to_i,
      :cumul_individuel => @gift_years[:nbr_individuel].to_i + @renewed_prev_year[:nbr_individuel].to_i,
      :cumul_benefactors => @gift_years[:nbr_benefactors].to_i + @renewed_prev_year[:nbr_benefactors].to_i,
      :cumul_pouvoirs => @gift_years[:pouvoirs].to_i + @renewed_prev_year[:pouvoirs].to_i
    }
    
    @foyers_to_stats = []
    @familles_to_stats  = []
    @associations_to_stats  = []
    @individuel_to_stats  = []
    @benefactors_to_stats  = []
    @pouvoirs_to_stats  = []

    month = @start_date
    while month <= @end_date
      @months[month.month.to_s] = {
        :month => month.month,
        :nbr_foyers => SheetYear.count(:conditions => ['year = ? AND paid_at >= ? and paid_at <= ? ',@year, month, month.end_of_month]), 
        :nbr_familles => SheetYear.count(:conditions => ['year = ? AND  paid_at >= ? and paid_at <= ?  AND join_type = ?',@year, month, month.end_of_month,2]), 
        :nbr_associations =>  SheetYear.count(:conditions => ['year = ? AND paid_at >= ? and paid_at <= ? AND join_type = ?',@year, month, month.end_of_month,3]), 
        :nbr_individuel => SheetYear.count(:conditions => ['year = ? AND  paid_at >= ? and paid_at <= ? AND join_type = ?',@year, month, month.end_of_month,1]), 
        :nbr_benefactors =>  SheetYear.count(:conditions => ['year = ? AND  paid_at >= ? and paid_at <= ? AND benefactor = ?',@year, month, month.end_of_month,true])

        }
        
      @months[month.month.to_s][:pouvoirs] = (@months[month.month.to_s][:nbr_familles] + @months[month.month.to_s][:nbr_associations])*2 + @months[month.month.to_s][:nbr_individuel]
      
      @months[month.month.to_s][:cumul_foyers] = @months[(month.month-1).to_s][:cumul_foyers].to_i + @months[month.month.to_s][:nbr_foyers].to_i
      @months[month.month.to_s][:cumul_familles] = @months[(month.month-1).to_s][:cumul_familles].to_i + @months[month.month.to_s][:nbr_familles].to_i
      @months[month.month.to_s][:cumul_associations] = @months[(month.month-1).to_s][:cumul_associations].to_i + @months[month.month.to_s][:nbr_associations].to_i
      @months[month.month.to_s][:cumul_individuel] = @months[(month.month-1).to_s][:cumul_individuel].to_i + @months[month.month.to_s][:nbr_individuel].to_i
      @months[month.month.to_s][:cumul_benefactors] = @months[(month.month-1).to_s][:cumul_benefactors].to_i + @months[month.month.to_s][:nbr_benefactors].to_i
      @months[month.month.to_s][:cumul_pouvoirs] = @months[(month.month-1).to_s][:cumul_pouvoirs].to_i + @months[month.month.to_s][:pouvoirs].to_i
      
      @foyers_to_stats << @months[month.month.to_s][:cumul_foyers]
      @familles_to_stats  << @months[month.month.to_s][:cumul_familles]
      @associations_to_stats  << @months[month.month.to_s][:cumul_associations]
      @individuel_to_stats << @months[month.month.to_s][:cumul_individuel]
      @benefactors_to_stats << @months[month.month.to_s][:cumul_benefactors]
      @pouvoirs_to_stats  << @months[month.month.to_s][:cumul_pouvoirs]
      
      month = month.next_month
    end


    chart_months = ["Jan.", "Fév.", "Mar.", "Avr.", "Mai", "Juin", "Juil.", "Août", "Sep.", "Oct.", "Nov.", "Dec."]
    
    #chart_months = ["01", "02", "03","04","05","06","07","08","09","10","11","12"]
    
    
    
    @chart_values = []
    
    i = 0
    chart_months.each do |month|
        
        @chart_values << {
          y: month.to_s,
          foyers: @foyers_to_stats[i],
          familles:@familles_to_stats[i],
          associations:@associations_to_stats[i],
          individuel:@individuel_to_stats[i],
          bienfaiteurs:@benefactors_to_stats[i],
          pouvoirs:@pouvoirs_to_stats[i]
    
	
          
        }
        i = i+1
    end
  
  
  
  
  
  
   end
  
  
end