class KbzPay

  KBZ_PAY = 'KBZPay'

  def self.pay(amount, receipt_no, url, key, app_id, code)
    shop = Shop.first
    prefix = shop.shop_code
    receipt_no = "#{prefix}#{receipt_no}"

    datetime = DateTime.now.strftime("%d%m%Y%H%M")
    kbz_app_id = app_id
    kbz_merch_code = code    
    kbz_api_key = key
    kbz_provider_url = "#{url}/precreate"

    kbz_method = 'kbz.payment.precreate'
    kbz_trade_type = "PAY_BY_QRCODE"
    kbz_version = "1.0"
    kbz_currency = "MMK"
    kbz_callback_url = "https://staging-v2.doemal.com/api/v3/ordering/kbz_callback"

    nounce_str = SecureRandom.base64(32).first(32).upcase

    params = "appid="+kbz_app_id+"&merch_code="+kbz_merch_code+"&merch_order_id="+receipt_no.to_s+"&method="+kbz_method+"&nonce_str="+nounce_str.to_s+"&notify_url="+ kbz_callback_url + "&timeout_express=20m&timestamp="+datetime+"&total_amount="+amount.to_s+"&trade_type="+kbz_trade_type+"&trans_currency="+ kbz_currency+"&version="+kbz_version+"&key="+kbz_api_key

    Rails.logger.info params
	  sign = Digest::SHA256.hexdigest(params)
		str = {
           "timestamp": datetime,
			     "method": kbz_method,
           "notify_url":  kbz_callback_url,
			     "nonce_str": nounce_str.to_s,
			     "sign_type": "SHA256",
			     "sign": sign,
			     "version": kbz_version,
			     "biz_content": {
			                     "merch_order_id": receipt_no,
			                     "merch_code": kbz_merch_code,
			                     "appid": kbz_app_id,
			                     "trade_type": kbz_trade_type,
			                     "total_amount": amount.to_s,
                           "timeout_express": "20m",
			                     "trans_currency": kbz_currency
			                    }
		      }

		result = HTTParty.post(kbz_provider_url,
        :body => { :Request => str}.to_json,
        :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }
    )
    Rails.logger.info result
    Rails.logger.info '===================================='
    if result['Response']['result'] == "SUCCESS"
      #TODO QR return
      qr = result['Response']['qrCode']
      return true, qr
    else
      # Rails.logger.debug result['Response']
      return false, result['Response']
    end
    
	end

  def self.query(receipt_no, current_user, url, key, app_id, code)
    shop = Shop.first
    prefix = shop.shop_code
    receipt_no = "#{prefix}#{receipt_no}"
    amount = 0
    datetime = DateTime.now.strftime("%d%m%Y%H%M")
    kbz_app_id = app_id
    kbz_merch_code = code    
    kbz_api_key = key
    kbz_provider_url = "#{url}/queryorder"

    kbz_method = 'kbz.payment.queryorder'
    kbz_trade_type = "PAY_BY_QRCODE"
    kbz_version = "1.0"
    kbz_currency = "MMK"
    kbz_callback_url = "https://staging-v2.doemal.com/api/v3/ordering/kbz_callback"

    nounce_str = SecureRandom.base64(32).first(32).upcase

    params = "appid="+kbz_app_id+"&merch_code="+kbz_merch_code+"&merch_order_id="+receipt_no.to_s+"&method="+kbz_method+"&nonce_str="+nounce_str.to_s+"&timestamp="+datetime+"&version="+kbz_version+"&key="+kbz_api_key

    Rails.logger.info params
    sign = Digest::SHA256.hexdigest(params)
    str = {"timestamp": datetime,
           "method": kbz_method,
           "nonce_str": nounce_str.to_s,
           "sign_type": "SHA256",
           "sign": sign,
           "version": kbz_version,
           "biz_content": {
                            "merch_order_id": receipt_no,
                            "merch_code": kbz_merch_code,
                            "appid": kbz_app_id
                          }
          }

    result = HTTParty.post(kbz_provider_url,
        :body => { :Request => str}.to_json,
        :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }
    )
    Rails.logger.info result
    Rails.logger.info "........................."
    if result['Response']['result'] == "SUCCESS"
      if result['Response']['trade_status'] == "PAY_SUCCESS"
        merch_order_id = result['Response']['merch_order_id']
        cash = result['Response']['total_amount']

        merch_order_id.slice! "#{prefix}"

        sp = SalePayment.find(merch_order_id)
        if !sp.nil?
          if sp.payment_status == 'pending'
            saleObj = Sale.find(sp.sale_id)
            if sp.process_payment(saleObj, current_user, cash, KbzPay::KBZ_PAY)
              amount = cash
            end
          end
        end

        # return true, "successfully paid by KBZ PAY"
      elsif result['Response']['trade_status'] == "PAY_FAILED"
          
        # return false, "pay failed by KBZ PAY"
      elsif result['Response']['trade_status'] == "WAIT_PAY"
        # return false , "Waiting to pay by KBZ PAY"
      end
    else
      #FAIL result
      # return false, "pay by KBZ PAY has failed"
    end

    return amount
  end

end