class PComptaExport < ApplicationRecord
  has_many :p_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
    self.p_documents.update_all(:p_compta_export_id => nil, :compta_locked => false)
    
    p_documents = PDocument.where(:p_document_type_id => [4,7], :compta_locked => false, :p_compta_export_id => nil)
    
    p_documents = p_documents.where("created_at >= ?", Date.parse("2019/01/01")) if self.start_at
    p_documents = p_documents.where("created_at >= ?", self.start_at.beginning_of_day) if self.start_at
    p_documents = p_documents.where("created_at <= ?", self.end_at.end_of_day) if self.end_at
    
    p_documents.update_all(:p_compta_export_id => self.id)
    
    
    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).where("p_bank_account_id is not null")
    
    p_payments = p_payments.where("paid_at >= ?", Date.parse("2019/01/01")) if self.start_at
    p_payments = p_payments.where("paid_at >= ?", self.start_at.beginning_of_day) if self.start_at
    p_payments = p_payments.where("paid_at <= ?", self.end_at.end_of_day) if self.end_at
    
    p_payments.update_all(:p_compta_export_id => self.id)
    
  end
  
  def valid_process
    
    self.p_documents.update_all(:compta_locked => true)
    self.p_payments.update_all(:compta_locked => true)
    self.p_fournisseur_orders.update_all(:compta_locked => true)
    
    self.validated = true
    self.save
  end
  
end
