class Sale < ActiveRecord::Base
  belongs_to :customer
  belongs_to :user
  belongs_to :open_cash_register
  belongs_to :seller

  has_many :cash_registers_moves
  has_many :inventories_moves
  has_many :sales_details
  has_many :products, through: :sales_details
  has_one :credit
  has_many :credit_payments, through: :credit
  has_one :sales_sellercommission
  has_many :products_returns
  has_many :pointsales, through: :open_cash_register

    ##--- Llevar registro de Actividad del usuario
  audited

  enum status: [:notpaid, :cancelled, :paid, :parcial, :cancelled_by_expiration]
  enum saletype: [:credit, :cash, :reserved]

  ##--- Validaciones previas de guardar
  validates :open_cash_register_id, presence: { message: "Se debe seleccionar caja registradora." }, on: [:create]
  validates :sale_code, presence: { message: "Se debe seleccionar caja registradora para generar el código de venta." }, on: [:create, :update]
  validates :customer_id, presence: { message: "Debe seleccionar cliente para la venta." }, on: [:create, :update]
  validates :seller_id, presence: { message: "Debe seleccionar vendedor para la venta." }, on: [:create, :update]
  validates :saletype, presence: { message: "Debe seleccionar tipo de venta." }, on: [:create, :update]

  accepts_nested_attributes_for :sales_details

  scope :activas, -> { where.not(sales: { status: 1 }) }

  def get_pointsale
    user.pointsale
  end

  def reserve_is_expired?
    if expiration_date >= Date.today
      false
    else
      true
    end
  end

  def self.sales_chart_by_period_of_time(period)
    all_sales = Array.new
    if period == 'week'
      beg_period = Date.current.beginning_of_week
      end_period = Date.current.end_of_week
    elsif period == 'month'
      beg_period = Date.current.beginning_of_month
      end_period = Date.current.end_of_month
    elsif period == 'day'
      beg_period = Date.current.beginning_of_day
      end_period = Date.current.end_of_day
    end
    Pointsale.activos.each do |pointsale|
      obj = {}
      obj[:pointsale] = pointsale.name.gsub(" ", "\n")
      obj[:total] = pointsale.sales.activas.where(date_sale: beg_period..end_period).where('sales.status > 1').sum(:total)
      all_sales << obj
    end
    all_sales = all_sales.to_json
    return all_sales
  end

  def reserve_debt
    total_in_moves = cash_registers_moves.where(status: 1).sum(:quantity)
    total - total_in_moves
  end

  def can_be_cancelled?(pos_config)
    daysToCancel = pos_config.days_cancel_sale
    if (date_sale + daysToCancel.days) >= Date.today && !cancelled?
      # checar si la venta es de credito y ver si tiene pagos
      if credit?
        has_payments = CreditPayment.where(credit_id: credit.id).any?
        has_payments ? (return false) : (return true)
      else
        return true
      end
    else
      return false
    end
  end
end
