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 online order app
  def paymal_payment
    if params[:account_no] && params[:key] && params[:token] && params[:sale_id]
      sale = Sale.find_by_sale_id(params[:sale_id])
      sale_id = sale.sale_id

      if !sale.nil?
        @paid_amount = sale.grand_total
        current_shift = ShiftSale.current_shift
        @shop = Shop.current_shop
        @status,@message,@balance = check_security_code(sale,params)
        sale_items = SaleItem.get_all_sale_items(sale_id)
        if @status
          sale_payment = SalePayment.new
          @status, @sale, @membership_data = sale_payment.process_payment(sale, current_login_employee, sale.grand_total, "paymal",params[:account_no])
          if @status && @membership_data["status"] == true
            sale_payment = SalePayment.new
            status = sale_payment.process_payment(sale, current_login_employee, 0, "cash")

            rebate_amount = nil
            # For Cashier by Zone
            bookings = Booking.find_by_sale_id(sale_id)

            shift = ShiftSale.current_open_shift(current_login_employee)
            if !shift.nil?
              cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id)
            else
              if bookings.dining_facility_id.to_i > 0
                table = DiningFacility.find(bookings.dining_facility_id)
                cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
                cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id)

                type  = 'payment'
                from = getCloudDomain #get sub domain in cloud mode
                ActionCable.server.broadcast "order_channel",table: table,type:type,from:from
              else
                shift = ShiftSale.find(sale.shift_sale_id)
                cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id)
              end
            end

            # For Print
            if Lookup.collection_of("print_settings").any? { |x| x == ["ReceiptBillA5Pdf", "1"] } #print_settings with name:ReceiptBillA5Pdf
              unique_code = "ReceiptBillA5Pdf"
            else
              unique_code = PrintSetting.where("unique_code REGEXP ?", "receipt.*bill.*pdf").first.unique_code
            end

            customer = sale.customer

            # get member information
            rebate = MembershipSetting.find_by_rebate(1)
            credit_data = SalePayment.find_by_sale_id_and_payment_method(sale_id,'creditnote')

            if customer.membership_id != nil && rebate && credit_data.nil?
              member_info    = Customer.get_member_account(customer)

              if member_info["status"] == true
                rebate_amount  = Customer.get_membership_transactions(customer,sale.receipt_no)
                current_balance = SaleAudit.paymal_search(sale_id)
              end
            end

            #orders print out
            booking = Booking.find_by_sale_id(sale_id)
            if booking.dining_facility_id.to_i>0
              table_id = booking.dining_facility_id
            else
              table_id = 0
            end

            latest_order = booking.booking_orders.order("order_id DESC").limit(1).first()
            if !latest_order.nil?
              latest_order_no = latest_order.order_id
            end

            booking.booking_orders.each do |order|
              # Order.pay_process_order_queue(order.order_id, table_id)
              oqs = OrderQueueStation.new
              oqs.pay_process_order_queue(order.order_id, table_id)

              assign_order = AssignedOrderItem.assigned_order_item_by_job(order.order_id)
              from = getCloudDomain #get sub domain in cloud mode
              ActionCable.server.broadcast "order_queue_station_channel",order: assign_order,from:from
            end

            #for card sale data
            card_data = Array.new
            card_sale_trans_ref_no = Sale.getCardSaleTrans(sale_id)
            if !card_sale_trans_ref_no.nil?
              card_sale_trans_ref_no.each do |cash_sale_trans|
                card_res_date = cash_sale_trans.res_date.strftime("%Y-%m-%d").to_s
                card_res_time = cash_sale_trans.res_time.strftime("%H:%M").to_s
                card_no = cash_sale_trans.pan.last(4)
                card_no = card_no.rjust(19,"**** **** **** ")
                card_data.push({'res_date' => card_res_date, 'res_time' => card_res_time, 'batch_no' => cash_sale_trans.batch_no, 'trace' => cash_sale_trans.trace, 'pan' => card_no, 'app' => cash_sale_trans.app, 'tid' => cash_sale_trans.terminal_id, 'app_code' => cash_sale_trans.app_code, 'ref_no' => cash_sale_trans.ref_no, 'mid' => cash_sale_trans.merchant_id})
              end
            end

            #card_balance amount for Paymal payment
            card_balance_amount, transaction_ref = SaleAudit.getCardBalanceAmount(sale_id)

            # get printer info
            print_settings=PrintSetting.find_by_unique_code(unique_code)
            # Calculate Food and Beverage Total
            item_price_by_accounts = SaleItem.calculate_price_by_accounts(sale.sale_items)
            discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(sale.sale_items)
            other_amount = SaleItem.calculate_other_charges(sale_items)

            printer = Printer::ReceiptPrinter.new(print_settings)
            filename, sale_receipt_no, printer_name = printer.print_receipt_bill(print_settings, false, nil, cashier_terminal,sale_items,sale,params[:account_no], item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,@shop, 'paid',current_balance,card_data,other_amount,latest_order_no,card_balance_amount,nil,transaction_ref)
            render json: JSON.generate({:status => true, :balance_amount => card_balance_amount,:receipt_no => sale.receipt_no,:order_no => latest_order_no, :message => "complete", :paid_amount => sale.grand_total})
          end
        end
      else
        @status   = false
        @message  = "Invalid sale_id!"
      end
    else
      @status=false
      @message  = "Invalid account no and security code"
    end
  end

  private

  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

  #check paymal card
  def search_paypar_account_no
    if params[:sale_id] && params[:account_no]
      sale = Sale.find_by_sale_id(params[:sale_id])
      if !sale.nil?
        @shop =Shop.find_by_shop_code(sale.shop_code)
        membership_setting = MembershipSetting.find_by_membership_type_and_shop_code("paypar_url",sale.shop_code)
        if membership_setting.gateway_url
          member_actions =MembershipAction.find_by_membership_type_and_shop_code("search_paypar_account_no",sale.shop_code)
          if member_actions.gateway_url
            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 = Customer.check_paymalcard(url,membership_setting.auth_token,merchant_uid,auth_token,params[:account_no])
            @status   = membership_data["status"]
            @message  = membership_data["message"]
          else
            @status   = false
            @message  = "Invalid gateway url!"
          end
        else
          @status   = false
          @message  = "Invalid gateway url!"
        end
      else
        @status   = false
        @message  = "Invalid sale_id"
      end
    else
      @status   = false
      @message  = "Invalid sale_id or card_no"
    end
  end

  def check_security_code(sale,params)
    current_shift = ShiftSale.current_shift
    membership_setting = MembershipSetting.find_by_membership_type_and_shop_code("paypar_url",Shop.current_shop.shop_code)
    if membership_setting.gateway_url
      member_actions =MembershipAction.find_by_membership_type_and_shop_code("search_paypar_security_code",Shop.current_shop.shop_code)
      if member_actions.gateway_url
        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 = Customer.check_security_code(url,membership_setting.auth_token,merchant_uid,auth_token,params[:account_no])
        @status   = membership_data["status"]
        # @message  = membership_data["message"]
        if @status
          security_code = membership_data["account_data"]["security_code"]
          string = "card_no=#{params[:account_no]}passcode=#{membership_data["account_data"]["security_code"]}token=#{params[:token]}"
          hash = Digest::SHA256.hexdigest string
          if hash == params[:key]
            if membership_data["account_data"]["available_balance"].to_i >sale.grand_total
              @status   = true
              @message  = "complete"
              @balance  = membership_data["account_data"]["available_balance"]
            else
              @status   = false
              @message  = "insufficient"
              @balance  = membership_data["account_data"]["available_balance"]
            end
          else
            @status   = false
            @message  = "incorrect"
          end
        else
          @status   = false
        end
      else
        @status   = false
        @message  = "Invalid gateway url!"
      end
    else
      @status   = false
      @message  = "Invalid gateway url!"
    end
    return @status,@message,@balance
  end

  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
  #get cloud domain
  def getCloudDomain
    from = ""
    if ENV["SERVER_MODE"] == 'cloud'
      from = request.subdomain.to_s  + "." + request.domain.to_s
    end

    return from
  end
end
