class PCustomer < ApplicationRecord
  
  has_many :price_documents
  
  has_many :particulars, :as => :owner, :dependent => :destroy
  
  has_many :p_contact_ps, :class_name => "PContact", :through => :particulars, :source => :p_contacts
  
  has_many :p_contacts, :as => :contactable, :dependent => :destroy
  accepts_nested_attributes_for :p_contacts, allow_destroy: true
  
  has_many :p_customer_sheets
  
  has_many :p_sheet_lines, :through => :p_customer_sheets
  
  has_many :p_products, :through => :p_customer_sheets
  
  
  accepts_nested_attributes_for :particulars
  
  belongs_to :particular
  accepts_nested_attributes_for :particular
  
  has_many :p_payments
  
  belongs_to :p_customer_cat
  
  has_many :p_documents
  
  validates :code, :presence => true, :uniqueness => true
  
  has_many :p_compta_elements
  
  belongs_to :accounting_zone
  
  belongs_to :market_discount
  
  
  has_many :open_range_elements, :as => :element
  
  has_many :open_ranges, :through => :open_range_elements
  
  belongs_to :p_commercial
  
  before_destroy do
    if self.p_customer_sheets.count > 0 or self.p_payments.count > 0
      false
    else
      true
    end
      
  end
  
  def can_destroy?
    if self.p_customer_sheets.count > 0 or self.p_payments.count > 0
      return false
    else
      return true
    end
  end
  
  after_initialize do
    self.p_payment_type_id = 41 if !self.p_payment_type_id?

  end
  
  
  def self.valid_sort
    
    ["code", "cache_encours_th", "cache_encours", "cache_payments_th", "cache_payments", "cache_payments_tot", "cache_ca"]
    
  end
  
  
  before_validation do
    
    if !self.code?
      if self.particulars[0]
        cars = self.particulars[0].organisation
        cars += self.particulars[0].name
        cars += self.particulars[0].firstname
        
        cars = cars.to_slug.gsub(/\W/,'').upcase
        cars = cars[0..2]
        cars +=  
        self.code = self.particulars[0].cp+cars
      end
    end
    
    generate_mlm_token
    
    if self.comptant
      
      if self.acompte
        errors.add(:acompte, "N'est pas compatible avec les paiements comptants") 
        
      end
      
      if self.acompte_percent?
        errors.add(:acompte_percent, "N'est pas compatible avec les paiements comptants") 
        
      end
      
      if self.payment_delais?
        errors.add(:payment_delais, "N'est pas compatible avec les paiements comptants") 
        
      end
      
      if self.payment_fin_de_mois
        errors.add(:payment_fin_de_mois, "N'est pas compatible avec les paiements comptants") 
        
      end
      
      
      
      
      
    end
    
    if self.acompte
      if !self.acompte_percent?
        errors.add(:acompte_percent, "Doit être remplis pour demander un acompte") 
      end
    end
    
    
    if !self.comptant
      if !self.payment_delais?
        errors.add(:payment_delais, "Délais de paiement nécessaire si pas de paiement comptant") 
      end
    end
    
  end
  
  
  def update_caches
    
    
    
    
  end
  
  def ca_ht
    0
  end
  
  def ca_ttc
    0
  end
  
  def nbr_orders
    self.p_customer_sheets.where(:state => "facturée")
    
  end
  
  def nbr_orders_refusees
    self.p_customer_sheets.where(:state => "refusée")
    
  end
  
  
  def encours_assure
    r = 0.0
    r = self.p_customer_cat.encourt_max if self.p_customer_cat
    r
  end
 
  def encours_assure_restant
    self.encours_assure.to_f - self.encours_ttc.to_f
  end
  
  def encours_ttc
    self.solde_avoir_and_bills - self.paiements_total
  end
  
  def th_r_encours_ttc
    self.solde_avoir_and_bills - self.th_r_paiements_total
  end
  
  
  def encours_at(date)
    self.solde_avoir_and_bills(date) - self.paiements_total(date)
  end
  
  
  def sheets_total_ht
    self.p_customer_sheets.where(:state => "facturée").sum(:cc_tot_amount_ht)
  end
  
  def solde_avoir_and_bills(date = Date.today)
    self.p_documents.where(:p_document_type_id => [4,7]).where("created_at < ?", date.to_time.end_of_day).sum(:cache_total_ttc)
    
  end
  
  def sheets_total_ttc(date = Date.today)
    self.p_customer_sheets.where(:state => "facturée").where("created_at < ?", date.to_time.end_of_day).sum(:a_ok_total_ttc)
  end
  
  def paiements_total(date = Date.today)
    self.p_payments.where(:paid => true).where("paid_at < ?", date.to_time.end_of_day).sum(:amount)
    
  end
  
  def th_paiements_total
    self.p_payments.where(:paid => false).sum(:amount)
    
  end
  
  def th_r_paiements_total
    self.p_payments.sum(:amount)
    
  end
  
  
  def self.for_search(search)
    PCustomer.joins(:particulars).where("code LIKE ? or particulars.organisation LIKE ? or particulars.name LIKE ? or particulars.firstname LIKE ? or particulars.address_2 LIKE ? or particulars.address_3 LIKE ? or particulars.cp LIKE ? or particulars.city LIKE ?","%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%","%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%").uniq
  end
  
  def generate_mlm_token
    if !self.mlm_token?
      self.mlm_token = loop do
   
      mlm_token = SecureRandom.hex(3).upcase
        break mlm_token unless PCustomer.exists?(mlm_token: mlm_token)
      end
      
    end
  end
  

  def name
    self.show_name
  end

  def show_name
    if self.particular
      n = ""
      n += self.particular.organisation+" " if self.particular.organisation?
      #n += self.particular.name+" " if self.particular.name?
      #n += self.particular.firstname+" " if self.particular.firstname?
      return n
    end
  end
  
  
  def show_name_extend
    if self.particular
      n = ""
      n += self.code.to_s+" "
      n += self.particular.organisation+" " if self.particular.organisation?
      n += self.particular.name+" " if self.particular.name?
      n += self.particular.firstname+" " if self.particular.firstname?
      n += self.particular.cp+" " if self.particular.cp?
      n += self.particular.city+" " if self.particular.city?
      return n
    end
  end
  

  after_save do
    if !self.particular  and self.particulars.count > 0
      self.particular = self.particulars.first
      self.save
      
    end
      
      
  end
  
  def archive_import
    past_fact = self.p_documents.where("d_number regexp '^[0-9]+'").order("created_at DESC")
    if past_fact.first
      date = past_fact.first.created_at + 1.second
      amount = past_fact.sum(:cache_total_ttc)
      if !self.p_payments.where(:p_payment_type_id => 66).first

        p_payment = self.p_payments.new(:p_payment_type_id => 66, :imported => true, :paid => true, :paid_at => date, :amount => amount)
        
        p_payment.save
      end
    end
    
    PPayment.where(:imported => true).update_all(:paid => true)
    date = nil

    self.p_payments.order("paid_at DESC").each do |pp|
      enc = self.encours_at(pp.paid_at)
   
        
      if enc == 0.0
        date = pp.paid_at.end_of_day
        break
      end
    end
    
    
    self.p_customer_sheets.where(:state => "facturée", :imported => true).update_all(:i_archive => false)
    self.p_documents.where(:label => "Facture", :imported => true).update_all(:i_archive => false)
    self.p_payments.where(:imported => true).update_all(:i_archive => false)
    
    self.p_customer_sheets.where(:state => "facturée", :imported => true).where("created_at < ?", date).update_all(:i_archive => true)
    self.p_documents.where(:label => "Facture", :imported => true).where("created_at < ?", date).update_all(:i_archive => true)

    self.p_payments.where(:imported => true).where("paid_at < ?", date).update_all(:i_archive => true) if date
    
    return true
    
  end
  

end
