<?php

class PageHelper {
  /**
   * Stores the reference to the Page Helper
   */
  public static $_instance = null;

  public static function getInstance()
  {
    if (is_null(self::$_instance)) {
      self::$_instance = new self();
    }

    return self::$_instance;
  }

  /**
  * Return the highest parent of a page, or itself if it has no parents
  * @param  int $id the id of the page we're looking for the hightest parent of
  * @return Post     A post object of the highest parent
  */
  public function getTopParent($id)
  {
    $parents = array_reverse(get_post_ancestors($id));

    return ($parents) ? get_page($parents[0]) : get_page($id);
  }

  /**
   * Return the name of a page by slug
   * @param  String $slug 
   * @return String       [name of the page]
   */
  public function getMenuName($slug) 
  {
    global $wpdb;

    $prefix = $wpdb -> get_prefix();

    $query = "SELECT a.name FROM {$prefix}terms as a JOIN {$prefix}term_taxonomy as b on a.term_id = b.term_id WHERE a.slug = '$slug' AND b.taxonomy='nav_menu' ";
    return $wpdb->get_var($query);
  }

  /** 
   * Returns the page ID based on the slug of the page
   * @param String $slug - the slug of the required page
  *  @return int - The ID of the page or 0 if not found. Note that 0 will be coerced to FALSE
  */
   public function getPageIDBySlug($pageSlug)
   {
    $page = get_page_by_path($pageSlug);

    return ($page) ? $page -> ID : 0;
   }

  /**
   * Returns the current Page URL
   * @return String - The URL you're on
   */
  public function getCurrentPageUrl()
  {
    $pageUrl = ("on" == $_SERVER["HTTPS"]) ? 'http://' : 'https://';
    if(80 != $_SERVER["PORT"]) {
      $pageUrl .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    } else {
      $pageUrl .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }

    return $pageUrl;
  }

  /**
   * Check if a page has children
   * @param postId - The page we're checking
   * @param postType - The type of post we're checking again
   * @return int - Coerced to Boolean
   */
  public function pageHasChildren($postID, $postType) {
    global $wpdb;

    $query = "SELECT COUNT(id) from {$prefix}post WHERE post_type='$postType' AND post_parent='$postID'";
    $children = $wpdb -> get_var($query);

    return ($children);
  }

}