class InvoicesController < ApplicationController

  before_filter :require_login

  add_breadcrumb "Dashboard", :dashboard_path

  # It get all the invoice related information of user.
  def index
    if params[:user_id]
      @requested_user =  User.find(params[:user_id])
    end
    if params[:type]
      @type = params[:type]
    end
    add_breadcrumb "Invoices"
    @invoices = current_user.related_payments
    @invoices = @invoices.includes(from_user: [:profile_image], to_user: [:profile_image])
    @invoices = @invoices.order("invoice_transaction_views.created_at DESC").page(params[:page]).per(params[:per_page])
  end

  # It will show all user related payment on payment page.
  def show
    @invoice = current_user.related_payments.where("id = ? and payment_type = ?", params[:id], params[:type]).first
    respond_to do |format|
      format.pdf do
        render :pdf => "Invoice-#{@invoice.id}", template: 'invoices/show.pdf.slim', layout: 'pdf.html.slim', page_size: 'A6'
      end
    end
  end

  # Method to pay the invoice.
  def pay
    @invoice = Invoice.find(params[:id])
    if current_user.has_credit_card?
      if @invoice.user == current_user
        unless @invoice.paid?
          unless @invoice.charged?
            if Charge.charge_for(@invoice)
              @invoice.charged = true
              @invoice.save validate: false
            else
              respond_to do |format|
                message = "Unable to Charge your Card."
                format.html { redirect_to request.referer || dashboard_path, notice: message}
                format.js { redirect_via_turbolinks_to request.referer || dashboard_path, notice: message}
                return
              end
            end
          end
          if @invoice.pay_tutor
            flash[:notice] = "Invoice has been paid."
            respond_to do |format|
              format.js {}
            end
          else
            if @invoice.manually_billed?
              message = "Your amount for this invoice has been transfered to #{Configurations::General.application_name} escrow account. But unable to make payment to the #{Tutor.model_name.human}. Please contact #{Configurations::General.application_name} team."
            else
              message = "Unable to make payment to #{Tutor.model_name.human}. Please contact #{Configurations::General.application_name} team."
            end
            redirect_to request.referer || root_path, notice: message
          end
        else
          redirect_to dashboard_path, notice: 'This session has already been paid.'
        end
      else
        raise ActiveRecord::RecordNotFound
      end
    else
      respond_to do |format|
        format.js {}
      end
    end
  end

end
