class Api::PaymentsController < Api::ApiController


  #Payment by Invoice ID
  # Payment Method - [Cash | CreditNote | VISA | MASTER | etc..]
  # Invoice No | Amount
  # Output
  # Status - [True/False] | Invoice | error_message (* when status false)
  def  create
    @invoice = Sale.find(params[:invoice_id])

    if (@invoice)
      handle_payment(@invoice)
    end
  end

  # Update of payment status from the external party
  # Invoice No | Payment ID | External params [] (* third party references and status)
  #
  def update
  end

  #create paymal payment for cashier app
  def paymal_payment
    if params[:sale_id] && params[:card_no]
      sale = Sale.find_by_sale_id(params[:sale_id])
      if !sale.nil?
        if sale.sale_status == "new"
          if !params[:card_no].empty?
            @status, @message = send_account_paymal(sale.grand_total, params[:card_no], sale.receipt_no)
            if @status
              sale_payment = SalePayment.new
              status, @sale, @membership_data = sale_payment.process_payment(sale, current_login_employee, sale.grand_total, "paymal",params[:card_no])

              if status == true && @membership_data["status"] == true
                sale_payment = SalePayment.new
                status = sale_payment.process_payment(sale, current_login_employee, 0, "cash")
                #card_balance amount for Paymal payment
                card_balance_amount = SaleAudit.getCardBalanceAmount(params[:sale_id])

                render json: JSON.generate({:status => true, :balance_amount => card_balance_amount,:receipt_no => sale.receipt_no, :message => "Payment successful."})
              else
                if @membership_data
                  if @membership_data["card_balance_amount"] != "null"
                    render json: JSON.generate({:status => false, :balance_amount => @membership_data["card_balance_amount"], :error_message => @membership_data["message"]})
                  else
                    render json: JSON.generate({:status => false, :error_message => @membership_data["message"]})
                  end
                else
                  render json: JSON.generate({:status => false, :error_message => "Payment failed!"})
                end
              end
            else
              render json: JSON.generate({:status => false, :error_message => @message})
            end
          else
            render json: JSON.generate({:status => false, :error_message => "Card No is required!"})
          end
        else
          render json: JSON.generate({:status => false, :error_message => "Already paid for '#{params[:sale_id]}'!"})
        end
      else
        render json: JSON.generate({:status => false, :error_message => "There is no sale for '#{params[:sale_id]}'!"})
      end
    else
      render json: JSON.generate({:status => false, :error_message => "Parameters missing! #{params[:sale_id]} #{params[:card_no]}"})
    end
  end

  def send_account_paymal(amount, account_no, receipt_no)
    sale = Sale.find_by_receipt_no(receipt_no)
    @out = []
    action_by = current_login_employee.name
    @status = true
    @message = ""
    membership_setting = MembershipSetting.find_by_membership_type("paypar_url")
    if membership_setting.gateway_url
      member_actions =MembershipAction.find_by_membership_type("get_account_balance")
      if member_actions.gateway_url
        @campaign_type_id = nil
        url = membership_setting.gateway_url.to_s + member_actions.gateway_url.to_s
        merchant_uid= member_actions.merchant_account_id
        auth_token = member_actions.auth_token.to_s
        membership_data = SalePayment.get_paypar_account_data(url,membership_setting.auth_token,merchant_uid,auth_token,account_no,amount,receipt_no)
        if membership_data["status"]==true
          remark = "Payment by account no Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} | Transaction ref: #{membership_data[:transaction_ref]} | Reload amount #{membership_data[:reload_amount]} | Old Balance Amount #{membership_data[:old_balance_amount]} | DateTime : #{membership_data[:date]}"
          sale_audit = SaleAudit.record_audit_for_edit(sale.sale_id,current_login_employee.name, current_login_employee.name,remark,"PAYBYACCOUNT" )
        else
          remark = "Payment by account no Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} | Remark : #{membership_data[:message]}"
          sale_audit = SaleAudit.record_audit_for_edit(sale.sale_id,current_login_employee.name, current_login_employee.name,remark,"PAYBYACCOUNT" )
        end
        @out = membership_data

        @status   = membership_data["status"]
        @message  = membership_data["message"]
      end
    else
      @status   = false
      @message  = "No gateway url!"
    end

    return @status, @message
  end

  #create paymal payment for cashier app

  private
  def handle_payment(sale_payment)

    payment_method = params[:payment_method]
    sale_payment = SalePayment.new

    #:received_amount, :card_payment_reference, :vochure_no, :giftcard_no,
    #:customer_id, :external_payment_status
    case payment_method
      when "cash"
        sale_payment.payment_method = "cash"
        sale_payment.received_amount = params[:amount]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "creditnote"
        sale_payment.payment_method = "creditnote"
        sale_payment.received_amount = params[:amount]
        sale_payment.customer_id = params[:customer_id]

        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "visa"
        sale_payment.payment_method = "visa"
        sale_payment.received_amount = params[:amount]
        sale_payment.payment_reference = params[:payment_reference]

        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "master"
        sale_payment.payment_method = "master"
        sale_payment.received_amount = params[:amount]
        sale_payment.payment_reference = params[:payment_reference]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "jcb"
        sale_payment.payment_method = "jcb"
        sale_payment.received_amount = params[:amount]
        sale_payment.payment_reference = params[:payment_reference]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "mpu"
        sale_payment.payment_method = "mpu"
        sale_payment.received_amount = params[:amount]
        sale_payment.payment_reference = params[:payment_reference]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "unionpay"
        sale_payment.payment_method = "unionpay"
        sale_payment.received_amount = params[:amount]
        sale_payment.payment_reference = params[:payment_reference]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "vochure"
        sale_payment.payment_method = "vochure"
        sale_payment.received_amount = params[:amount]
        sale_payment.customer_id = params[:customer_id]
        sale_payment.payment_reference = params[:vochure_no]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "giftcard"
        sale_payment.payment_method = "giftcard"
        sale_payment.received_amount = params[:amount]
        sale_payment.customer_id = params[:customer_id]
        sale_payment.payment_reference = params[:giftcard_no]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "paypar"
        sale_payment.payment_method = "paypar"
        sale_payment.received_amount = params[:amount]
        sale_payment.payment_reference = params[:payment_reference]
        #TODO: implement paypar implementation
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "JunctionPay"
        sale_payment.payment_method = "JunctionPay"
        sale_payment.received_amount = params[:amount]
        sale_payment.customer_id = params[:customer_id]
        sale_payment.payment_reference = params[:vochure_no]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
      when "alipay"
        sale_payment.payment_method = "alipay"
        sale_payment.received_amount = params[:amount]
        sale_payment.payment_reference = params[:payment_reference]
        @status, @invoice = sale_payment.process_payment(sale_payment, current_login_employee)
    end
  end
end
