class PPayment < ApplicationRecord
  
  belongs_to :p_bank_account
  
  belongs_to :p_payment_type
  belongs_to :p_customer
  validates :p_customer_id, :presence => true
  validates :amount, :presence => true
  validates :paid_at, :presence => true
  
  
  belongs_to :p_remise
  
  belongs_to :p_sheet_line
  belongs_to :p_ship_tour_truck_sheet_line
  
  
  has_many :p_payment_documents, :dependent => :destroy
  accepts_nested_attributes_for :p_payment_documents, allow_destroy: true
  
  has_one :p_compta_element, :as => :element, :dependent => :destroy
  
  
  QI_DYNAMICS = %w(total_affected reste_to_affect affected)

  eval(QI_DYNAMICS_CORE)
  
  def compta_date
    self.paid_at
  end
  
  def compta_amount
    self.amount
  end
  
  
  after_save do
    self.generate_p_compta_element
  end
  
  def generate_p_compta_element
    if self.id 
      if p_compta_element = PComptaElement.where(:element_type => "PPayment", :element_id => self.id).first
        
      else
        p_compta_element = PComptaElement.new(:p_customer => self.p_customer, :element => self)
      end
    
      
    
      p_compta_element.save
    end
  end
  
  
  
  after_initialize do
    self.p_payment_type_id = 1 if !self.p_payment_type_id?
    self.paid = true
  end
  
  
  before_validation do
    if self.p_payment_type and self.amount
     
      
      if self.p_payment_type.signe == 1
        if self.amount < 0
          self.amount = self.amount * -1
          
        end
        
      elsif self.p_payment_type.signe == 2
        if self.amount > 0
          self.amount = self.amount * -1
          
        end
        
      end
      
    end
    
    
    
    if self.amount and (((self.amount < 0 and self.total_affected < self.amount.to_f) or (self.amount > 0 and 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).round(2)}€)") 
    end
    true
    
  
  end
  
  after_save do 
    
    
    self.p_payment_documents.each do |p_payment_document|
      p_payment_document.save
    end
    
    #self.p_customer.update_caches if self.p_customer
    true
  end
  
  def ca_total_affected
    r = 0.0
    self.p_payment_documents.each do |ppd|
      r += ppd.amount.to_f if !ppd.marked_for_destruction?
    end
    return r.round(2)
    
  end
  
  def ca_reste_to_affect
    (self.amount.to_f - self.total_affected.to_f).round(2)
  end
  
  def ca_affected
    if self.reste_to_affect == 0.0
      true
    else
      false
      
    end
  end
  
  
  
  
end
