class Transactions::CreditNotesController < ApplicationController

  before_action :set_transactions_sale, only: [:show, :edit, :update, :destroy]
  before_action :check_user

  # GET /transactions/sales
  # GET /transactions/sales.json
  def index

    @sources = [["All",''], ["Cashier","cashier"],["Quick Service","quick_service"],["Online Order","doemal_order"]]
    @customers = Customer.all

    filter        = params[:filter]
    customer      = params[:customer]
    order_source  = params[:order_source]

    if params[:from].present? && params[:to].present?
      from        = Time.zone.parse(params[:from]).beginning_of_day
      to          = Time.zone.parse(params[:to]).end_of_day
    end

    if filter.nil? && from.nil? && to.nil? && customer.nil? && order_source.nil?
      order_source_query = "(select orders.source FROM orders JOIN sale_orders so ON so.order_id=orders.order_id WHERE so.sale_id=sales.sale_id GROUP BY so.sale_id)"

      @credit_notes = Sale.select("sales.*, #{order_source_query} as source")
                      .joins("JOIN sale_payments sp on sp.sale_id = sales.sale_id")
                      .where("(CASE WHEN (sales.grand_total + sales.amount_changed)=(select SUM(sale_payments.payment_amount)
                                        FROM sale_payments WHERE sale_payments.sale_id=sales.sale_id AND sale_payments.payment_method!='creditnote')
                                THEN NULL ELSE payment_method='creditnote' END)")
      @credit_notes = Kaminari.paginate_array(@credit_notes).page(params[:page]).per(20)
    else
        sale = Sale.search_credit_sales(customer,filter,from,to,order_source)
        if !sale.nil?
           @credit_notes = sale
           @credit_notes = Kaminari.paginate_array(@credit_notes).page(params[:page]).per(20)
         else
           @credit_notes = 0
         end
    end
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @credit_notes }
    end

  end

  def check_user
    if current_user.nil?
      redirect_to root_path
    end
  end

end
