class Transactions::CardSettleTransController < ApplicationController
  authorize_resource :class => false

  # GET /transactions/sales
  # GET /transactions/sales.json
  def index
    @status = [["All Status",''], ["Approved","Approved"], ["Declined","Declined"]]
    @payment_method = [["All Payments",''],["MPU Payment","mpu"], ["Visa & Master Payment","vmj"],
                ["JCB Payment","jcb"],["UnionPay Payment","cup"],
                ["Alipay Payment","alipay"]]
    @sales = Sale.all

    payment_type = params[:payment_type]
    cashier_name = params[:cashier_name]
    status_type = params[:status_type]


    from, to  = get_date_range_from_params

    if cashier_name.nil? && from.nil? && to.nil? && payment_method.nil? && status_type.nil?

        @cardSettles = CardSettleTran.order("sale_id desc")

        @cardSettles = Kaminari.paginate_array(@cardSettles).page(params[:page]).per(20)
    else
        cardSettle = CardSettleTran.search(cashier_name,from,to,payment_type,status_type)
        if cardSettle.count > 0
           @cardSettles = cardSettle
           @cardSettles = Kaminari.paginate_array(@cardSettles).page(params[:page]).per(20)
         else
           @cardSettles = 0
         end
    end

  end

  # date range
  PERIOD = {
    "today" => 0,
    "yesterday" => 1,
    "this_week" => 2,
    "last_week" => 3,
    "last_7" => 4,
    "this_month" => 5,
    "last_month" => 6,
    "last_30" => 7,
    "this_year" => 8,
    "last_year" => 9
  }

  def get_date_range_from_params
    period_type = params[:period_type]
    period = params[:period]

    if params[:from].present? && params[:to].present?
      from = Time.zone.parse(params[:from])
      to = Time.zone.parse(params[:to])
    else
        case period.to_i
          when PERIOD["today"]
            from = Time.current
            to = Time.current
          when PERIOD["yesterday"]
            from = 1.day.ago
            to = 1.day.ago
          when PERIOD["this_week"]
            from = Time.current.beginning_of_week
            to = Time.current
          when PERIOD["last_week"]
            from = 1.week.ago.beginning_of_week
            to = 1.week.ago.end_of_week
          when PERIOD["last_7"]
            from = 7.day.ago
            to = Time.current
          when PERIOD["this_month"]
            from = Time.current.beginning_of_month
            to = Time.current
          when PERIOD["last_month"]
            from = 1.month.ago.beginning_of_month
            to = 1.month.ago.end_of_month
          when PERIOD["last_30"]
            from = 30.day.ago
            to = Time.current
          when PERIOD["this_year"]
            from = Time.current.beginning_of_year
            to = Time.current
          when PERIOD["last_year"]
            from = 1.year.ago.beginning_of_year
            to = 1.year.ago.end_of_year
        end
    end

    from = from.beginning_of_day
    to = to.end_of_day

    return from, to
  end

end
