class PPayment < ActiveRecord::Base
  belongs_to :p_payment_type
  belongs_to :p_customer
  validates :p_customer_id, :presence => true
  validates :amount, :presence => true
  validates :paid_at, :presence => true, :if => :paid_date_needed?
  validates :theo_date, :presence => true, :if => :theo_date_needed?
  
  has_many :p_payment_documents
  accepts_nested_attributes_for :p_payment_documents, allow_destroy: true
  
  before_validation do
    
    
    if self.total_affected < self.amount.to_f
      
      self.affected = false
    else
      self.affected = true
    end
    
    if self.total_affected > self.amount.to_f
      errors.add(:amount, "Ne doit pas être inférieur aux affectations (manque #{(self.total_affected - self.amount.to_f)}€)") 
    end
    
    
  
  end
  
  after_save do 
    self.p_payment_documents.each do |p_payment_document|
      p_payment_document.save
    end
    
  end
  
  def total_affected 
    r = 0.0
    self.p_payment_documents.each do |ppd|
      r += ppd.amount.to_f
    end
    return r
  end
  
  def paid_date_needed?
    true if self.paid
  end
  
  def theo_date_needed?
    true if self.p_payment_type and !self.p_payment_type.comptant
  end
  
end
