class PPaymentDocument < ApplicationRecord
  
  belongs_to :price_document
  belongs_to :p_payment
  has_one :p_customer, :through => :p_payment
  
  validates :price_document_id, :presence => true, :if => :price_document_id_needed?
  #validates :p_payment_id, :presence => true
  validates :amount, :presence => true
  attr_accessor :skip_validation
  
  def price_document_id_needed?
    true if !self.avoir_id
  end
  
  after_save do
    
    if !skip_validation
      
      puts "VALIDATION PPAYMENTDOC"
      
      self.price_document.save
      self.price_document.price_line_block.save if self.price_document.price_line_block
      puts "FIN VALIDATION PPAYMENTDOC"
      
    
      #self.p_customer.update_caches if self.p_customer
    end
    
    true
  end
  
  after_destroy do 
    price_document = self.price_document
    
    #self.restore_attributes
    
    #self.save(:validate => false)
    if price_document
      #ddf
      
      price_document.save 
    end
    self.p_payment.save if self.p_payment
    
    self.p_customer.update_caches if self.p_customer
    
    true
  end
  
  def siblings_payments
    siblings_payments = self.price_document.p_payment_documents.joins(:p_payment).where(:p_payments => {:canceled => false})
    siblings_payments = siblings_payments.where("p_payment_documents.id != ?", self.id) if self.id
    return siblings_payments
  end
  
  def siblings_payments_total
    self.siblings_payments.sum(:amount)
  end
  
  before_validation do
    
    if !skip_validation
    
      if self.price_document
      
      
        sum = self.siblings_payments_total + self.amount.to_f 
      
      
        if sum > (self.price_document.tot_amount_ttc) and false #désactivé pour gérer les impayés
      
          errors.add(:amount, "Ne doit pas dépasser le montant de la somme restant dues (#{self.price_document.totals[:ok_total_ttc].to_f - siblings_payments_total})") 
        end
      
      
      end
    end
    

    true
  
  end
  
  
  
  
end
