class PCustomer < ActiveRecord::Base
  has_many :particulars, :as => :owner, :dependent => :destroy
  
  has_many :p_contacts, :as => :contactable
  accepts_nested_attributes_for :p_contacts
  
  has_many :p_customer_sheets
  
  accepts_nested_attributes_for :particulars
  
  belongs_to :particular
  accepts_nested_attributes_for :particular
  before_validation do
    generate_mlm_token
  end
  
  def self.for_search(search)
    PCustomer.joins(:particular).where("code LIKE ? or particulars.organisation LIKE ? or particulars.name LIKE ? or particulars.firstname LIKE ?","%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%")
  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

  after_create do
    if !self.particular  and self.particulars.count > 0
      self.particular = self.particulars.first
      self.save
      
    end
      
      
  end

end
