class Admin::PaymentsController < Admin::BaseController

  include Admin::InheritedResource

  skip_before_filter :require_login, :verify_admin, :only => [:balanced_payment_event]

  # Retrieves basic information to be displayed on payment page.
  def index
    respond_to do |format|
      format.json { render json: data_table }
      format.html {}
    end
  end

  # Update the payment information.
  def update
    @payment = Payment.find(params[:id])
#    begin
      if @payment.credit?
        transaction = Balanced::Credit.find(@payment.uri)
      else
        transaction = Balanced::Debit.find(@payment.uri)
      end
      @payment.balanced_transaction = transaction
      respond_to do |format|
        if @payment.save!
          @message = "Synchronized payment with BalancedPayments database."
          format.js { render 'referesh_datatable' }
          format.html {}
        else
          @message = "Unable to Synchronized payment with BalancedPayments database."
          format.js { render 'referesh_datatable' }
          format.html {}
        end
      end
  end

  # Method to reprocess the payment.
  def resend
    @payment = Payment.find(params[:id])
    @payment.resend!
    flash[:notice] = "Marked payment for reprocessing. And this payment will be considered by the PaymentEngine in next 10 minutes"
    redirect_to request.referer || admin_payments_path
  end

  # Find and updating the transaction.
  def balanced_payment_event
    event_entity = params['entity']
    event_entity_type = event_entity['_type']
    payment = Payment.find_by(transaction_id: event_entity['id'])
    payment.reload_from_balanced_payments! if payment.present?
    render :nothing => true
  end

  private
  def permitted_params
    params.permit(testimonial: [:amount, :status, :_type, :description, :transaction_id ])
  end

end
