class CountPartCom < ActiveRecord::Base

  def self.last_paid
    CountPartCom.where(:paid => true).order("last_day DESC").first
  end

  def paid_now
    if !self.paid
      start = CountPartCom.last_paid.last_day.tomorrow.beginning_of_day
      stop = self.last_day.end_of_day
    
      self.amount = Order.com_part_between(start, stop)
      self.nbr_parts = Credit.parts_at(stop)
      self.part_price =  self.amount / self.nbr_parts
    
      control_i = 0.0
    
    
      AnnonceAccount.all.each do |annonce_account|
        if annonce_account.callif(stop)
          puts "NOUVELLE COM"
          puts "Parts"
          puts annonce_account.callif(stop)[3]
          com = annonce_account.callif(stop)[3] * self.part_price
          puts "Com"
          puts com
          control_i = control_i + com
          if com > 0.0
            annonce_account.commissions.create :count_part_com => self, :amount => com, :devise_id => 1, :commission_type_id => 3
            #annonce_account.commissions.create :count_part_com => self, :amount => (annonce_account.callif(stop)[3] * 0.1 ), :devise_id => 2, :commission_type_id => 3
          end
        end
      
      end
      self.paid = true
      self.paid_at = Time.now
      self.control_amount = control_i
      
      self.save
    end
    return self
  end

end
