class PreSale < ActiveRecord::Base
  belongs_to :customer
  belongs_to :user
  belongs_to :open_cash_register
  belongs_to :product
  belongs_to :special_price

  has_one :cash_register, through: :open_cash_register
  has_one :pointsale, through: :cash_register

  enum sale_type: [:credit, :cash, :reserved]

  validates :customer_id, presence: { message: "Debe seleccionar cliente para la venta." }, on: [:create, :update]
  validates :open_cash_register_id, presence: { message: "Debe seleccionar caja registradora." }, on: [:create, :update]
  validates :sale_type, presence: { message: "Debe seleccionar tipo de venta." }, on: [:create, :update]

  # before_save :get_totals

  def get_totals
    special_price = SpecialPrice.find_by(customer_id: customer_id, product_id: product_id)
    unless special_price.blank?
      self.special_price_id = special_price.id
      discount_per_unit = special_price.get_unit_discount(unit_price)
      self.discount = discount_per_unit * quantity
    end

    self.discount += haggle
    self.amount = quantity * unit_price
    self.tax = 0.0
    if product.include_sale_tax == 1
      self.tax = ((PosConfig.first.tax_percent / 100) * amount).round(2)
    end
    self.total = (amount - discount) + tax
    return true
  end
end
