class PFournisseur < ApplicationRecord
  
  has_many :p_contacts, :as => :contactable, :dependent => :destroy
  accepts_nested_attributes_for :p_contacts, allow_destroy: true
  
  belongs_to :accounting_zone
  
  has_many :p_fournisseur_docs
  
  validates :code, :presence => true
  
  belongs_to :p_payment_type
  
  has_many :p_fournisseur_orders
  
  
  has_many :particulars, :as => :owner, :dependent => :destroy
    
  accepts_nested_attributes_for :particulars
    
  belongs_to :particular
  accepts_nested_attributes_for :particular
  

  acts_as_sorting :fields => {
    :code => {:name => "Code", :reorder => true},
    :show_name => {:name => "Nom", :reorder => false},
    :enabled => {:name => "Actif ?", :reorder => true, :format => :boolean},
    :particular => {:name => "Adresse", :reorder => false},
 
    :p_payment_type => {:name => "Type de paiement", :reorder => true, :sort_name => "p_payment_type_id"},
    :payment_comptant => {:name => "Paiement comptant ?", :reorder => true, :format => :boolean},
    :payment_delais => {:name => "Délais paiement", :reorder => true},
    :payment_month_end => {:name => "Fin de mois ?", :reorder => true, :format => :boolean},
    
    
    
    :actions => {:name => "Actions", :reorder => false}
  }


  
  after_save do
    if !self.particular  and self.particulars.count > 0
      self.particular = self.particulars.first
      self.save
      
    end
      
      
  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 member_label
    "#{self.code} #{self.show_name}"
  end
  
  before_validation do
    
    if self.payment_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_month_end
        errors.add(:payment_month_end, "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.payment_comptant
      if !self.payment_delais?
        errors.add(:payment_delais, "Délais de paiement nécessaire si pas de paiement comptant") 
      end
    end
    
  end
  
  
end
