class Provider::Admin::AccountsController < Provider::Admin::Account::BaseController

  activate_menu :account, :overview

  before_action :find_countries, :only => [:edit, :update]
  before_action :find_account
  before_action :deny_unless_can_update, :only => [:update, :edit]

  def show; end

  def edit
    check_require_billing_information
  end

  def update
    check_require_billing_information
    respond_to do |format|
      if @account.update_attributes(params[:account])
        flash[:notice] = 'The account information was updated.'
        format.html do
          redirect_to_success
        end
        format.js   { render :js => "jQuery.flash.notice('#{flash[:notice]}')" }
      else
        format.html { render :action => 'edit' }
        format.js   { render :template => 'shared/error' }
      end
    end
  end

  private

  def protect_suspended_account
    render :suspended, layout: 'provider/suspended'
  end

  def redirect_to_success
    if upgrading_account?
      redirect_to edit_provider_admin_account_braintree_blue_path(next_step: 'upgrade_plan')
    else
      redirect_to provider_admin_account_path
    end
  end

  def check_require_billing_information
    @account.require_billing_information! if @account.bought_cinstance.paid? || upgrading_account?
  end

  def upgrading_account?
    params[:next_step] == 'credit_card'
  end

  def find_account
    @account = current_account
  end

  def find_countries
    @countries = Country.all
  end

  def deny_unless_can_update
    unless can?(:update, current_account)
      render :text => 'Action disabled', :status => :forbidden
    end
  end

end
