class PaymentInvoiceController < ApplicationController
  before_action :authenticate_user!
  before_action :dashboard_topbar
  before_action :back_button_disable
  #load_and_authorize_resource :class => PaymentInvoice
  #skip_load_resource :only => [:new, :create]

  def billings 
    @payment_invoices = PaymentInvoice.where(organisation_id: current_user.organisation.id)
  end

  def new
    @payment_invoice = PaymentInvoice.new
    @purchase_order_amount = PurchaseOrder.where(:id => params["id"]).last
  end
 

  def make_payment
    purchase_order = PurchaseOrder.where(:id => params["payment_invoice"]["purchase_order_id"]).last
    if purchase_order.payment_invoices.present? ? purchase_order.payment_invoices.to_a.first.payment_status != "success" : ""
      @payment_invoice = current_user.organisation.payment_invoices.build
      token = params[:stripeToken]
      @purchase_order_amount = PurchaseOrder.where(:id =>params["payment_invoice"]["purchase_order_id"]).last
      #amount = params["payment_invoice"]["amount"].to_i * (@purchase_order_amount.purchase_order_items.count)
      amount = purchase_order.amount
      purchase_order_id = params["payment_invoice"]["purchase_order_id"]
      @payment_invoice[:stripeToken] = token
      @payment_invoice[:amount] = amount
      @payment_invoice[:ordered_by] = current_user.id
      @payment_invoice[:purchase_order_id] = purchase_order_id
      # Create a Customer
      begin
        customer = Stripe::Customer.create(
                    :card => token,
                    :email => current_user.email.present? ? current_user.email : "" ,
                    :description => "customer details"
                    
                 )
        puts customer
        @transcation = Stripe::Charge.create(
                          :amount => (amount.to_f*100).to_i, # in cents
                          :currency => "usd",
                          :customer => customer.id,
                          :description => "Charge for SimPayment"
                      )
        if @transcation["status"] == "succeeded"
          @payment_invoice[:transcation_id] = @transcation["id"]
          invoice_number = "PN-" + SecureRandom.hex(3)
          @payment_invoice[:invoice_number] = invoice_number
          @payment_invoice[:customer_id] = customer.id
          @payment_invoice[:customer_email] = customer.email
          @payment_invoice[:invoiced_on] = DateTime.now
          @payment_invoice[:payment_status] = "success"
          flash[:success] = "Payment created Successfully"
          @payment_invoice.save
          redirect_to invoice_payment_invoice_index_path(:invoice_number=> @payment_invoice.invoice_number)
        else
          @payment_invoice[:transcation_id] = @transcation["id"]
          @payment_invoice[:customer_id] = customer.id
          @payment_invoice[:customer_email] = customer.email
          @payment_invoice[:failure_message] = @transcation["failure_message"]
          @payment_invoice[:payment_status] = "failed"
          flash[:error] = "Payment failed due to #{@transcation["failure_message"]}"
           @payment_invoice.save
           redirect_to sim_managements_path
        end
       
      rescue Stripe::CardError => e
      # CardError; display an error message.
        flash[:error] = 'Please Check the Card Number and try again later'
        redirect_to new_payment_invoice_path(:id => purchase_order_id)
      rescue => e
        # Some other error; display an error message.
        flash[:error] = 'Something went wrong .please try later'
        redirect_to new_payment_invoice_path(:id => purchase_order_id)
      end
    else
      flash[:error] = "Oops! Payment completed.please make sim active"
      redirect_to sim_managements_path
    end  
  end

  def invoice
    if params[:invoice_number].present?
      @payment_invoice = PaymentInvoice.where(invoice_number: params["invoice_number"])
      @total_purchase_orders = @payment_invoice.last.purchase_order.purchase_order_items.where(:itemable_type=>"SimManagement").map(&:itemable).compact
    else
      flash[:error] = "Oops! Problem in displaying Invoice.Please try later"
      redirect_to sim_managements_path
    end  
  end


  def activated_plans
    if params["invoice"].present?
      @payment_invoice = PaymentInvoice.where(invoice_number: params["invoice"])
      if @payment_invoice.to_a.first.payment_status == "success"
        @purchase_order = @payment_invoice.last.purchase_order
        @purchase_order_all = @purchase_order.purchase_order_items.where(:itemable_type=>"SimManagement").map(&:itemable).compact
        @purchase_order_all.each do |item|
          @sim_rate_plan = SimRatePlan.where(:id => @purchase_order.sim_rate_plan_id).last
            # twilio API to activate the sim
            @response = @sim_rate_plan.activate_sim(item,"RatePlan=#{@sim_rate_plan.plan_id}&Status=active")
              logger.info "SIM ACTIVE RES Rateplan: " + @response.to_s
              logger.info "SIM ACTIVE:"
              logger.info "SIM ACTIVE RES: " + @response.to_s
            if @response["status"] == "active" || @response["status"] == "scheduled"
              logger.info "SIM ACTIVE IN:"
              item.is_active = "true"
              item.activated_on = DateTime.now
              item.current_status = "active"
              item.save
               logger.info "SIM ACTIVE IN:" + item.attributes.to_s
              flash[:success] = "Successfully activated plan"
            else 
              if @response["detail"].present?
               flash[:error] = "Activation failed due to #{@response["detail"]}" 
              elsif @response["message"].present?
                 flash[:error] = "Activation failed due to #{@response["message"]}"
              else
                flash[:error] = "Activation failed"
              end  
            end 
        end    
      else
        flash[:error] = "Oops! Payment failure .Please try later" 
      end     
    else
      flash[:error] = "Oops! Problem in activating the  Plan.Please try later" 
    end
    redirect_to sim_managements_path  
  end 


  def download_invoice
    @payment_invoice = PaymentInvoice.where(id: params[:id]).last
    @total_purchase_orders = @payment_invoice.purchase_order.purchase_order_items.where(:itemable_type=>"SimManagement").map(&:itemable).compact
    respond_to do |format|
      format.pdf do
        render pdf: "sim_invoice",
               template: "payment_invoice/download_invoice.pdf.erb",
               locals: {:invoice => @payment_invoice,
                        :purchase_order => @total_purchase_orders}
      end
    end
  end  

 

  private  

    def payment_invoice_params
      params.require(:payment_invoice).permit(:id,:stripeToken,:sim_management_id,:invoice_number,:purchased_on,:status)
    end

    def back_button_disable
      response.headers['Cache-control'] = 'no-cache,no-store'
    end  

end


