module JamRuby
  class PaymentHistory < ActiveRecord::Base

    self.table_name = 'payment_histories'

    belongs_to :sale
    belongs_to :recurly_transaction_web_hook
    belongs_to :charge


    def self.index(user, params = {})

      limit = params[:per_page]
      limit ||= 20
      limit = limit.to_i

      query = PaymentHistory.limit(limit)
                  .includes(sale: [:sale_line_items], recurly_transaction_web_hook:[], charge:[])
                  .where(user_id: user.id)
                  .where("transaction_type = 'sale' OR transaction_type = 'refund' OR transaction_type = 'void'")
                  .order('created_at DESC')


      current_page = params[:page].nil? ? 1 : params[:page].to_i
      next_page = current_page + 1

      # will_paginate gem
      query = query.paginate(:page => current_page, :per_page => limit)

      if query.length == 0  # no more results
        { query: query, next_page: nil}
      elsif query.length < limit  # no more results
        { query: query, next_page: nil}
      else
        { query: query, next_page: next_page }
      end

    end
  end
end