<?php
class links_ranking
{
	var $mydirname;
	var $controller_name;
	var $Links;

	/** Constructor
	 *
	**/
	function __construct($mydirname)
	{
		$this->mydirname = $mydirname;
		$this->controller_name = str_replace('links_', '', get_class($this));
		$this->Links = links_Base::getInstance($this->mydirname);
		$this->Links->setControllerName($this->controller_name);
		$this->Links->breadcrumbs();
	}

	function index($cid = 0, $per_page = 10)
	{
		$this->hits($cid, $per_page);
	}

	function hits($cid = 0, $per_page = 10)
	{
		$this->_render($cid, $per_page, 'hits');
	}

	function rating($cid = 0, $per_page = 10)
	{
		$this->_render($cid, $per_page, 'rating');
	}

	function access($cid = 0, $per_page = 10)
	{
		$this->_render($cid, $per_page, 'access');
	}

	function _render($cid = 0, $per_page = 10, $h_r_a = 'access')
	{
		$per_page = intval($per_page/10) * 10;
		if ($per_page > 100) $per_page = 100;
		if ($per_page < 10) $per_page = 10;

		if (! in_array($h_r_a, array('hits', 'rating', 'access'))) {
			$h_r_a = 'access';//TODO
		}

		if ($cid > 0 && empty($this->Links->allcid[$cid])) {
			$this->Links->linksRedirectHeader($this->Links->makeUrl('ranking', $h_r_a, array()), 2, _MD_NO_CATEGORY);
			exit();
		}

		$this->Links->clearWhere();
		if ($cid > 0) $this->Links->setWhere('cid', "%[$cid]%", 'LIKE');
		if ($h_r_a == 'rating') {
			$this->Links->setWhere('l.votes', 0, '>');
		} else {
			$this->Links->setWhere('l.'. $h_r_a, 0, '>');// larger than 0
		}
		$this->Links->setWhere('l.status', 0, '>');
		$this->Links->setWhere('l.date', time(), '<');
		$add_order = ($h_r_a == 'rating') ? ', votes DESC': '';
		$this->Links->setOrder('l.'. $h_r_a .' DESC'. $add_order) ;
		$links = $this->Links->getDatas($per_page) ;

		$bread = $this->Links->getBreadcrumbs();
		$lang_arr = array('hits' => _MD_POPULAR, 'rating' => _MD_TOPRATED, 'access' => _MD_TOP_ACCESS);
		$bread[] = array('name' => $lang_arr[$h_r_a]);

		$title_arr = array('hits' => _MD_RANKING_HITS_TOP, 'rating' => _MD_RANKING_RATE_TOP, 'access' => _MD_RANKING_ACCESS_TOP);
		$title = $title_arr[$h_r_a] . $per_page;
		if ($cid > 0 && !empty($this->Links->allcid[$cid])) {
			$title .= '&nbsp;['. _MD_CATEGORY .' : '. $this->Links->allcid[$cid] .']';
		}

		$categories = $this->Links->Categories->getCategories($cid);

		$data = array(
			'links'              => $links,
			'categories'         => $categories,
			'category_id'        => $cid,
			'ranking_title'      => $title,
			'c_tree_controller'  => 'ranking',
			'c_tree_method'      => $h_r_a,
			'xoops_breadcrumbs'  => $bread,
			'xoops_pagetitle'    => $this->Links->module_name .' : '. $title,
		);

		$template = $this->Links->getTemplatePrefix() . '_ranking.html';
		$this->Links->view($template, $data);
	}



}
