class TransactionsController < ApplicationController

  respond_to :js, only: [:new, :create]

  before_filter :require_login

  # It render transaction form to pay.
  def new
    @transaction = Transaction.new
    render layout: false
  end

  # To pay the tutor.
  def create
    @transaction = Transaction.new(transaction_params.merge(from_user_id: current_user.id))
    if current_user.has_credit_card?
      respond_to do |format|
        if @transaction.valid?
          if Charge.charge_for(@transaction)
            @transaction.charged = true
            @transaction.save
            if @transaction.pay_tutor
              flash[:notice] = 'Payment is successful.'
              format.js {}
            else
              format.js {render partial: 'form', replace: 'form#new_transaction'}
            end
          else
            format.js {render partial: 'form', replace: 'form#new_transaction'}
          end
        else
          format.js {render partial: 'form', replace: 'form#new_transaction'}
        end
      end
    else
      respond_to do |format|
        format.js {}
      end
    end
  end

  private
  def transaction_params
    params.required(:transaction).permit(:description, :amount, :to_user_id, :from_user_id)
  end
end
