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

  # GET /crm/customers
  # GET /crm/customers.json
  def index
    filter = params[:filter]
    type   = params[:type]
    if filter.nil?
      @crm_customers = Customer.all
    else
      @crm_customers = Customer.search(filter)
      # search account no from paypar
      if !@crm_customers.present? && type == "card"
        response = Customer.search_paypar_account_no(filter)
        if response["status"] == true
          @crm_customers = Customer.new
          @crm_customers.name              = response["customer_data"]["name"]
          @crm_customers.contact_no        = response["customer_data"]["phone"]
          @crm_customers.email             = response["customer_data"]["email"]
          @crm_customers.date_of_birth     = response["customer_data"]["DOB"]
          @crm_customers.nrc_no            = response["customer_data"]["NRC"]
          @crm_customers.address           = response["customer_data"]["address"]
          @crm_customers.card_no           = response["customer_data"]["customer_card_no"]
          @crm_customers.paypar_account_no = filter
          @crm_customers.membership_id     = response["customer_data"]["id"]
          @crm_customers.membership_type   = response["customer_data"]["member_group_id"]
          @crm_customers.customer_type     = "Dinein"
          @crm_customers.tax_profiles      = ["1", "2"]
          @crm_customers.save
          @crm_customers = Customer.search(filter)
        end
      end
    end
    @crm_customers  = Kaminari.paginate_array(@crm_customers).page(params[:page]).per(20)
    @crm_customer   = Customer.new
    @count_customer = Customer.count_customer

    @taxes = TaxProfile.all.order("order_by asc")

    @filter = filter

    # if flash["errors"]
    #   @crm_customer.valid?
    # 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])
    @sales  = Sale.where("customer_id=?", params[:id])

    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

    #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

    # POST /crm/customers
  # POST /crm/customers.json
   def create 
    # Remove "" default first 
    params[:customer][:tax_profiles].delete_at(0)   
    @crm_customers = Customer.new(customer_params)

    respond_to do |format|
      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=2'
                                                    },
                                        :timeout => 10
                               )

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

                 rescue Net::OpenTimeout
                   response = {"status" => false, "message" => "Can't open membership server "}

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

                 rescue SocketError
                   response = {"status" => false, "message" => "Can't open membership server "}
              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]+'/customers', notice: 'Customer was successfully created.' }
                  else
                      format.html { redirect_to crm_customers_path, notice: 'Customer 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 )
                  else
                    status   = customer.update_attributes(membership_type:member_group_id)
                  end

                  # When paypar account no not exist in paypar
                  if response["message"] == "Account has not exist."
                    customer.destroy
                    if params[:sale_id]
                      format.html { redirect_to '/origami/'+params[:sale_id]+'/customers', notice: 'Customer cannot created.' + response["message"]}
                    else
                      format.html { redirect_to crm_customers_path, notice: 'Customer cannot created.' + response["message"] }
                    end
                  end

                  if params[:sale_id]
                      format.html { redirect_to '/origami/'+params[:sale_id]+'/customers', notice: 'Customer was successfully created.' + response["message"]}
                  else
                      format.html { redirect_to crm_customers_path, notice: 'Customer was successfully created.' + response["message"] }
                  end
              end
          else
              if params[:sale_id]
                  format.html { redirect_to '/origami/'+params[:sale_id]+'/customers', 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]+'/customers'}
            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
end
  # PATCH/PUT /crm/customers/1
  # PATCH/PUT /crm/customers/1.json
  def update
    # Remove "" default first 
    params[:customer][:tax_profiles].delete_at(0)
    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=2'
                                                  },
                                      :timeout => 10
                              )
            rescue Net::OpenTimeout
              response = { status: false }

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

            rescue SocketError
              response = { status: false}
            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, notice: 'Customer 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 )
              else
                status   = customer.update_attributes(membership_type:member_group_id)
              end

              format.html { redirect_to crm_customers_path, notice: response["error"] }
            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=2'
                                                  },
                                      :timeout => 10
                                            )
            rescue Net::OpenTimeout
              response = { status: false }

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

            rescue SocketError
              response = { status: false}
            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, notice: 'Customer 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, notice: 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
  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

  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)
    end
end
