class DonatorTransactionExport < ActiveRecord::Base
  
  validates :end_at, :presence => true
  
  validates :export_type_id, :presence => true
  
  has_many :donator_transactions
  
  
  #TYPES = ["cb ponctuel", "cb mensuel", "sepa"]
  TYPES = ["cb (toutes)", "archives cb mensuel", "sepa"]
  
  def self.export_today
    
    if !DonatorTransactionExport.where(:export_type_id => 1, :end_at => (Date.today-1.day)).first
      donator_transaction = DonatorTransactionExport.create(:export_type_id => 1, :end_at => (Date.today-1.day))
      donator_transaction.send_mail
    end
    #donator_transaction = DonatorTransactionExport.create(:export_type_id => 3, :end_at => Date.today)
    #donator_transaction.send_mail
    
  end
  
  def short_type
    if self.export_type_id == 1
      "CB"
    elsif self.export_type_id == 2
      "CB archive"
    elsif self.export_type_id == 3
      "SEPA"
    end
  end
  
  after_create do
    self.find_donator_transactions.update_all :exported => true, :donator_transaction_export_id => self.id
    self.generate_file
  end
  
  def find_donator_transactions
    donator_transactions_result = DonatorTransaction.joins(:tr_payment_ok).where("donator_transactions.paid_at <= ?", DateTime.parse(self.end_at.to_s).end_of_day)
    
    donator_transactions_result = donator_transactions_result.where("exported = 0 or exported is null")
    
    if self.export_type_id == 1 or self.export_type_id == 2
      
      donator_transactions_result = donator_transactions_result.where(:completed_finish => true).where("tr_payments.tr_payment_type_id = 3").where(:paid => true)
      
      if self.export_type_id == 1
        donator_transactions_result = donator_transactions_result#.where(:recurrent => false)
        
        
      elsif self.export_type_id == 2
        donator_transactions_result = donator_transactions_result.where(:recurrent => true)
        
        
      end
      
    
    elsif self.export_type_id == 3
      
      donator_transactions_result = donator_transactions_result.where(:completed_finish => true).where("tr_payments.tr_payment_type_id = 5").where(:paid => true)
      
      
    end
    
    
    donator_transactions_result #.where(:recurrent => false)
    
  end
  
  
  def generate_file
    if self.export_type_id == 1
      elements = {
    
 
        #"CliCompagnie" => "particular_bill.organisation",
        "CliCivilité" => "particular_bill.civilite_prodons",
        "CliPrenom" => "particular_bill.firstname",
        "CliNom" => "particular_bill.name",
        "CliAdresse" => "particular_bill.address_longue",

        "CliCodePosta" => "particular_bill.cp",
        "CliVille" => "particular_bill.city",
        "CliPays" => "prodons_country",
        "CliCourriel_Personnel" => "particular_bill.email",
        "CliTel_Domicile" => "particular_bill.tel",
        "TrxMontantDon" => "total",
        "TrxCodeOccasion" => "occasion",
        "TrxCodeActivité" => "activite",
        "TrxModePaiement" => "prodons_payment_mode",
        "TrxDateDon" => "prodons_date",
        "Recu_RecuNo" => "prodons_recu_number",
        "TrxReçuStatut" => "prodons_recu_statut",
        "TrxReçuAnnuel" => "prodons_recu_annuel",
        "TrxRéférencePaiement" => "nil"
        
        
      
      }
      
    elsif self.export_type_id == 2

  
      elements = {
    
       
        #"CliCompagnie" => "particular_bill.organisation",
        "CliCivilité" => "particular_bill.civilite_prodons",
        "CliPrenom" => "particular_bill.firstname",
        "CliNom" => "particular_bill.name",
        "CliAdresse" => "particular_bill.address_longue",

        "CliCodePosta" => "particular_bill.cp",
        "CliVille" => "particular_bill.city",
        "CliPays" => "prodons_country",
        "CliCourriel_Personnel" => "particular_bill.email",
        "CliTel_Domicile" => "particular_bill.tel",
        "TrxMontantDon" => "total",
        "TrxCodeOccasion" => "occasion",
        "TrxCodeActivité" => "activite",
        "TrxModePaiement" => "prodons_payment_mode",
        "TrxDateDon" => "prodons_date",
        #"Recu_RecuNo" => "prodons_recu_number"
        "TrxReçuStatut" => "prodons_recu_statut",
        "TrxReçuAnnuel" => "prodons_recu_annuel"
        
      
      }

  
    elsif self.export_type_id == 3
      
      elements = {
        
       
        #"CliCompagnie" => "particular_bill.organisation",
        "CliCivilité" => "particular_bill.civilite_prodons",
        "CliPrenom" => "particular_bill.firstname",
        "CliNom" => "particular_bill.name",
        "CliAdresse" => "particular_bill.address_longue",

        "CliCodePosta" => "particular_bill.cp",
        "CliVille" => "particular_bill.city",
        "CliPays" => "prodons_country",
        "CliCourriel_Personnel" => "particular_bill.email",
        "CliTel_Domicile" => "particular_bill.tel",
        
        "EngOccasion" => "occasion",
        "EngActivité" => "activite",
        "EngModePaiement" => "prodons_payment_mode",
        
        "EngVersement" => "total",
        "EngDateInscription" => "prodons_date",
        
        "Iban" => "prodons_iban",
        "Bic" => "prodons_bic",
        "PERIODICITE" => "prodons_periodicite",
        "Prochain(date)" => "prodons_prochain_date"
        
        
        
        

        
      }
      
    end
    
    
    
    
    
    
    headers = []
    attributes = []

    elements.each do |key, value|
      headers << key
      attributes << value
    end
    
    attributes = attributes[0...-1] if self.export_type_id == 1

    @csv = CSV.generate(:headers => true, :col_sep => ";") do |csv|
      csv << headers
  
      self.donator_transactions.all.each do |donator_transaction|

        csv << attributes.map{ |attr| eval("donator_transaction."+attr.to_s) }
  
      end
  
  
      #boutique
  
      if self.export_type_id == 1
        elements = {
    
 
          #"CliCompagnie" => "particular_bill.organisation",
          "CliCivilité" => "particular_bill.civilite_prodons",
          "CliPrenom" => "particular_bill.firstname",
          "CliNom" => "particular_bill.name",
          "CliAdresse" => "particular_bill.address_longue",

          "CliCodePosta" => "particular_bill.cp",
          "CliVille" => "particular_bill.city",
          "CliPays" => "prodons_country",
          "CliCourriel_Personnel" => "particular_bill.email",
          "CliTel_Domicile" => "particular_bill.tel",
          "TrxMontantDon" => "total",
          "TrxCodeOccasion" => "occasion",
          "TrxCodeActivité" => "activite",
          "TrxModePaiement" => "prodons_payment_mode",
          "TrxDateDon" => "prodons_date",
          "Recu_RecuNo" => "prodons_recu_number",
          "TrxReçuStatut" => "prodons_recu_statut",
          "TrxReçuAnnuel" => "prodons_recu_annuel"
        
        
      
        }
      
        @product_orders = ProductOrder.where(:paid => true, :product_order_payment_type_ok_id => 3).where("paid_at <= ? and paid_at >= ?", DateTime.parse(self.end_at.to_s).end_of_day, DateTime.parse(self.end_at.to_s).beginning_of_day)
  
        @product_orders.each do |product_order|
          
          product_order.product_order_products.each do |product_order_product|

          
            product_stock = product_order_product.product.product_stocks.where(:product_option_id => product_order_product.product_option_id,:product_size_id => product_order_product.product_size_id).first
            pays = product_order.prodons_country
            tel = ""
            occasion = "catalogue"
            product_stock ? activite = product_stock.prodon : activite = ""
            date = product_order.prodons_date
            

            
            
            csv << [product_order.particular_bill.civilite_prodons,product_order.particular_bill.firstname, product_order.particular_bill.name,"#{product_order.particular_bill.address_2} #{product_order.particular_bill.address_3}", product_order.particular_bill.cp,product_order.particular_bill.city,pays,product_order.product_customer.email,tel,product_order_product.archived_price_ttc_with_qty, occasion,activite,"CB", date,"","N","", product_order.bill_number ]
          end
          
        end
        
      end
  
  
  
    end
    
    
    
    
    
    
    
    
    
    
    
    
    @final_file = "#{Rails.root}/csv/donator_transaction_exports/#{self.id}.csv"
        
    
    
          
      
          
          
    File.open(@final_file, 'wb') do |file|
      file << @csv.encode('iso-8859-1', :undef => :replace, :replace => '')
    end
    
  end
  
  
  def send_mail
    
    
    ExportsMails.send_export(self).deliver
    
  end
  
  def csv_url
    "#{Rails.root}/csv/donator_transaction_exports/#{self.id}.csv"
  end
  
end
