class ProductOrderProduct < ActiveRecord::Base
  belongs_to :order
  belongs_to :product


  belongs_to :product_size
  belongs_to :product_option

  belongs_to :archived_product, class_name: "Product"
  belongs_to :archived_product_size,  class_name: "ProductSize"
  belongs_to :archived_product_option, class_name: "ProductOption"

  def price_ttc_with_qty
    qty.to_f * product.price_ttc.to_f
  end
  
  def final_price_ttc_with_qty
    qty.to_f * product.final_price_ttc.to_f
  end
  
  

  def archived_price_ttc_with_qty
    if archived_product
      qty.to_f * archived_product.price_ttc.to_f 
    else
      0
    end
  end
  
  
  def archived_final_price_ttc_with_qty
    if archived_product
      qty.to_f * archived_product.final_price_ttc.to_f 
    else
      0
    end
  end
  

  def verify_qty

    product_stock_t = self.product.product_stocks.where(:product_option_id => self.product_option_id,:product_size_id => self.product_size_id).first

    if product_stock_t and self.qty > product_stock_t.stock_th
      self.qty = product_stock_t.stock_th
    elsif !product_stock_t

      self.qty = 0
    end
  end
  
  def update_stock_th
    product_stock_t = self.product.product_stocks.where(:product_option_id => self.product_option_id,:product_size_id => self.product_size_id).first

    if product_stock_t
      product_stock_t.stock_th = product_stock_t.stock_th - self.qty
      product_stock_t.save
      
    end
  end
  
  def update_stock
    product_stock = self.product.product_stocks.where(:product_option_id => self.product_option_id,:product_size_id => self.product_size_id).first

    if product_stock
      product_stock.stock = product_stock.stock - self.qty
      product_stock.save
      
    end
  end


end
