class SalePayment < ApplicationRecord

  CARD = ['mpu', 'visa', 'master', 'jcb', 'unionpay']

  self.primary_key = "sale_payment_id"

  #primary key - need to be unique generated for multiple shops
  before_create :generate_custom_id

  belongs_to :sale

  has_one :sale_audit, -> { where "SUBSTRING_INDEX(sale_audits.remark,'||',1) = sale_payments.sale_payment_id" }, foreign_key: "sale_id", primary_key: "sale_id"

  attr_accessor :received_amount, :card_payment_reference, :voucher_no, :giftcard_no, :customer_id, :external_payment_status,:action_by

  scope :credits, -> { where(payment_method: 'creditnote') }
  scope :cards, -> { where(payment_method: ['mpu', 'visa', 'master', 'jcb', 'unionpay']) }

  def self.sync_sale_payment_records(sale_payments)
    if !sale_payments.nil?
      sale_payments.each do |sp|
        payment = SalePayment.find_by_sale_payment_id(sp['sale_payment_id'])
        # unless SalePayment.exists?(sp['sale_payment_id'])
        if payment.nil?
          payment = SalePayment.new
        end
        payment.sale_payment_id = sp['sale_payment_id']
        payment.sale_id = sp['sale_id']
        payment.payment_method = sp['payment_method']
        payment.payment_amount = sp['payment_amount']
        payment.outstanding_amount = sp['outstanding_amount']
        payment.payment_reference = sp['payment_reference']
        payment.payment_status = sp['payment_status']
        payment.save
      end
      Rails.logger.debug '....... Sale Payment sync completed ......'
    end
  end

  def self.get_kbz_pay_amount(sale_id, current_user)
    amount = 0
    kbz_pay_method = PaymentMethodSetting.where(payment_method: KbzPay::KBZ_PAY, gateway_communication_type: ['api', 'Api'], is_active: true)
                                          .where.not(gateway_url: [nil, ''], auth_token: [nil, ''], merchant_account_id: [nil, '']).last
    sale_payment = SalePayment.where('sale_id=? and payment_method=? and payment_status!=?', sale_id, KbzPay::KBZ_PAY, 'dead').last
    if !sale_payment.nil? and !kbz_pay_method.nil?
      if sale_payment.payment_status == 'pending'
        amount = KbzPay.query(sale_payment.id, current_user, kbz_pay_method.gateway_url, kbz_pay_method.auth_token, kbz_pay_method.merchant_account_id, kbz_pay_method.additional_parameters)
      elsif sale_payment.payment_status == 'paid'
        amount = sale_payment.payment_amount
      end
    end

    return amount
  end

  def process_kbz_payment(sale_id, grand_total, pay_amount, status)
    if status == 'pending'
      SalePayment.where("sale_id=? and payment_method=? and payment_status=?", sale_id, KbzPay::KBZ_PAY, 'pending').update_all(:payment_status => 'dead')
    end

    self.sale_id = sale_id
    self.payment_method = KbzPay::KBZ_PAY
    self.payment_amount = self.payment_amount.to_i + pay_amount.to_i
    if grand_total > 0
      self.outstanding_amount = grand_total.to_i - pay_amount.to_i
    else
      self.outstanding_amount = self.outstanding_amount.to_i - pay_amount.to_i
    end
    self.payment_status = status
    return self.save
  end

  def process_payment(invoice, action_by, cash_amount, payment_method, remark=nil, payment_for=false)
    self.sale = invoice
    self.received_amount = cash_amount
    self.payment_reference = remark
    self.action_by = action_by
    #get all payment for this invoices
    if payment_for
      amount_due = SalePayment.get_credit_amount_due_left(self.sale_id).first.payment_amount
    elsif payment_method == 'foc'
      amount_due = invoice.total_amount
    else
      amount_due = invoice.sale_payments
      .map(&:payment_amount).reduce(invoice.grand_total, :-)
    end

    if amount_due > 0
      payment_status = false
      membership_data = nil
      #route to payment type
      case payment_method
        when "cash"
          payment_status, outstanding_amount, balance_amount = cash_payment(payment_for)
        when "creditnote"
          if !self.sale.customer_id.nil?
            payment_status = creditnote_payment(self.customer_id)
          end
        when "visa"
           payment_status = external_terminal_card_payment(:visa, payment_for)
        when "master"
           payment_status = external_terminal_card_payment(:master, payment_for)
        when "jcb"
           payment_status = external_terminal_card_payment(:jcb, payment_for)
        when "mpu"
           payment_status = external_terminal_card_payment(:mpu, payment_for)
        when "unionpay"
           payment_status = external_terminal_card_payment(:unionpay, payment_for)
        when "alipay"
          payment_status = external_terminal_card_payment(:alipay, payment_for)
        when "vochure"
           payment_status = vochure_payment
        when "giftcard"
           payment_status = giftcard_payment
        when "paypar"
          payment_status = paypar_payment
        when "foc"
          payment_status = foc_payment
        when "paymal"
          payment_status, membership_data = paymal_payment
        when "JunctionPay"
          payment_status = junction_pay_payment
        when "dinga"
          payment_status,membership_data = dinga_payment
        when "GiftVoucher"
          payment_status = giftvoucher_payment
        else
          payment_status = external_terminal_card_payment(payment_method, payment_for)
      end

      if payment_status
        #record an payment in sale-audit
        remark = "Payment #{payment_method}- for Invoice #{invoice.receipt_no} Due [#{amount_due}]| pay amount -> #{cash_amount} | Payment Status ->#{payment_status}"
        if payment_for
          current_shift_user =Employee.find_by_id(self.sale.cashier_id)
          shift = ShiftSale.current_open_shift(current_shift_user)
          if !shift.nil?
            shift_sale_id = shift.id
          else
            shift = ShiftSale.current_shift(self.sale.shop_code)
            shift_sale_id = shift.id
          end

          remark = "#{self.sale_payment_id}||#{shift_sale_id} -> #{remark}"

          sale_audit = SaleAudit.record_payment(invoice.id, remark, action_by.name)
        else
          sale_audit = SaleAudit.record_payment(invoice.id, remark, action_by.name)
        end

        # update complete order items in oqs
        booking = Booking.find_by_sale_id(sale_id)
        booking.booking_orders.each do |sodr|
          assigned = AssignedOrderItem.where("order_id = '#{ sodr.order_id }'").pluck(:assigned_order_item_id)
          AssignedOrderItem.where('assigned_order_item_id IN (?)', assigned).update_all(delivery_status: true)
          # AssignedOrderItem.where("order_id = '#{ sodr.order_id }'").find_each do |aoi|
          #   aoi.delivery_status = 1
          #   aoi.save
          # end
        end

        return true, self.save, membership_data, outstanding_amount, balance_amount
      else
        #record an payment in sale-audit
        remark = "Payment failed - Grand Total [#{invoice.grand_total}] | Due [#{amount_due}] | Paid [#{invoice.amount_received}]"
        sale_audit = SaleAudit.record_payment(invoice.id, remark,action_by.name)
        # return false, "Payment failed"
        return false, self.save, membership_data
      end
    else
      sale_update_payment_status(0)
      #record an payment in sale-audit
      remark = "No outstanding Amount - Grand Total [#{invoice.grand_total}] | Due [#{amount_due}] | Paid [#{invoice.amount_received}]"
      sale_audit = SaleAudit.record_payment(invoice.id, remark,action_by.name)

      return false, "No outstanding Amount"
    end

  end

  def kbz_edit_sale_payment(amt, action_by)
    self.action_by = action_by
    sale_update_payment_status(amt)
  end

  def self.get_paypar_account(url,token,membership_id,campaign_type_id,merchant_uid,auth_token)
    # Control for Paypar Cloud
    begin
      response = HTTParty.get(url,
              :body => { app_token: token,membership_id:membership_id,
                        campaign_type_id:campaign_type_id,merchant_uid:merchant_uid,
                        auth_token:auth_token
                        }.to_json,
              :headers => {
                        'Content-Type' => 'application/json',
                        'Accept' => 'application/json; version=3'
              }, :timeout => 10
        )
    rescue Net::OpenTimeout
        response = { status: false }

    rescue OpenURI::HTTPError
      response = { status: false}

    rescue SocketError
      response = { status: false}
    end
    Rails.logger.debug "Get Paypar Account "
    Rails.logger.debug response.to_json
    return response
  end

  def self.get_paypar_account_data(url,token,merchant_uid,auth_token,account_no,amount,receipt_no)
    # Control for Paypar Cloud
    begin
      response = HTTParty.get(url,
              :body => { merchant_uid:merchant_uid,auth_token:auth_token,receipt_no: receipt_no,
                account_no: account_no, amount: amount}.to_json,
              :headers => {
                        'Content-Type' => 'application/json',
                        'Accept' => 'application/json; version=4'
              }, :timeout => 10
        )
    rescue Errno::ECONNREFUSED
        response = { "status" => false, "message" => "Can't open membership server"}
    rescue Net::OpenTimeout
        response = { "status" => false, "message" => "No internet connection " }
    rescue OpenURI::HTTPError
        response = { "status" => false, "message" => "No internet connection "}
    rescue SocketError
        response = { "status" => false, "message" => "No internet connection "}
    end
    Rails.logger.debug "Get Paypar Account "
    Rails.logger.debug response.to_json
    return response;
  end

  def self.redeem(paypar_url,token,membership_id,received_amount,sale_id)
      membership_actions_data = MembershipAction.find_by_membership_type("redeem")
      if !membership_actions_data.nil?

        url = paypar_url.to_s + membership_actions_data.gateway_url.to_s
        merchant_uid = membership_actions_data.merchant_account_id
        auth_token = membership_actions_data.auth_token
        campaign_type_id = membership_actions_data.additional_parameter["campaign_type_id"]
        sale_data = Sale.find_by_sale_id(sale_id)
        account_no = Customer.find_by_customer_id(self.sale.customer_id).paypar_account_no

        if sale_data
          others = 0
          sale_data.sale_payments.each do |sale_payment|
              others = others + sale_payment.payment_amount
          end
          redeem_prices = sale_data.grand_total - others
          # Control for Paypar Cloud
          begin
            response = HTTParty.post(url,
                  :body => { membership_id:membership_id,
                            total_amount: redeem_prices,
                            total_sale_transaction_amount: sale_data.grand_total,
                            redeem_amount:received_amount,
                            receipt_no:sale_data.receipt_no,
                            campaign_type_id:campaign_type_id,
                            account_no: account_no,
                            merchant_uid:merchant_uid,
                            auth_token:auth_token}.to_json,
                  :headers => {
                            'Content-Type' => 'application/json',
                            'Accept' => 'application/json; version=3'
                  },
                  :timeout => 10
            )
          rescue Net::OpenTimeout
            response = false

          rescue OpenURI::HTTPError
            response = { status: false}

          rescue SocketError
            response = { status: false}
          end
        else
            response = false;
        end

      else
        response =false;
      end

      Rails.logger.debug "Redeem response"
      Rails.logger.debug response.to_json

      return response;

  end

  def self.create_payment(paypar_url,membership_type,membership_id,received_amount,sale_id)
      membership_actions_data = MembershipAction.find_by_membership_type(membership_type);
      sale_data = Sale.find_by_sale_id(sale_id)
      customer_data = Customer.find_by_customer_id(sale_data.customer_id)
      if !membership_actions_data.nil?

        url = paypar_url.to_s + membership_actions_data.gateway_url.to_s
        merchant_uid = membership_actions_data.merchant_account_id
        auth_token = membership_actions_data.auth_token

        if sale_data
          others = 0
          sale_data.sale_payments.each do |sale_payment|
              others = others + sale_payment.payment_amount
          end
          payment_prices = sale_data.grand_total - others

          if membership_id.to_i <= 0
          membership_id  = customer_data.membership_id
            params  = { membership_id:membership_id,
                            amount:received_amount,
                            receipt_no:sale_data.receipt_no,
                            merchant_uid:merchant_uid,
                            auth_token:auth_token}.to_json
          else
            params  = { account_no:membership_id,
                            amount:received_amount,
                            receipt_no:sale_data.receipt_no,
                            merchant_uid:merchant_uid,
                            auth_token:auth_token}.to_json
          end

          # Control for Paypar Cloud
          begin
            response = HTTParty.post(url,
                  :body => params,
                  :headers => {
                            'Content-Type' => 'application/json',
                            'Accept' => 'application/json; version=4'
                  },
                  :timeout => 10
            )
          rescue Net::OpenTimeout
            response = false

          rescue OpenURI::HTTPError
            response = { status: false}

          rescue SocketError
            response = { status: false}
          end
        else
            response = false;
        end

      else
        response =false;
      end

      Rails.logger.debug "Create Payment response"
      Rails.logger.debug response.to_json

      return response;

  end

    # Check for Card Payment
  def self.get_sale_payments_by_card(sale_payments)
    # Check for Card Payment
    payment_methods = SalePayment.where.not(payment_method: ['cash', 'creditnote', 'foc']).distinct.pluck(:payment_method)
    sale_payments.each do |sp|
      payment_methods.each do |m|
        if sp.payment_method == m
          return true;
        end
      end
      # if sp.payment_method == "jcb" || sp.payment_method == "mpu" || sp.payment_method == "visa" || sp.payment_method == "master" || sp.payment_method == "unionpay" || sp.payment_method == "alipay"
      #   return true;
      # end
    end
  end

  private
  def cash_payment(payment_for=false)

    sale_payments_data = SalePayment.find_by_sale_id(self.sale_id)
    payment_status = false

    self.payment_method = "cash"
    self.payment_amount = self.received_amount
    if !payment_for
      self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
    else
      credit_sale_payment = SalePayment.get_credit_total_left(self.sale_id)[0] ? SalePayment.get_credit_total_left(self.sale_id)[0].payment_amount.to_f : 0  ###need to calculate creditnote total in here
      self.outstanding_amount = credit_sale_payment - self.received_amount.to_f
    end

    self.payment_status = "paid"
    payment_status = self.save!
    if !payment_for
      sale_update_payment_status(self.received_amount)
    else
      update_shift_for_credit_payment()
    end

    balance_amount =0.0
    outstanding_amount =0.0
    if self.sale.grand_total.to_f > self.received_amount.to_f
      balance_amount = self.sale.grand_total.to_f - self.received_amount.to_f
      outstanding_amount = 0.0
    else
      balance_amount = 0.0
      outstanding_amount = self.received_amount.to_f - self.sale.grand_total.to_f
    end
    return payment_status , outstanding_amount.to_i, balance_amount.to_i
  end

  def foc_payment
    payment_status = false
    sale =  self.sale
    sale.sale_payments.update_all(payment_status: "cancelled")
    # add to sale item with foc
    sale_items = sale.sale_items

    sale_items.each do|item|
      SaleItem.update_existing_item(item.qty, item, sale.sale_id, "foc", item.unit_price, item.price)
    end

    sale.compute_by_sale_items(sale.total_discount,'','','',"foc")

    self.payment_method = "foc"
    self.payment_amount = self.received_amount

    self.outstanding_amount = 0.00
    self.payment_status = "paid"
    payment_status = self.save!
    # sale_update_payment_status(self.received_amount)
    sale_update_payment_status(0, true)
    return payment_status
  end

  def creditnote_payment(customer_id)
    payment_status = false

    self.payment_method = "creditnote"
    self.payment_amount = self.received_amount
    self.customer_id  = self.customer_id
    self.outstanding_amount = 0 - self.received_amount.to_f
    self.payment_status = "outstanding"
    payment_status = self.save!

    sale_update_payment_status(self.received_amount)
    return payment_status
  end

  def external_terminal_card_payment(method, payment_for=false)
    payment_status = false
    self.payment_method = method
    self.payment_amount = self.received_amount
    # self.payment_reference  = self.card_payment_reference
    if !payment_for
      self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
    else
      credit_payment = SalePayment.get_credit_total_left(self.sale_id) ###need to calculate creditnote total in here
      self.outstanding_amount = credit_payment[0].payment_amount.to_f - self.received_amount.to_f
    end
    self.payment_status = "paid"
    payment_status = self.save!
    if payment_for
      update_shift_for_credit_payment
    else
      sale_update_payment_status(self.received_amount)
    end
    return payment_status
  end

  def voucher_payment
    payment_status = false

    #Next time - validate if the vochure number is valid - within
    self.payment_method = "voucher"
    self.payment_amount = self.received_amount
    self.payment_reference  = self.voucher_no
    self.outstanding_amount = self.sale.grand_total- self.received_amount
    self.payment_status = "paid"
    payment_status = self.save!
    sale_update_payment_status(self.received_amount)

    return payment_status

  end

  def giftcard_payment
    payment_status = false

    #Next time - validate if the vochure number is valid - within
    self.payment_method = "giftcard"
    self.payment_amount = self.received_amount
    self.payment_reference  = self.giftcard_no
    self.outstanding_amount = self.sale.grand_total- self.received_amount
    self.payment_status = "paid"
    payment_status = self.save!
    sale_update_payment_status(self.received_amount)

    return payment_status

  end

  def paypar_payment
    payment_status = false

    #Next time - validate if the vochure number is valid - within
    customer_data = Customer.find_by_customer_id(self.sale.customer_id)
    membership_setting = MembershipSetting.find_by_membership_type("paypar_url")
    membership_data = redeem(membership_setting.gateway_url,membership_setting.auth_token,customer_data.membership_id,self.received_amount,self.sale.sale_id)

     #record an payment in sale-audit
      remark = "#{membership_data} Redeem- for Customer #{self.sale.customer_id} Sale Id [#{self.sale.sale_id}]| pay amount -> #{self.received_amount} "
      sale_audit = SaleAudit.record_paymal(self.sale.sale_id, remark, 1)

    if membership_data["status"]==true
      self.payment_method = "paypar"
      self.payment_amount = self.received_amount
      self.payment_reference  = self.voucher_no
      self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
      self.payment_status = "paid"
      payment_status = self.save!
      # SalePayment.where(:sale_payment_id => self.sale_payment_id).update_all(:payment_status => 'paid')
      sale_update_payment_status(self.received_amount.to_f)

    else
      sale_update_payment_status(0)
    end
    return payment_status

  end

  def paymal_payment
    payment_status = false

    #Next time - validate if the vochure number is valid - within
    account_no = self.payment_reference
    # self.sale.customer.update_attributes(paypar_account_no: )
    membership_setting = MembershipSetting.find_by_membership_type("paypar_url")
    membership_data = SalePayment.create_payment(membership_setting.gateway_url,"create_payment",account_no,self.received_amount,self.sale.sale_id)

     #record an payment in sale-audit
      remark = "#{membership_data} PayMal Payment- for Customer #{self.sale.customer_id} Sale Id [#{self.sale.sale_id}]| pay amount -> #{self.received_amount} "
      sale_audit = SaleAudit.record_paymal(self.sale.sale_id, remark, 1)

    if membership_data["status"] == true
      self.payment_method = "paymal"
      self.payment_amount = self.received_amount
      # self.payment_reference  = self.voucher_no
      self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
      self.payment_status = "paid"
      payment_status = self.save!
      # SalePayment.where(:sale_payment_id => self.sale_payment_id).update_all(:payment_status => 'paid')
      sale_update_payment_status(self.received_amount.to_f)
    else
      sale_update_payment_status(0)
    end

    return payment_status,membership_data
  end

  def junction_pay_payment
    payment_status = false

    #Next time - validate if the vochure number is valid - within
    self.payment_method = "JunctionPay"
    self.payment_amount = self.received_amount
    # self.payment_reference  = self.payment_reference
    self.outstanding_amount = self.sale.grand_total- self.received_amount
    self.payment_status = "paid"
    payment_status = self.save!
    sale_update_payment_status(self.received_amount)
    return payment_status
  end

  def dinga_payment
    payment_status = false

    #Next time - validate if the vochure number is valid - within

    # customer_data = Customer.find_by_customer_id(self.sale.customer_id)

    account_no = self.payment_reference
    # if account_no == 0
    #   account_no  = customer_data.customer_id
    # end

    membership_setting = MembershipSetting.find_by_membership_type("paypar_url")
    membership_data = SalePayment.create_payment(membership_setting.gateway_url,"dinga_payment",account_no,self.received_amount,self.sale.sale_id)

     #record an payment in sale-audit
      remark = "#{membership_data} Dinga Payment- for Customer #{self.sale.customer_id} Sale Id [#{self.sale.sale_id}]| pay amount -> #{self.received_amount} "
      sale_audit = SaleAudit.record_paymal(self.sale.sale_id, remark, 1)

    if membership_data["status"]==true
      self.payment_method = "dinga"
      self.payment_amount = self.received_amount
      self.payment_reference  = self.voucher_no
      self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
      self.payment_status = "paid"
      payment_status = self.save!
      SalePayment.where(:sale_payment_id => self.sale_payment_id).update_all(:payment_status => 'paid')
      sale_update_payment_status(self.received_amount.to_f)
    else
      sale_update_payment_status(0)
    end

    return payment_status,membership_data

  end

  def giftvoucher_payment
    payment_status = false
    self.payment_method = "giftvoucher"
    self.payment_amount = self.received_amount
    self.payment_reference  = self.payment_reference
    self.outstanding_amount = self.sale.grand_total.to_f - self.received_amount.to_f
    self.payment_status = "paid"
    payment_status = self.save!
    sale_update_payment_status(self.received_amount)
    return payment_status
  end

  def sale_update_payment_status(paid_amount, check_foc = false)
    #update amount_outstanding
    if !self.sale || ['completed'].include?(self.sale.sale_status)
      return
    end

    sale = self.sale
    sale_payments = sale.sale_payments.reload

    is_credit = sale_payments.any? { |x| x.payment_method == "creditnote" }
    is_foc = sale_payments.any? { |x| x.payment_method == "foc" } || check_foc

    if is_foc
      sale.amount_received = 0.0
      sale.amount_changed = 0.0
      sale.payment_status = 'foc'
      sale.sale_status = 'completed'
    elsif sale.grand_total <= sale_payments.sum(&:payment_amount) && sale.sale_status == "new"
      sale.amount_received = sale.amount_received + paid_amount.to_d
      sale.amount_changed = sale_payments.sum(&:payment_amount) - sale.grand_total

      sale.payment_status = "paid"
      if is_credit
        sale.payment_status = "outstanding"
      end

      sale.sale_status = "completed"

      if MembershipSetting.find_by_rebate(1) && !is_foc && !is_credit
        response = rebat(sale)

         #record an payment in sale-audit
         remark = "#{response} Rebate- for Customer #{sale.customer_id} | Sale Id [#{sale.sale_id}]| pay amount -> #{self.received_amount} "
         sale_audit = SaleAudit.record_paymal(sale.sale_id, remark, 1)

        if !response.nil?
          if response["status"] == true
          sale.rebate_status = 'true'
          end
          if response["status"] == false
            sale.rebate_status = 'false'
          end

          if response[:status] == false
            sale.rebate_status = 'false'
          end
          if response[:status] == "no_member"
            sale.rebate_status = nil
          end
        end
      end
    end
    sale.save!

    if sale.sale_status == 'completed'
      table_update_status(sale)
      update_shift
    end
  end

  # update for cashier shift
  def update_shift
    current_shift_user = Employee.find_by_id(self.action_by.id)
    shift = ShiftSale.current_open_shift(current_shift_user)

    if shift.nil?
      current_shift_user = Employee.find_by_id(self.sale.cashier_id)
      shift = ShiftSale.current_open_shift(current_shift_user)
    end

    if !shift.nil?
      shift.update(self.sale)
      self.sale.shift_sale_id = shift.id
      self.sale.cashier_id = shift.employee_id
      self.sale.cashier_name = Employee.find(shift.employee_id).name
      self.sale.save
    else
      shift = ShiftSale.current_shift
      shift.update(self.sale)
      self.sale.shift_sale_id = shift.id
      self.sale.cashier_id = shift.employee_id
      self.sale.cashier_name = Employee.find(shift.employee_id).name
      self.sale.save
    end
  end

   # update for shift with credit payment
  def update_shift_for_credit_payment
    shift_credit = ShiftSale.find_by_id(self.sale.shift_sale_id)
    shift = self.action_by.current_shift
    if !shift.nil?
      shift = ShiftSale.current_shift
    end
    if !shift.nil?
      credit_payment_left = get_credit_payment_left[0].payment_amount.to_f
      if self.payment_method == "cash"
        if credit_payment_left == 0 || credit_payment_left >= self.received_amount.to_f
          shift.cash_sales = shift.cash_sales.to_f + self.received_amount.to_f
        else
          # extra_changed_amount = self.received_amount.to_f + credit_payment_left
          shift.cash_sales = shift.cash_sales.to_f + (self.received_amount.to_f + credit_payment_left)
          self.sale.amount_received =   self.sale.amount_received.to_f - credit_payment_left
          self.sale.amount_changed = self.sale.amount_changed.to_f - credit_payment_left
          self.sale.save!
        end
      else
        shift.other_sales = shift.other_sales.to_f + self.received_amount.to_f
      end
      if credit_payment_left == 0 || credit_payment_left >= self.received_amount.to_f
        if shift.id == shift_credit.id
          shift.credit_sales = shift_credit.credit_sales.to_f - self.received_amount.to_f
        end

      else
        shift.credit_sales = shift_credit.credit_sales.to_f - (self.received_amount.to_f + credit_payment_left)
      end
      shift.save
    end
  end

  def table_update_status(sale_obj)
    puts "Update staus 1"
    if booking = sale_obj.booking
      puts "Update staus 2"
      if booking.dining_facility
        puts "Update staus 3"
        table = booking.dining_facility
        if !table.current_bookings.exists?
          puts "Update staus 3"
          table.update_attributes(status: "available")
        end
      end
    end
  end

  def rebat(sObj)
    rebate_prices,campaign_method = SaleItem.calculate_rebate_by_account(sObj.sale_items)
    generic_customer_id = sObj.customer.membership_id

    if generic_customer_id.present?

      paypar     = sObj.sale_payments
      payparcost = 0
      credit     = 0

      paypar.each do |pp|
        if pp.payment_method == "paypar"
          payparcost = payparcost + pp.payment_amount
        end
        if pp.payment_method == "creditnote"
          credit = 1
        end
      end
      # overall_dis = SaleItem.get_overall_discount(sObj.id)
      overall_dis   = sObj.total_discount

      if credit != 1
        membership        = MembershipSetting.find_by_membership_type("paypar_url")
        memberaction      = MembershipAction.find_by_membership_type("get_member_campaign")
        merchant_uid      = memberaction.merchant_account_id.to_s
        campaign_type_id  = memberaction.additional_parameter["campaign_type_id"]
        auth_token        = memberaction.auth_token.to_s
        url               = membership.gateway_url.to_s + memberaction.gateway_url.to_s

        # Control for Paypar Cloud
        begin
          response = HTTParty.get(url,
                                :body => {
                                  member_group_id:sObj.customer.membership_type,
                                  merchant_uid:merchant_uid,
                                  campaign_type_id: campaign_type_id,
                                  auth_token:auth_token
                                }.to_json,
                                :headers => {
                                  'Content-Type' => 'application/json',
                                  'Accept'       => 'application/json; version=3'
                                }, :timeout => 10)
        rescue Net::OpenTimeout
           response = { "status": false , "message": " Connection timeout" }
        rescue OpenURI::HTTPError
           response = { "status": false, "message": "Can't connect server"}

        rescue SocketError
           response = { "status": false, "message": "Can't connect server"}
        end

        redeem_amount = payparcost + overall_dis

        total_percentage = 0

        type_arr = []
        Rails.logger.debug "-------------Get Member Campaign--------------"
        Rails.logger.debug response.to_json
        # Check for present response fields
        if response["membership_campaign_data"].present?
          response["membership_campaign_data"].each do |a|
            campaign_method.each do |cm|
              if cm[:type].downcase.strip == a["rules_type"].downcase.strip
                if cm[:amount] > 0
                  data = {:type => a["rules_type"], :percentage => a["change_unit"].to_i * a["base_unit"].to_i}
                  total_percentage = total_percentage + a["change_unit"].to_i * a["base_unit"].to_i

                  type_arr.push(data)
                end
              end
            end
          end
        end

        Rails.logger.debug "--------------Get Member Campaign Data----------"
        Rails.logger.debug type_arr.to_json

        rebate_arr =[]

        campaign_method.each do |a|
          data = {:type => a[:type], :amount => a[:amount]}
          type_arr.each do |si|
            if (si[:type] == a[:type]) && (a[:amount] > 0)
              if credit == 1
                 data[:amount] = 0
              else
                amount = (redeem_amount / total_percentage).to_f * si[:percentage]
                actual = a[:amount].to_f - amount.to_f
                data[:amount] = actual
              end

            end
          end
          rebate_arr.push(data)
        end
        Rails.logger.debug "---------------Rebate Response----------------"
        Rails.logger.debug rebate_arr.to_json

     		total_amount = rebate_prices - payparcost - overall_dis
        Rails.logger.debug total_amount

        if credit == 1
          total_amount = 0
        end

        if total_amount >= 0
       		receipt_no        = sObj.receipt_no
          membership        = MembershipSetting.find_by_membership_type("paypar_url")
          memberaction      = MembershipAction.find_by_membership_type("rebate")
          merchant_uid      = memberaction.merchant_account_id.to_s
          campaign_type_id  = memberaction.additional_parameter["campaign_type_id"]
          auth_token        = memberaction.auth_token.to_s
          url               = membership.gateway_url.to_s + memberaction.gateway_url.to_s

          # Control for Paypar Cloud
          begin
            response = HTTParty.post(url,
                                  :body => {
                                    generic_customer_id:generic_customer_id ,
                                    total_sale_transaction_amount: sObj.grand_total,
                                    merchant_uid:merchant_uid,
                                    total_amount: total_amount,
                                    campaign_type_id: campaign_type_id,
                                    receipt_no: receipt_no,
                                    campaign_method: rebate_arr.to_json,
                                    auth_token:auth_token
                                  }.to_json,
                                  :headers => {
                                    'Content-Type' => 'application/json',
                                    'Accept'       => 'application/json; version=3'
                                  }, :timeout => 10)
          rescue Net::OpenTimeout
             response = { "status": false , "message": "Connect To" }
          rescue OpenURI::HTTPError
             response = { "status": false, "message": "Can't connect server"}

          rescue SocketError
             response = { "status": false, "message": "Can't connect server"}
          end
          Rails.logger.debug "Rebate Response"
          Rails.logger.debug response.to_json
          return response
        end
      end
    else
       response = { "status": "no_member", "message": "Not membership"}
    end

  end

  #credit payment query

  def self.get_credit_sales(params)
    total_payment_amounts = SalePayment.select("sale_payments.sale_id, SUM(sale_payments.payment_amount) as total_payment_amount").group(:sale_id)

    payments = SalePayment.select("sale_payments.sale_id, sale_payments.sale_payment_id, sale_payments.payment_method, sale_payments.payment_amount")
              .select("total_payment_amount")
              .joins("JOIN (#{total_payment_amounts.to_sql}) AS total_payment_amounts ON total_payment_amounts.sale_id = sale_payments.sale_id")

    credit_sales = Sale.select("sales.sale_id, sales.receipt_no, sales.receipt_date as sale_date, sales.cashier_name")
                  .select("sale_payments.sale_payment_id, sale_payments.payment_amount").select("customers.name as customer_name")
                  .joins("JOIN (#{payments.to_sql}) AS sale_payments ON sale_payments.sale_id = sales.sale_id").joins(:customer).joins(:orders)
                  .completed.where("sale_payments.payment_method = 'creditnote' AND sales.grand_total > sale_payments.total_payment_amount - sale_payments.payment_amount")
                  .group(:receipt_no)
                  .order(:receipt_date).order(:receipt_no)

    if params["receipt_no"].present?
      credit_sales = credit_sales.where("sales.receipt_no LIKE ?", "%#{params["receipt_no"]}%")

    end

    if params["customer_id"].present?
      credit_sales = credit_sales.where("sales.customer_id = ?", params["customer_id"])
    end

    if params[:type].present?
      sources = []
      sources << params[:type]
      sources << 'emenu' if params[:type] == 'cashier'
      credit_sales = credit_sales.where("orders.source IN (?)", sources)
    end

  end

  def self.get_credit_amount_due_left(sale_id)
    SalePayment.left_joins(:sale_audit).where(sale_id: sale_id)
      .select("SUM(CASE WHEN sale_payments.payment_method = 'creditnote' THEN sale_payments.payment_amount ELSE 0 END) - SUM(CASE WHEN sale_audits.sale_audit_id IS NOT NULL THEN sale_payments.payment_amount ELSE 0 END) AS payment_amount")
  end

  def self.get_credit_total_left(sale_id)
    SalePayment.left_joins(:sale_audit).where(sale_id: sale_id)
      .select("SUM(CASE WHEN sale_payments.payment_method = 'creditnote' THEN sale_payments.payment_amount ELSE 0 END) - SUM(CASE WHEN sale_audits.sale_audit_id IS NOT NULL THEN sale_payments.payment_amount ELSE 0 END) AS payment_amount")
  end

  def self.get_sale_payment_for_credit(sale_data)
    sale_data.sale_payments
      .joins(:sale_audit)
  end

  def get_credit_payment_left
    SalePayment.left_joins(:sale_audit).where(sale_id: sale_id)
      .select("SUM(CASE WHEN sale_payments.payment_method = 'creditnote' THEN sale_payments.payment_amount ELSE 0 END) - SUM(CASE WHEN sale_audits.sale_audit_id IS NOT NULL THEN sale_payments.payment_amount ELSE 0 END) AS payment_amount")
  end

  def self.get_sale_payments(sale_data)
    sale_data.sale_payments
      .merge(SalePayment.where.not(payment_method: 'creditnote')
      .or(SalePayment.where.not(SalePayment.arel_table[:payment_amount].lteq(sale_data.sale_payments.joins(:sale_audit).sum(:payment_amount)))))
  end
  private
  def generate_custom_id
     if self.sale_payment_id.nil?
        self.sale_payment_id = SeedGenerator.generate_id(self.class.name, "SPI")
     end
  end
end
