class Customer < ApplicationRecord

  #self.primary_key = :customer_id

  # Customer Image Uploader
  mount_uploader :image_path, CustomerImageUploader

  before_create :generate_custom_id
  has_many :orders
  has_many :sales

  validates_presence_of :name #, :contact_no #,:card_no
  # validates :contact_no, numericality: true, uniqueness: { scope: :shop_code }, allow_blank: true
  # validates :email, presence: true, uniqueness: { scope: :shop_code }, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }, allow_blank: true
  # validates :card_no, uniqueness: true
  # validates :paypar_account_no, uniqueness: true

  paginates_per 50

  def draft_customer(params, pin)
    cus = Customer.find_by_contact_no(params[:phone_number])
    if cus.nil?
      self.name = params[:name]
      self.contact_no = params[:phone_number]
      self.email = pin.to_s + "@gmail.com"
      self.pin_code = pin.to_s
      self.pin_sent_at = Time.current
      tax_profiles=TaxProfile.where(group_type: "online_order")
      tax_ids =[]
      tax_profiles.each {|tax| tax_ids << "#{tax.id}"}
      self.tax_profiles = tax_ids
      self.save
      return self
    else
      cus.pin_code = pin
      cus.pin_sent_at = Time.current
      cus.save
      return cus
    end
  end

  def self.walkin
    self.find_by(name: "WALK-IN")
  end

  def self.takeaway
    self.find_by(name: "TAKEAWAY")
  end

  def self.get_member_account(customer)
    membership      = MembershipSetting.active.find_by_membership_type("paypar_url")
    memberaction    = MembershipAction.active.find_by_membership_type("get_all_member_account")
    merchant_uid    = memberaction.merchant_account_id.to_s
    auth_token      = memberaction.auth_token.to_s
    url             = membership.gateway_url.to_s + memberaction.gateway_url.to_s
# urltest =self.url_exist?(url)
    if !membership.nil? && !memberaction.nil?
      begin
        response      = HTTParty.get(url, :body => {
                            membership_id: customer.membership_id,
                            merchant_uid:merchant_uid,
                            type: "summary",
                            auth_token:auth_token
                          }.to_json,
                              :headers => {
                                'Content-Type' => 'application/json',
                                'Accept'       => 'application/json; version=3'
                              },
                            :timeout => 10)
      rescue Errno::ECONNREFUSED
        response = {status: false, message: "Can't open membership server " }
      rescue HTTParty::Error
        response = {status: false, message: "Server Error"}

      rescue Net::OpenTimeout
        response = { status: false , message: "Server Time out"}

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

      rescue SocketError
        response = { status: false, message: "Can't connect server"}
      end
    else
      response = {status: false, message: "There is no membership setting."}
    end
    Rails.logger.debug "--------Get Member Account response -------"
    Rails.logger.debug response.to_json
    return response;

  end

  def self.get_membership_transactions(customer,receipt_no = nil)
    membership      = MembershipSetting.active.find_by_membership_type("paypar_url")
    memberaction    = MembershipAction.active.find_by_membership_type("get_member_transactions")
    if !membership.nil? && !memberaction.nil?
      merchant_uid    = memberaction.merchant_account_id.to_s
      auth_token      = memberaction.auth_token.to_s
      url             = membership.gateway_url.to_s + memberaction.gateway_url.to_s
  # urltest =self.url_exist?(url)

      begin
      response        = HTTParty.get(url,
                                      :body => { membership_id: customer.membership_id,
                                              receipt_no:receipt_no,
                                              merchant_uid:merchant_uid,auth_token:auth_token
                                              }.to_json,
                                      :headers => {
                                              'Content-Type' => 'application/json',
                                              'Accept'       => 'application/json; version=3'
                                      },
                                      :timeout => 10
                                 )

      rescue Errno::ECONNREFUSED
        response = {status: false, message: "Can't open membership server " }
      rescue HTTParty::Error
        response = {status: false, message: "Can't open membership server " }

      rescue Net::OpenTimeout
        response = { status: false , message: "Server Time out"}

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

      rescue SocketError
        response = { status: false, message: "Can't connect server"}
      end
    else
      response = {status: false, message: "There is no membership."}
    end
    Rails.logger.debug "get membership transactions !!!!!!!"
    Rails.logger.debug response
    return response;

  end

  def self.update_membership
    membership      = MembershipSetting.find_by_membership_type("paypar_url")
    memberaction    = MembershipAction.find_by_membership_type("create_membership_customer")
    merchant_uid    = memberaction.merchant_account_id.to_s
    auth_token      = memberaction.auth_token.to_s
    url             = membership.gateway_url.to_s + memberaction.gateway_url.to_s

    @customers    = Customer.where("membership_type IS NOT NULL AND membership_id IS NULL")

    @customers.each do |customer|
      member_params = { name: customer.name,phone: customer.contact_no,
                  email: customer.email,dob: customer.date_of_birth,
                  address: customer.address,nrc:customer.nrc_no,
                  card_no:customer.card_no,member_group_id: customer.membership_type,
                  merchant_uid:merchant_uid,auth_token:auth_token}.to_json

      # Check for paypar account exists
      # if paypar_account_no != nil || paypar_account_no != ''
      if customer.paypar_account_no.present?
        member_params = { name: customer.name,phone: customer.contact_no,
                        email: customer.email,dob: customer.date_of_birth,
                        address: customer.address,nrc:customer.nrc_no,
                        paypar_account_no: customer.paypar_account_no,
                        card_no:customer.card_no,member_group_id: customer.membership_type,
                        merchant_uid:merchant_uid,auth_token:auth_token}.to_json
      end

      begin
      response     = HTTParty.post(url,
                     :body => member_params,
                     :headers => {
                              'Content-Type' => 'application/json',
                              'Accept'       => 'application/json; version=3'
                      })
      rescue Errno::ECONNREFUSED
        response = {status: false, message: "Can't connect server" }
      rescue Net::OpenTimeout
        response = { status: false, message: "Server Time out" }

      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 "--------Update Membership response -------"
      Rails.logger.debug response.to_json
      if response["status"] == true
        status   = customer.update_attributes(membership_id: response["customer_datas"]["id"])
      end
    end
  end

  def self.update_rebate
    sales    = Sale.where("rebate_status = 'false'")
    sales.each do |sale|
      if sale.customer.membership_id
          response = self.rebat(Sale.find(sale.sale_id))
           #record an payment in sale-audit
           if !response.nil?
            remark = "UPdate Rebate Response - #{response} for Customer #{sale.customer_id} Sale Id [#{sale.sale_id}]| pay amount -> #{sale.amount_received} "
            sale_audit = SaleAudit.record_paymal(sale.sale_id, remark, 1)
          end
           if response["status"] == true
             status   = sale.update_attributes(rebate_status: "true")
           end
      end
    end
  end

  def self.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
          sObj.update_attributes(rebate_status: nil)
        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": "Connect To" }
        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|
            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

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

            end
          end
          rebate_arr.push(data)
        end

        total_amount = rebate_prices - payparcost - overall_dis

        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 "Rebage Response"
          Rails.logger.debug response.to_json
          return response
        end
      end
    else
      puts "no Response"
       response = { "status": "no_member", "message": "Not membership"}
    end
  end

  def self.search_paypar_account_no(account_no)
    membership      = MembershipSetting.find_by_membership_type("paypar_url")
    memberaction    = MembershipAction.find_by_membership_type("search_paypar_account_no")
    merchant_uid    = memberaction.merchant_account_id.to_s
    auth_token      = memberaction.auth_token.to_s
    url             = membership.gateway_url.to_s + memberaction.gateway_url.to_s
    begin
       response = HTTParty.get(url,
                            :body => { paypar_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 Errno::ECONNREFUSED
      response = {"status" => false, "message" => "No internet connection "}
    rescue HTTParty::Error
       response = {"status" => false, "message" => "No internet connection "}

    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
    case response.code
    when 404
      response = {"status" => false, "message" => "Not Found "}
    when 500...600
      response = {"status" => false, "message" => response.message}
    end
    Rails.logger.debug "--------Search Paypar Account No response -------"
    Rails.logger.debug response.to_json
    return response
  end

  def self.search(search)
    if search
      # find(:all, :conditions => ['name LIKE ? OR contact_no LIKE ?', "%#{search}%", "%#{search}%"])
      where("name LIKE ? OR customer_type LIKE ? OR contact_no LIKE ? OR card_no LIKE ? OR DATE_FORMAT(CONVERT_TZ(date_of_birth, '+00:00', '<%= Time.zone.formatted_offset %>'), '%Y-%m-%d') LIKE ? OR nrc_no LIKE ? OR gender LIKE ? OR paypar_account_no ='#{search}'", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%")
    else
      find(:all)
    end
  end

  def lastest_invoices
    sales.where(:customer_id => self.id).order("created_at desc").limit(5)
  end

  def self.count_customer
    all = self.all.count+1
    count = all-2

  end

   WALKIN   = "CUS-000000000001"
   TAKEAWAY = "CUS-000000000002"

  def self.check_paymalcard(url,token,merchant_uid,auth_token,account_no)
     # Control for Paypar Cloud
     begin
       response = HTTParty.get(url,
               :body => { merchant_uid:merchant_uid,auth_token:auth_token,paypar_account_no: account_no}.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 "search_paypar_account_no"
     Rails.logger.debug response.to_json
     if response["status"]
       response = { "status" => true, "message" => "Success"}
     else
       response = { "status" => false, "message" => response["message"]}
     end
     return response
  end
  def self.check_security_code(url,token,merchant_uid,auth_token,account_no)
     # Control for Paypar Cloud
     begin
       response = HTTParty.get(url,
               :body => { merchant_uid:merchant_uid,auth_token:auth_token,paypar_account_no: account_no}.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 "search_paypar_account_no"
     Rails.logger.debug response.to_json
     return response
  end
  private
  def generate_custom_id
    self.customer_id = SeedGenerator.generate_id(self.class.name, "CUS")
  end
end
