class MOdrPrime < ApplicationRecord
  belongs_to :p_customer
  belongs_to :m_odr_file_roulage


  include ActionView::Helpers::NumberHelper
  include ActionView::Helpers::TranslationHelper
  include ActionView::Helpers::UrlHelper

  has_many :m_odr_prime_files #, :dependent => :destroy

  has_many :mail_hists
  has_many :m_odr_virements

  acts_as_sorting :fields => {
    :id => {:name => "Id", :reorder => true},
    :p_customer => {:name => "Client"},
    :state => {:name => "Statut", :reorder => true},
    :amount => {:name => "Montant"},
    :actions => {:name => "Actions", :reorder => true},

  }

  before_validation do

    self.nbr_pneus = 0

    self.amount = 0 

    self.m_odr_prime_files.each do |m|
      self.nbr_pneus = self.nbr_pneus.to_i + m.nbr_pneus
      self.amount = self.amount.to_f + m.amount
    end
  
  end

  before_destroy do
    self.m_odr_file_roulage.nbr_primes_useds = self.m_odr_file_roulage.nbr_primes_useds - self.nbr_pneus
    self.m_odr_file_roulage.save
    self.m_odr_file_roulage.m_odr_file.save


    puts self.m_odr_prime_files.count

    self.m_odr_prime_files.each do |m|
      
      m.m_odr_file.nbr_pneus_useds = m.m_odr_file.nbr_pneus_useds - m.nbr_pneus
      m.m_odr_file.save

      m.destroy
      
    end

   

  end

  def change_state(state)
    self.state = state
    self.save
  end

  def cancel

  end

  def self.reset_primes
    MOdrFile.order("buy_at DESC").where(:m_odr_file_type_id => 2).update_all(:nbr_pneus_useds => 0)

    MOdrFileRoulage.update_all(:nbr_primes_useds => 0)

    MOdrFile.all.each do |m|
      m.save
    end

    MOdrPrime.destroy_all

  end

  def send_init_mail
    if self.state == "A traiter"
      slug = "primes-traitement-en-cours"
    else
      slug = "primes-manque-rib"
    end

    #MailHist.auto_generate_mail(:fr, slug, self.p_customer.email, options = {:arguments => {:remise => number_to_currency(self.amount.to_f)}, :p_customer => self.p_customer, :element => self})
    
  end


  def send_mail_type(slug, element = nil)

    mail_hist = MailHist.auto_generate_mail(:fr, slug, self.p_customer.email, {:arguments => {:remise => number_to_currency(self.amount.to_f), :nbr => self.nbr_pneus }, :m_odr_prime => self, :p_customer => self.p_customer, :element => self})
    
  end

end
