class SimPaymentsController < ApplicationController
	before_action :authenticate_user!
  before_action :dashboard_topbar
  #load_and_authorize_resource :class => SimManagement

	def new
    @sim_payments = SimPayment.new
  end
 
  def create
    @sim_payments = current_user.organisation.sim_payment.build
    token = params[:stripeToken]
    amount = params["sim_payment"]["amount"]
    sim_management_id = params["sim_payment"]["sim_management_id"]
    invoice_number = "PN-" + SecureRandom.hex(3)
    @sim_payments[:invoice_number] = invoice_number
    @sim_payments[:stripeToken] = token
    @sim_payments[:amount] = amount
    @sim_payments[:sim_management_id] = sim_management_id
    Stripe::Charge.create(
            :amount => amount, # in cents
            :currency => "cad",
            source: token,
            :description => "Charge for SimPayment"
        )
    if @sim_payments.save
      flash[:success] = "Payment created Successfully"
      redirect_to invoice_sim_payments_path(:invoice_number=> @sim_payments.invoice_number)
    else
      flash[:error] = "Oops! Problem in payment.Please try again"
      Rails.logger.warn "#{@sim_payments.errors.full_messages}"
      @exisitng_sim_payments = current_user.organisation.sim_payments.all
      render :index
    end
  end

  def invoice
    if params[:invoice_number].present?
      @exisitng_sim_managements = SimPayment.where(invoice_number: params["invoice_number"])
      @sim_management = SimManagement.where(id: 22).first
    else
      flash[:error] = "Oops! Problem in displaying Plans.Please try later"
      redirect_to sim_managements_path
    end  
  end

  def sim_payments_params
      params.require(:sim_payment).permit(:id,:stripeToken,:sim_management_id,:amount,:invoice_number)
    end
end
