class Crm::CustomersController < BaseCrmController
  load_and_authorize_resource except: [:create]
  before_action :set_crm_customer, only: [:show, :edit, :update, :destroy,:sync]

  # GET /crm/customers
  # GET /crm/customers.json
  def index
    @no_need_validation =false
    filter = params[:filter]
    filter_card_no = params[:filter_card_no]
    type   = params[:type]
    @customer_update_phone_email_membertype =false
    if filter_card_no==""
      @crm_customers = Customer.all
    elsif !filter_card_no.nil?
      @crm_customers=Customer.where("card_no=?",filter_card_no)
    elsif filter.nil? || filter_card_no==""
      @crm_customers = Customer.all
    else
      @crm_customers = Customer.search(filter)
      # paymal_customer = Customer.search_paypar_account_no(filter)
      # search account no from paypar
      if type == "card"

       response = Customer.search_paypar_account_no(filter)
        if !@crm_customers.present?
          if response["status"] == true
            tax_ids =[]
            TaxProfile.all.each {|tax| tax_ids << "#{tax.id}"}
            @crm_customers =Customer.create(name: response["customer_data"]["name"],
                                            contact_no: response["customer_data"]["phone"],
                                            email: response["customer_data"]["email"],
                                            date_of_birth: response["customer_data"]["DOB"],
                                            nrc_no: response["customer_data"]["NRC"],
                                            address: response["customer_data"]["address"],
                                            card_no: response["customer_data"]["customer_card_no"],
                                            paypar_account_no: filter,
                                            membership_id: response["customer_data"]["id"],
                                            membership_type: response["customer_data"]["member_group_id"],
                                            customer_type: "Dinein",
                                            tax_profiles: tax_ids
                                            )
            @crm_customers = Customer.search(filter)
            flash[:member_notice]='Customer was successfully created.'
          else
            flash[:member_error]=response["message"]
          end
        else
          if response["status"] ==true
            @crm_customers.each do |customer|
              if !response["customer_data"].nil?
                if customer.contact_no != response["customer_data"]["phone"]
                  @customer_update_phone_email_membertype =true
                end
                if customer.email != response["customer_data"]["email"]
                    @customer_update_phone_email_membertype =true
                end
                if customer.name != response["customer_data"]["name"]
                    @customer_update_phone_email_membertype =true
                end
                if customer.membership_type.to_i != response["customer_data"]["member_group_id"]
                    @customer_update_phone_email_membertype =true
                end
              else
                flash[:member_error]=response["message"]
              end
            end
          else
            if response["message"] =='No internet connection '
              flash[:member_error]=response["message"]
            else
              flash[:member_error]="Need to press sync button "
            end

          end
        end
      end
    end
    @crm_customers  = Kaminari.paginate_array(@crm_customers).page(params[:page]).per(20)
    @crm_customer   = Customer.new
    @count_customer = Customer.count_customer

    @membership_types = Lookup.collection_of("member_group_type")

    # @taxes = TaxProfile.where(:group_type => 'cashier')
      @taxes = TaxProfile.unscope(:order).select("tax_profiles.id, CONCAT(tax_profiles.name, '(', lookups.name, ')') as name")
          .joins(:lookup)
          .order("group_type ASC, order_by ASC")

    @filter = filter

    #get paypar accountno
    @paypar_accountno = Customer.where("paypar_account_no IS NOT NULL AND paypar_account_no != ''").pluck("paypar_account_no")

    #for create customer on/off
    @create_flag = true
    lookup_customer = Lookup.collection_of('customer_settings')
    if !lookup_customer.empty?
      lookup_customer.each do |create_setting|
        if create_setting[0].downcase == "create"
          if create_setting[1] == '0' && current_login_employee.role == 'cashier'
            @create_flag = false
          end
        end
      end
    end
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @crm_customers }
    end
  end

  # GET /crm/customers/1
  # GET /crm/customers/1.json
  def show
    @orders = Order.where("customer_id=?", params[:id]).limit(20)
    @sales  = Sale.where("customer_id=?", params[:id]).limit(20)

    if @orders
      @order_items = []
      @orders.each do |order|
          @order_items = @order_items + order.order_items
      end
    end
    if @sales
      @sale_items = []
      @sales.each do |sale|
          @sale_items = @sale_items + sale.sale_items
      end
    end

    params[:type] = nil
    params[:customer_id] = params[:id]
    @credit_sales = SalePayment.get_credit_sales(params)

    #get customer amount
      @customer        = Customer.find(params[:id])
      @response        = Customer.get_membership_transactions(@customer)

      Rails.logger.debug "get membership transactions response"
      Rails.logger.debug @response.to_json
      # @response = ""
      #end customer amount

  end

  # GET /crm/customers/new
  def new
    @crm_customer = Customer.new
    @membership   = Customer.get_member_group()
  end

  # GET /crm/customers/1/edit
  def edit
    @customer        = Customer.find(params[:id])
  end

  def sync
    @customer        = Customer.find(params[:id])
    respond_to do |format|
      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
      paypar_account_no = @customer.paypar_account_no
      id              = @customer.membership_id
      member_group_id = @customer.membership_type
      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
      member_params = { name: name,phone: phone,email: email,
                        dob: dob,address: address,nrc:nrc,card_no:card_no,
                        member_group_id: member_group_id,
                        id:id,
                        merchant_uid:merchant_uid,auth_token:auth_token}.to_json

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

        begin
        response        = HTTParty.post(url,
                                  :body => member_params,
                                  :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
        customer = Customer.find(@crm_customer.customer_id)
        Rails.logger.debug "--------Sync Member response -------"
        Rails.logger.debug response.to_json
        if response["status"] == true

          status   = customer.update_attributes(membership_id: response["customer_datas"]["id"],membership_type:member_group_id )

          format.html { redirect_to crm_customers_path }
          flash[:member_notice] ='Member was successfully synced'
        else
          # Check membership id and bind to user
          if response["membership_id"] != nil
            status   = customer.update_attributes(membership_id: response["membership_id"],membership_type:member_group_id )
            format.html { redirect_to crm_customers_path }
            flash[:member_notice] ='Member was successfully synced'
          else
            status   = customer.update_attributes(membership_type:member_group_id)
          end
          # When paypar account no not exist in paypar
          if response["message"] == "Account does not exist."
            customer.destroy
            format.html { redirect_to crm_customers_path }
            flash[:member_error] ='Member cannot created.Invalid Account.'
          else
            format.html { redirect_to crm_customers_path }
            flash[:member_error] =response["message"]
          end
          format.html { redirect_to crm_customers_path }
          flash[:member_error] =response["message"]
        end
      end
    end
  end
    # POST /crm/customers
  # POST /crm/customers.json
  def create
    # Remove "" default first
    params[:customer][:tax_profiles].delete_at(0)
    @checked_contact = Customer.find_by_contact_no(customer_params[:contact_no])
    if @checked_contact.nil?
      respond_to do |format|
        @crm_customers = Customer.new(customer_params)
        if @crm_customers.save
          # update tax profile
          customer = Customer.find(@crm_customers.customer_id)
          customer.update_attributes(tax_profiles: params[:customer][:tax_profiles])
            name            = customer_params[:name]
            phone           = customer_params[:contact_no]
            email           = customer_params[:email]
            dob             = customer_params[:date_of_birth]
            address         = customer_params[:address]
            nrc             = customer_params[:nrc_no]
            card_no         = customer_params[:card_no]
            paypar_account_no = customer_params[:paypar_account_no]
            member_group_id = params[:member_group_id]

            if member_group_id.present?
                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

                member_params = { name: name,phone: phone,email: email,
                              dob: dob,address: address,nrc:nrc,card_no:card_no,
                              member_group_id: member_group_id,
                              merchant_uid:merchant_uid,auth_token:auth_token}.to_json

                # Check for paypar account exists
                # if paypar_account_no != nil || paypar_account_no != ''
                if paypar_account_no.present?
                  member_params = { name: name,phone: phone,email: email,
                                  dob: dob,address: address,nrc:nrc,card_no:card_no,
                                  paypar_account_no: paypar_account_no,
                                  member_group_id: member_group_id,
                                  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'
                                                      },
                                          :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
                Rails.logger.debug "--------------Create Member---------"
                Rails.logger.debug response.to_json
                if response["status"] == true
                    customer = Customer.find(@crm_customers.customer_id)
                    status   = customer.update_attributes(membership_id: response["customer_datas"]["id"],membership_type:member_group_id )

                    if params[:sale_id]
                        format.html { redirect_to '/origami/'+params[:sale_id]+'/'+params[:type]+'/customers/'+params[:page] }
                        flash[:member_notice]='Member was successfully created.'
                    else
                        format.html { redirect_to crm_customers_path }
                        flash[:member_notice]='Member was successfully created.'
                    end
                      # format.json { render :index, status: :created, location: @crm_customers }
                else
                    customer = Customer.find(@crm_customers.customer_id)

                    # Check membership id and bind to user
                    if response["membership_id"] != nil
                      status   = customer.update_attributes(membership_id: response["membership_id"],membership_type:member_group_id )
                      format.html { redirect_to crm_customers_path }
                      flash[:member_notice]='Member was successfully created.'
                    else
                      status   = customer.update_attributes(membership_type:member_group_id)
                    end
                    # When paypar account no not exist in paypar
                    if response["message"] == "Account does not exist."
                      customer.destroy
                      if params[:sale_id]
                        format.html { redirect_to '/origami/'+params[:sale_id]+'/'+params[:type]+'/customers/'+params[:page] }
                        flash[:member_error]='Member cannot created.Invalid Account.'
                      else
                        format.html { redirect_to crm_customers_path }
                        flash[:member_error]='Member cannot created.Invalid Account.'
                      end
                    else
                      format.html { redirect_to crm_customers_path }
                      flash[:member_error]=response["message"]
                    end
                    if params[:sale_id]
                        format.html { redirect_to '/origami/'+params[:sale_id]+'/'+params[:type]+'/customers/'+params[:page] }
                    flash[:member_notice]='Member was successfully created.' + response["message"]
                    else
                        format.html { redirect_to crm_customers_path }
                        # flash[:member_notice]='Member was successfully created.'
                    end
                end
            else
                if params[:sale_id]
                    format.html { redirect_to '/origami/'+params[:sale_id]+'/'+params[:type]+'/customers/'+params[:page], notice: 'Customer was successfully created. noted'}
                  else
                    format.html { redirect_to crm_customers_path, notice: 'Customer was successfully created. ' }
                end
            end
        else
            if params[:sale_id]
              flash[:errors] = @crm_customers.errors
              format.html { redirect_to '/origami/'+params[:sale_id]+'/'+params[:type]+'/customers/'+params[:page]}
              format.json { render json: @crm_customers.errors, status: :unprocessable_entity }
            else
              flash[:errors] = @crm_customers.errors
              format.html { redirect_to crm_customers_path}
              format.json { render json: @crm_customers.errors, status: :unprocessable_entity }
            end
        end
      end
    else
      flash[:errors] = {"contact_no":["has already been taken"]}
      respond_to do |format|
        if params[:sale_id]
          format.html { redirect_to '/origami/'+params[:sale_id]+'/'+params[:type]+'/customers/'+params[:page]}
        else
          format.html { redirect_to crm_customers_path}
        end
        format.json { render json: @crm_customers.errors, status: :unprocessable_entity }
      end
    end #end of contact no checked
  end
  # PATCH/PUT /crm/customers/1
  # PATCH/PUT /crm/customers/1.json
  def update
    # Remove "" default first
    params[:customer][:tax_profiles].delete_at(0)
    @checked_contact = nil
    @existed_contact = Customer.find_by_customer_id_and_contact_no(customer_params[:id], customer_params[:contact_no])
    if @existed_contact.nil?
      @checked_contact = Customer.find_by_contact_no(customer_params[:contact_no])
    end
    if !@existed_contact.nil? || @checked_contact.nil?
      respond_to do |format|
        if @crm_customer.update(customer_params)
          # update tax profile
          @crm_customer.update_attributes(tax_profiles: params[:customer][:tax_profiles])
          name            = customer_params[:name]
          phone           = customer_params[:contact_no]
          email           = customer_params[:email]
          dob             = customer_params[:date_of_birth]
          address         = customer_params[:address]
          nrc             = customer_params[:nrc_no]
          card_no         = customer_params[:card_no]
          paypar_account_no = customer_params[:paypar_account_no]
          id              = @crm_customer.membership_id
          member_group_id = params[:member_group_id]

          if !id.present? && !member_group_id.nil?
              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

              member_params = { name: name,phone: phone,email: email,
                                dob: dob,address: address,nrc:nrc,card_no:card_no,
                                member_group_id: member_group_id,
                                id:id,
                                merchant_uid:merchant_uid,auth_token:auth_token}.to_json

              # Check for paypar account exists
              # if paypar_account_no != nil || paypar_account_no != ''
              if paypar_account_no.present?
                member_params = { name: name,phone: phone,email: email,
                                  dob: dob,address: address,nrc:nrc,card_no:card_no,
                                  paypar_account_no: paypar_account_no,
                                  member_group_id: member_group_id,
                                  id:id,
                                  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'
                                                    },
                                        :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
              customer = Customer.find(@crm_customer.customer_id)
              Rails.logger.debug "--------Update Member response -------"
              Rails.logger.debug response.to_json
              if response["status"] == true

                status   = customer.update_attributes(membership_id: response["customer_datas"]["id"],membership_type:member_group_id )

                format.html { redirect_to crm_customers_path }
                flash[:member_notice]='Member was successfully updated'
              else
                # Check membership id and bind to user
                if response["membership_id"] != nil
                  status   = customer.update_attributes(membership_id: response["membership_id"],membership_type:member_group_id )
                  format.html { redirect_to crm_customers_path }
                  flash[:member_notice]='Member was successfully updated'
                else
                  status   = customer.update_attributes(membership_type:member_group_id)
                  format.html { redirect_to crm_customers_path }
                  flash[:member_error]=response["message"]
                end
              end
          else
              membership      = MembershipSetting.find_by_membership_type("paypar_url")
              memberaction    = MembershipAction.find_by_membership_type("update_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

              member_params = { name: name,phone: phone,email: email,
                                dob: dob,address: address,nrc:nrc,card_no:card_no,
                                member_group_id: member_group_id,
                                id:id,
                                merchant_uid:merchant_uid,auth_token:auth_token}.to_json

              # Check for paypar account exists
              if paypar_account_no.present?
                member_params = { name: name,phone: phone,email: email,
                                  dob: dob,address: address,nrc:nrc,card_no:card_no,
                                  paypar_account_no: paypar_account_no,
                                  member_group_id: member_group_id,
                                  id:id,
                                  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'
                                                    },
                                        :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
              Rails.logger.debug "--------Update Member response -------"
              Rails.logger.debug response.to_json
              if response["status"] == true
                customer = Customer.find(@crm_customer.customer_id)
                # Check membership id and bind to user
                if response["membership_id"] != nil
                  status   = customer.update_attributes(membership_id: response["membership_id"],membership_type:member_group_id )
                else
                  status   = customer.update_attributes(membership_type:member_group_id )
                end
                format.html { redirect_to crm_customers_path }
                flash[:member_notice] ='Member was successfully updated.'
                format.json { render :show, status: :ok, location: @crm_customer }
              else
                customer = Customer.find(@crm_customer.customer_id)
                # Check membership id and bind to user
                if response["membership_id"] != nil
                  status   = customer.update_attributes(membership_id: response["membership_id"],membership_type:member_group_id )
                else
                  status   = customer.update_attributes(membership_type:member_group_id )
                end
                format.html { redirect_to crm_customers_path }
                flash[:member_error] =response["message"]
              end
          end
        else

          flash[:errors] = @crm_customer.errors
          format.html { redirect_to crm_customers_path}
          format.json { render json: @crm_customer.errors, status: :unprocessable_entity }
        end
      end
    else
      flash[:errors] = {"contact_no":["has already been taken"]}
      respond_to do |format|
        if params[:sale_id]
          format.html { redirect_to '/origami/'+params[:sale_id]+'/'+params[:type]+'/customers/'+params[:page]}
        else
          format.html { redirect_to crm_customers_path}
        end
        format.json { render json: @crm_customers.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /crm/customers/1
  # DELETE /crm/customers/1.json
  def destroy
    @crm_customer.destroy
    respond_to do |format|
      format.html { redirect_to crm_customers_url, notice: 'Customer was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def customer_update_phone_email_member_type
     @customer  = Customer.find(params[:id])
     response = Customer.search_paypar_account_no(@customer.paypar_account_no)
     if response["status"] == true
        @customer.update_attributes(name: response["customer_data"]["name"],
                                    contact_no: response["customer_data"]["phone"],
                                    email: response["customer_data"]["email"],
                                    membership_type: response["customer_data"]["member_group_id"]
                                    )
        respond_to do |format|
          format.html { redirect_to crm_customers_path }
          flash[:member_notice]='Membership was successfully updated'
        end
     end


  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_crm_customer
      @crm_customer = Customer.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def customer_params

      params.require(:customer).permit(:id, :name, :company, :contact_no, :email,
                :date_of_birth,:salutation,:gender,:nrc_no,:address,:card_no, :paypar_account_no, :customer_type, :image_path)
    end

end
