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
  
  has_one :p_compta_element, :as => :element, :dependent => :destroy
  
  
  
  before_validation do
    
    
    if self.total_affected < self.amount.to_f
      
      self.affected = false
    else
      self.affected = true
    end
    
    if self.amount and ((self.amount.to_f < 0.0 and self.total_affected.to_f < self.amount.to_f) or (self.amount.to_f > 0 and self.total_affected.to_f > self.amount.to_f))# and !self.imported
      errors.add(:amount, "Ne doit pas être inférieur aux affectations (manque #{(self.total_affected - self.amount.to_f)}€)") 
    end
    
    true
    
  
  end
  
  after_save do 
    self.p_payment_documents.each do |p_payment_document|
      p_payment_document.save
    end
    self.generate_p_compta_element
    self.p_customer.update_caches if self.p_customer
    true
  end
  
  

  
  def generate_p_compta_element
    
    if self.p_compta_element
      p_compta_element = self.p_compta_element
    else
      p_compta_element = PComptaElement.new(:p_customer => self.p_customer, :element => self)
    end
    
    p_compta_element.amount = (self.amount)
    if self.paid_at?
      p_compta_element.date = self.paid_at
    elsif self.theo_paid_at?
      p_compta_element.date = self.theo_paid_at
    else
      p_compta_element.date = self.created_at
    end
    puts p_compta_element.save

  end
  
  def total_affected 
    r = 0.0
    self.p_payment_documents.each do |ppd|
      r += ppd.amount.to_f
    end
    return r.round(2)
  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
  
  def reste_to_affect
    (self.amount.to_f - self.total_affected.to_f).round(2)
  end
  
end
