class Order < ActiveRecord::Base
  
  belongs_to :customer
  belongs_to :credit_product
  belongs_to :commission
  
  
  validates :cgv, :presence => true
  validates :retractation, :presence => true
  
  
	scope :between, lambda { |start, stop|
	        after(start).before(stop)
	    }
	
	scope :after, lambda { |date|
	        where("(paid_at >= ?)", date )
	    }
	scope :before, lambda { |date|
	        where("(paid_at <= ?)", date )
	    }
  
  
  
  
  
  
  after_save do
    

    
  end
  
  def generate_bill
    if self.paid  and self.paid_at and self.payment_type_id == 2 and !self.bill_token
      
      self.bill_at = self.paid_at

      
      begin
        self[:bill_token] = SecureRandom.urlsafe_base64
      end while Order.exists?(:bill_token => self[:bill_token])
      
      
      @documents = Order.where("bill_token IS NOT NULL").where("bill_at <= ? and bill_at >= ?",self.bill_at.end_of_month, self.bill_at.beginning_of_month )
      @last = @documents.order("bill_id DESC").first
          if @last and @last.bill_id?
            @number = @last.bill_id.to_i + 1
        else
            @number = 1
          
        end
        
        self.bill_id = @number
      
      
      
      
      self.bill_number = "SP"+self.bill_at.strftime("%Y%m").to_s+('%05d' % self.bill_id)
      self.save
    end
    
    
  end
  
  def billing_address?
    if self.customer.address? and self.customer.cp? and self.customer.city? and self.customer.country?
      true
    else
      false
    end
  end
  
  def after_paid(soft=false)
    #ajout des crédits au compte
    self.customer.credits.create(:cred => true, :value => self.nbr_credits, :expire_after => self.paid_at.to_date+(self.validity.to_i.months), :operation_id => self.id, :operation_type => "Order", :note => "Commande de crédits")
    self.customer.inscription_binaire
    
    if !soft
      #comission directe désactivée, remplacée par le mutliniveau
      if self.customer.parent
      
        #self.customer.parent.commissions.create(:order => self, :commission_type_id => 1, :amount => (self.price_ht.to_f() *0.1))
      
      end
    
      
      # binaire (commissions désactivé dans customer commission_binary_now)
      if self.customer.binary_parent
        self.credit_binary_parent(self.customer.binary_parent, self.customer)
      end
      
      
      # commissions multiniveau
      
      self.commission_mlm_now
      
      self.generate_bill
      self.save
      
    end
    
  end
  
  def commission_mlm_now
    if self.customer.parent
      i = 0
      parent_to_commission = self.customer.parent
      
      while parent_to_commission and i <= 12
        i += 1
        
        if parent_to_commission.mlm_nbr_niveaux >= i
          com_percent = (parent_to_commission.callif_now[4][i].to_f/100)
          com = ((parent_to_commission.callif_now[4][i].to_f/100)*self.price_ht.to_f()).round(2)
          puts "Commission à #{parent_to_commission.pseudo}: génération #{i}, #{com_percent}%, #{com}"
          
          parent_to_commission.commissions.create(:order => self, :commission_type_id => 10, :amount => com, :percent => com_percent, :generation => i)
          
        end
        
        parent_to_commission = parent_to_commission.parent
        
        
      end
      
      
    end
  end
  
  def credit_binary_parent(parent, fileul)

  
    parent.binary_points.create(:value => self.binary_points, :side => fileul.binary_side, :fileul_id => fileul.id, :order => self, :point_type => 1)
    parent.commission_binary_now(self)
    
    
    if parent.binary_parent
      self.credit_binary_parent(parent.binary_parent, parent)
    end
    
    
  end
  
  def self.points_binaires_between(start, stop)
    Order.between(start, stop).where("unpaid is null").where("payment_type_id = 2").where(:paid => true).sum(:binary_points)
  end
  
  
  def self.points_binaires_mlm_between(start, stop)
    Order.between(start, stop).where("unpaid is null").where("payment_type_id = 2").where(:paid => true).includes(:customer).where("customers.parent_id IS NOT NULL").sum(:binary_points)
  end
  
  def self.points_binaires_direct_between(start, stop)
    Order.between(start, stop).where("unpaid is null").where("payment_type_id = 2").where(:paid => true).includes(:customer).where("customers.parent_id IS NULL").sum(:binary_points)
  end
  
  
  def self.com_part_between(start,stop)
    self.points_binaires_mlm_between(start, stop) * 0.20 + self.points_binaires_direct_between(start, stop) * 1.0
    
    
  end
  
  def evaluate_use_coms(force_eval=false)
    ttc = self.credit_product.price_ttc_final(self.customer)
    
    if self.customer.solde_commissions > 0.0 and (self.with_com or force_eval == true)
      if self.customer.solde_commissions >= ttc
        self.credit_product.price_ttc_final(self.customer)
      else
        self.customer.solde_commissions
      end
      
    else
      0.0
    end
    
  end
  
  
  def evaluate_solde_coms(force_eval=false)
    self.customer.solde_commissions - self.evaluate_use_coms(force_eval)
  end
  
  def evaluate_price_with_coms_ht(force_eval=false)
    
        if self.with_com or force_eval == true
          
          (self.evaluate_price_with_coms_ttc(force_eval) / 1.2).round(2)
    
        else
        
          self.credit_product.price_ht_final(self.customer)
        end
    
  end
  
  def evaluate_price_with_coms_ttc(force_eval=false)
    self.credit_product.price_ttc_final(self.customer) - self.evaluate_use_coms(force_eval)

    
  end
  
  
end