class WithdrawablesController < ApplicationController

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

  before_filter :require_login

  # It will show the total amount and withdrawable amount to user and also has withdraw option so that user can withdraw amount.
  def new
    if current_user.has_bank_account?
      @withdrawable = Withdrawable.new
      @withdrawable_amount = current_user.withdrawable_amount
      @total_amount = current_user.total_balance
      render layout: false
    else
      @user = current_user
      @user.build_bank_account unless @user.bank_account
      @redirect_url = new_withdrawable_path
      render template: 'settings/bank_accounts', layout: false
    end
  end

  # To withdraw money from user account.
  def create
    @withdrawable = Withdrawable.new(withdrawable_params.merge(user_id: current_user.id))
    respond_to do |format|
      if @withdrawable.withdraw
        format.js
      else
        format.js {render partial: 'form', replace: 'form#new_withdrawable'}
      end
    end
  end

  private
  def withdrawable_params
    params.required(:withdrawable).permit(:amount, :description)
  end

end
