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]

    if filter.nil?
      @crm_customers = Customer.all
    else
      @crm_customers = Customer.search(filter)

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

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

    # POST /crm/customers
  # POST /crm/customers.json
   def create

    @crm_customers = Customer.new(customer_params)

    respond_to do |format|
      if @crm_customers.save
          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]
          member_group_id = params[:member_group_id]

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

              begin
              response        = HTTParty.post(url,
                                        :body => {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,
                                        :headers => {
                                              'Content-Type' => 'application/json',
                                              'Accept'       => 'application/json'
                                                    },
                                        :timeout => 10
                               )
           
              rescue Net::OpenTimeout
                response = { status: false }

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

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

    respond_to do |format|
      if @crm_customer.update(customer_params)

        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]
        id              = @crm_customer.membership_id
        member_group_id = params[:member_group_id]

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

            begin
            response        = HTTParty.post(url,
                                      :body => { 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,
                                      :headers => {
                                               'Content-Type' => 'application/json',
                                               'Accept'       => 'application/json'
                                                  },
                                      :timeout => 10
                              )
            puts "hhhhhhhhh"
            puts response.to_json
            rescue Net::OpenTimeout
              response = { status: false }

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

            rescue SocketError
              response = { status: false}
            end

            if response["status"] == true

              customer = Customer.find(@crm_customer.customer_id)
              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

              customer = Customer.find(@crm_customer.customer_id)
              status   = customer.update_attributes(membership_type:member_group_id )

              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
            begin
            response        = HTTParty.post(url,
                                      :body => {name: name,phone: phone,email: email,
                                                dob: dob,address: address,nrc:nrc,card_no:card_no,
                                                id: id,member_group_id:member_group_id,merchant_uid:merchant_uid,auth_token:auth_token}.to_json,
                                      :headers => {
                                               'Content-Type' => 'application/json',
                                               'Accept'       => 'application/json'
                                                  },
                                      :timeout => 10
                                            )
            rescue Net::OpenTimeout
              response = { status: false }
              
            rescue OpenURI::HTTPError
              response = { status: false}

            rescue SocketError
              response = { status: false}
            end

            if response["status"] == true
              format.html { redirect_to crm_customers_path, notice: 'Customer was successfully updated.' }
              format.json { render :show, status: :ok, location: @crm_customer }
            else
              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(:name, :company, :contact_no, :email,
                :date_of_birth,:salutation,:gender,:nrc_no,:address,:card_no)
    end
end
