class PComptaExport < ApplicationRecord
  has_many :price_documents, :dependent => :nullify
  has_many :p_fournisseur_orders, :dependent => :nullify
  has_many :p_payments, :dependent => :nullify
  
  validates :start_at, :presence => true
  
  validates :end_at, :presence => true
  
  def add_elements
    if !self.validated
      self.price_documents.update_all(:p_compta_export_id => nil, :compta_locked => false)
      
      p_documents = PriceDocument.where(:price_document_type_id => [4,5], :compta_locked => false, :p_compta_export_id => nil)
      
   
      p_documents = p_documents.where("date >= ?", self.start_at.beginning_of_day) if self.start_at
      p_documents = p_documents.where("date <= ?", self.end_at.end_of_day) if self.end_at
      
      p_documents.update_all(:p_compta_export_id => self.id)
      
      if false
        self.p_payments.update_all(:p_compta_export_id => nil, :compta_locked => false)
      
        p_payments = PPayment.where(:compta_locked => false, :p_compta_export_id => nil)
      
   
        p_payments = p_payments.where("date >= ?", self.start_at.beginning_of_day) if self.start_at
        p_payments = p_payments.where("date <= ?", self.end_at.end_of_day) if self.end_at
      
        p_payments.update_all(:p_compta_export_id => self.id)
      
      end
      
      
      
    end
    
  end
  
  def valid_process
    
    self.price_documents.update_all(:compta_locked => true)
   
    self.validated = true
    self.save
  end
  
end
