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
  
  has_secure_password validations: false
  
  
  validates_presence_of :password, :on => :create, :if => :public_validation?
  
  validates :email, :presence => true, :uniqueness => true, :format => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :if => :public_validation?
  
  validates :siren, :presence => true, :if => :valid_siren?
  validates :ape, :presence => true, :if => :valid_siren?
  
  has_many :p_documents
  
  has_many :p_payments
  belongs_to :p_price_cat
  
  has_many :p_compta_elements
  
  has_many :mail_histories
  
  
  attr_accessor :valid_public, :generate_mdp, :valid_siren
  before_validation do
    self.generate_token if !self.token? and self.email?
  end
  
  
  
  def update_caches
    
    self.cache_encours = self.encours_ttc
    #
    self.cache_payments = self.paiements_total
    
    self.cache_ca = self.ca_ht
    
    self.cache_ca_ttc = self.ca_ttc
    
    self.save
    
    
  end
  
  def ca_ht
    0
  end
  
  def ca_ttc
    0
  end
  
  def valid_siren?
    true if self.valid_siren
  end
  def generate_mdp_now
    ps = SecureRandom.hex(4)
    self.password = ps
    self.password_confirmation = ps
    
    if !self.email?
      errors.add(:email, "Doit être présent") 
      
    end
    
    
    if self.save
      
      
      
      mail_history = MailHistory.generateMail("generation_mdp", self.email, {:element => self, :p_customer => self, :mail_options => {:arguments =>  {:mdp => ps}}})
      
      mail_history.deliver_mail
      
      
      
      
    else
    
    end
    
    
  end
  
  
  def public_validation?
    true if self.valid_public
  end
    
  before_create do
    self.generate_token
  end
  
  def generate_token
    begin
      self.token = SecureRandom.urlsafe_base64
    end while PCustomer.exists?(:token => self.token)
  end
  
    
    
  before_validation do
    
    if !self.p_price_cat
      self.p_price_cat = PPriceCat.first
    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 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
      
    self.update_caches
  end
  
  
  def send_password_reset


    begin
      self[:reset_password_token] = SecureRandom.urlsafe_base64
    end while PCustomer.exists?(:reset_password_token => self[:reset_password_token])

    self.reset_password_sent_at = Time.now




    self.save(:validate => false)
    PCustomerMailer.password_reset(self).deliver
  end
  
  
  def encours_ttc
    self.solde_avoir_and_bills - self.paiements_total
  end

  def encours_at(date)
    self.solde_avoir_and_bills(date) - self.paiements_total(date)
  end

  def solde_avoir_and_bills(date = Date.today)
    self.p_documents.where(:p_document_type_id => PDocument::COMPTA_DOC_TYPES).where("created_at < ?", date.to_time.end_of_day).sum(:cache_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


  

end
