class Api::CustomersController < Api::ApiController

  #List all active customers by name
  def index
    @customers = Customer.order("name asc")
  end

  #Show customer by ID
  def show
    @customer = Customer.find_by(params[:id])
  end

  def create
    return unless params[:name].present? && params[:email].present? && params[:contact_no].present?
    @customer = Customer.new(name: params[:name], email: params[:email], contact_no: params[:contact_no])
    if @customer.save
      status = true
    else
      status = false
    end
    render json: status
  end

  def get_customer_by_account
    account_no = params[:account_no]
    group_type = params[:group_type] || 'food_court'

    unless @customer = Customer.find_by(paypar_account_no: account_no)
      response = Customer.search_paypar_account_no(account_no)
      if response["status"] == true
        @customer = 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: account_no,
          membership_id: response["customer_data"]["id"],
          membership_type: response["customer_data"]["member_group_id"],
          customer_type: "Dinein",
          tax_profiles: TaxProfile.where(group_type: group_type).pluck(:id),
          })
      else
        @message = response["message"]
      end
    end
  end

  def get_customer_by_phone
    if @customer = Customer.find_by_contact_no(params[:contact_no])
      status = true
    else
      status = false
    end
    render json: status
  end

  #Show customer detail by Order item
  def get_customer_order
    @customer = Customer.find(params[:id])
  end

  #Show customer last five order
  def get_customer_last_orders
    @sales =Sale.where("sales.customer_id=? and sales.sale_status =?",params[:customer_id],'completed').order("created_at desc").limit(5)
  end
end
