class Origami::CreditPaymentsController < BaseOrigamiController
  def index
    @sale_id = params[:sale_id]
    @cashier_type   = params[:type]

    # limit visa_amount
    sale_data = Sale.find_by_sale_id(@sale_id)
    total     = sale_data.grand_total
    @creditcount = 0
    others = 0
    if current_shop.is_rounding_adj
         new_total    = Sale.get_rounding_adjustment(sale_data.grand_total)
    else
        new_total    = sale_data.grand_total
    end
    @rounding_adj = new_total-sale_data.grand_total

    sale_data.sale_payments.each do |sale_payment|
        if sale_payment.payment_method == "creditnote"
          @creditcount = @creditcount + sale_payment.payment_amount
        else
          others = others + sale_payment.payment_amount
        end
    end
    @can_credit = total - @creditcount - others
  end

  def create
    cash = params[:amount]
    sale_id = params[:sale_id]
    if(Sale.exists?(sale_id))
      saleObj = Sale.find(sale_id)

      # rounding adjustment
      # if shop_details.is_rounding_adj
      #   new_total    = Sale.get_rounding_adjustment(saleObj.grand_total)
      #   rounding_adj = new_total-saleObj.grand_total
      #   saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj)
      # end

      saleObj = Sale.find(sale_id)
      remark = "credit payment for Receipt No #{saleObj.receipt_no}"
      sale_payment = SalePayment.new
      @status, @sale = sale_payment.process_payment(saleObj, current_user, cash, "creditnote",remark)
    end
  end

  def create_credit_payment
    arr_sale = JSON.parse(params[:data])
    if !ShiftSale.current_shift.nil?
      if !arr_sale.nil?
        arr_sale.each do |arr_sale|
          arr_sale.each do |sale|
            if(Sale.exists?(sale[0]))
              saleObj = Sale.find(sale[0])
              remark = "credit note payment for Receipt No #{saleObj.receipt_no}"
              sale_payment = SalePayment.new
              @status, @sale = sale_payment.process_payment(saleObj, current_user, sale[1], "cash", remark, true)
            end
          end
        end
      end
      if @status
        render :json => {status: true}
      else
        render :json => {status: false, message: 'Some error occurred!'}
      end
    else
      render :json => {status: false, message: 'No current shift open for this employee!'}
    end

  end

end
