class PrintReceiptJob < ApplicationJob
  queue_as :high_priority

  def perform(shop_code, sale_id)
    current_shop = Shop.find_by(shop_code: shop_code)
    ActsAsTenant.with_tenant(current_shop) do
      saleObj = saleObj = Sale.find(sale_id)
      sale_items = SaleItem.get_all_sale_items(sale_id)

      booking = saleObj.booking
      latest_order_no = booking.booking_orders.last.order_id

      cashier_terminal = booking.cashier_terminal_by_dining_facility || saleObj.cashier_terminal_by_shift_sale

      customer = saleObj.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,saleObj.receipt_no)
          current_balance = SaleAudit.paymal_search(sale_id)
        end
      end

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

      print_settings = PrintSetting.where("unique_code REGEXP ?", "receipt.*bill.*pdf").first

      item_price_by_accounts = SaleItem.calculate_price_by_accounts(saleObj.sale_items)
      discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items)
      other_amount = SaleItem.calculate_other_charges(sale_items)

      printer = Printer::ReceiptPrinter.new(print_settings)

      if saleObj.sale_status == 'completed'
        printer.print_receipt_bill(print_settings, false, nil, cashier_terminal, sale_items, saleObj, customer.paypar_account_no, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, current_shop, 'paid', current_balance, card_data, other_amount, latest_order_no, card_balance_amount, nil, transaction_ref)
      elsif saleObj.generic_void?
        printer.print_receipt_bill(print_settings, false, nil,cashier_terminal, sale_items, saleObj, customer.paypar_account_no, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, current_shop, "VOID", current_balance, card_data, other_amount,nil,nil,nil)
      elsif saleObj.mmqr_cancel_void?
        printer.print_receipt_bill(print_settings, false, nil,cashier_terminal, sale_items, saleObj, customer.paypar_account_no, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, current_shop, "MMQR CANCEL", current_balance, card_data, other_amount,nil,nil,nil)
      end
    end
  end
end
