<?php
/*
 * Copyright (c) 2012, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class sly_Controller_Realurl2dbg extends sly_Controller_System {
	private $i = 1;

	protected function getViewFolder() {
		return _WV24_DBG_PATH.'views/';
	}

	public function indexAction() {
		$this->init();

		if (!WV24_Util::hasSiteStartArticle()) {
			print sly_Helper_Message::warn('realURL2 hat keine URLs erzeugt, da der Homepage-Artikel (noch) nicht korrekt eingestellt wurde.');
			return;
		}

		$rootArts = sly_Util_Article::getRootArticles();
		$rootCats = sly_Util_Category::getRootCategories();
		$children = array_merge($rootCats, $rootArts);

		if (empty($children)) {
			print sly_Helper_Message::info('Es wurden noch keine Inhalte angelegt.');
			return;
		}

		$tree = $this->tree($children);
		$this->render('../../../../../backend/views/toolbars/languages.phtml', array('params' => array('page' => 'realurl2dbg')), false);
		$this->render('tree.phtml', compact('tree'), false);
	}

	protected function tree($children, $level = 1) {
		$ul = '';

		if (is_array($children)) {
			$len = count($children);
			$li  = '';

			foreach ($children as $idx => $cat) {
				$isArticle   = $cat instanceof sly_Model_Article;
				$art         = $isArticle ? $cat : $cat->getStartArticle();
				$catChildren = $isArticle ? array() : $cat->getChildren();
				$cat_id      = $cat->getId();
				$classes     = array('lvl-'.$level, 'active');
				$liClasses   = array('lvl-'.$level, $this->i % 2 ? 'odd' : 'even');

				++$this->i;

				$sub_li = $this->tree($catChildren, $level + 1);

				if ($idx === 0) {
					$classes[] = 'first';
				}

				if ($idx === $len-1) {
					$classes[] = 'last';
				}

				if ($art->getFragment() !== '') {
					$classes[] = 'fragment';
				}

				if ($art->isSkipped()) {
					$classes[] = 'skipped';
				}

				if ($catChildren) {
					$classes[] = 'children';
				}
				else {
					$classes[]   = 'empty';
					$liClasses[] = 'empty';
				}

				$classes[] = $cat->isOnline() ? 'sly-online' : 'sly-offline';
				$classes   = ' class="'.implode(' ', $classes).'"';
				$label     = $isArticle ? $cat->getName() : $cat->getCatname();
				$url       = WV24_RealURL2::getURL($cat->getId(), $cat->getClang(), array(), '', true);

				$li .= '<li class="'.implode(' ', $liClasses).'">';
				$li .= '<span'.$classes.'>'.sly_html($label).'</span> <span class="wrapper"><a href="'.$url.'" class="sly-blank">'.sly_html($url).'</a></span>';
				$li .= $sub_li;
				$li .= '</li>';
			}

			if (!empty($li)) {
				$ul = "<ul>$li</ul>";
			}
		}

		return $ul;
	}
}
