class SubProduct < ActiveRecord::Base
  belongs_to :fournisseur
  belongs_to :product
  belongs_to :product_order_product
  
  def price_ht_with_qte
    self.calculated_price.to_f * self.qte
  end
  
  def qte_tot
    if self.product_order_product
      self.qte * self.product_order_product.qty
    else
      0.0
    end
  end
  
  def price_tot_with_qte
    self.qte_tot * self.calculated_price.to_f
  end
  
  def calculated_price
    
    if self.product_order_product.price_ht
      price_order_product = self.product_order_product.price_ht
    end
    
    if self.price_type == "reste"
      if price_order_product
        somme = 0.0
        self.product_order_product.sub_products.where("price_type != ?", "reste" ).each do |sp|
          somme += sp.calculated_price
        end
        
        
        (price_order_product - somme).round(2)
      else
        0.0
      end
    elsif self.price_type == "percent"
      if price_order_product
        
        
        (price_order_product * (self.price_ht/100)).round(2)
      else
        0.0
      end
    else
      self.price_ht.round(2)
    end
  end
  
end
