<?php

/**
 * Pagelist for Contao
 *
 * Copyright (c) 2015 Benjamin Roth
 *
 * @license LGPL-3.0+
 */

namespace eSM_pagelist;
use \Contao\Module;
/**
 * Class ModulePagelist
 * @package eSM_pagelist
 */
class ModulePagelist extends Module
{

	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'mod_pagelist';


	/**
	 * Do not display the module if there are no menu items
	 * @return string
	 */
	public function generate()
	{
		if (TL_MODE == 'BE')
		{
			$objTemplate = new \BackendTemplate('be_wildcard');

			$objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['pagelist'][0]) . ' ###';
			$objTemplate->title = $this->headline;
			$objTemplate->id = $this->id;
			$objTemplate->link = $this->name;
			$objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;

			return $objTemplate->parse();
		}

		$strBuffer = parent::generate();
		return strlen($this->Template->items) ? $strBuffer : '';
	}


	/**
	 * Generate content element
	 */
	protected function compile()
	{
		global $objPage;

		$intPage = $objPage->id;
		$trail = $objPage->trail;

		// Overwrite with custom reference page
		if ($this->defineRoot && $this->rootPage > 0)
		{
			$trail = array($this->rootPage);
			$intPage = $this->rootPage;
		}
		$level = array_search($intPage, $trail, true);
		
		$this->Template->request = ampersand(\Environment::get('indexFreeRequest'));
		$this->Template->skipId = 'skipNavigation' . $this->id;
		$this->Template->skipNavigation = specialchars($GLOBALS['TL_LANG']['MSC']['skipNavigation']);
		$this->Template->items = $this->getSubpages($trail[$level]);

	}

	/**
	 * Recursively compile the navigation menu and return it as HTML string
	 * @param integer
	 * @param integer
	 * @return string
	 */
	protected function getSubpages($pid, $level=1)
	{
		$time = time();
		
		$offset = 0;
		$limit = null;
		
		
		// Get all active subpages
		
		// Get the total number of items
		$objSubpagesCountStatement = $this->Database->prepare("SELECT COUNT(p1.id) as 'total' FROM tl_page p1 WHERE p1.pid=? AND p1.type!='root' AND p1.type!='error_403' AND p1.type!='error_404' AND p1.hide!=1" . ((FE_USER_LOGGED_IN && !BE_USER_LOGGED_IN) ? " AND p1.guests!=1" : "") . (!BE_USER_LOGGED_IN ? " AND (p1.start='' OR p1.start<".$time.") AND (p1.stop='' OR p1.stop>".$time.") AND p1.published=1" : "") . " ORDER BY p1.sorting");
		$objSubpagesStatement = $this->Database->prepare("SELECT p1.* FROM tl_page p1 WHERE p1.pid=? AND p1.type!='root' AND p1.type!='error_403' AND p1.type!='error_404' AND p1.hide!=1" . ((FE_USER_LOGGED_IN && !BE_USER_LOGGED_IN) ? " AND p1.guests!=1" : "") . (!BE_USER_LOGGED_IN ? " AND (p1.start='' OR p1.start<".$time.") AND (p1.stop='' OR p1.stop>".$time.") AND p1.published=1" : "") . " ORDER BY p1.sorting");

		$objTotal = $objSubpagesCountStatement->execute($pid);
		$total = $objTotal->total;
		
		// Split the results
		if ($this->perPage > 0 && !isset($limit))
		{
			// Adjust the overall limit
			if (isset($limit))
			{
				$total = min($limit, $total);
			}

			$page = $this->Input->get('page') ? $this->Input->get('page') : 1;

			// Check the maximum page number
			if ($page > ($total/$this->perPage))
			{
				$page = ceil($total/$this->perPage);
			}

			// Limit and offset
			$limit = $this->perPage;
			$offset = (max($page, 1) - 1) * $this->perPage;

			// Overall limit
			if ($offset + $limit > $total)
			{
				$limit = $total - $offset;
			}

			// Add the pagination menu
			$objPagination = new \Pagination($total, $this->perPage);
			$this->Template->pagination = $objPagination->generate("\n  ");
		}

		// Limit the result
		if (isset($limit))
		{
			$objSubpagesStatement = $objSubpagesStatement->limit($limit, $offset);
		}
		
		$objSubpages = $objSubpagesStatement->execute($pid);

		if ($objSubpages->numRows < 1)
		{
			return '';
		}
		
		$items = array();
		$groups = array();

		// Get all groups of the current front end user
		if (FE_USER_LOGGED_IN)
		{
			$this->import('FrontendUser', 'User');
			$groups = $this->User->groups;
		}

		// Layout template fallback
		if (!strlen($this->eSM_pagelist_template))
		{
			$this->esTemplate = 'espl_default';
		}

		$objTemplate = new \FrontendTemplate($this->eSM_pagelist_template);

		$objTemplate->type = get_class($this);
		$objTemplate->level = 'level_' . $level++;

		// Get page object
		global $objPage;

		// Browse subpages
		while($objSubpages->next())
		{

			if ($objSubpages->type == 'redirect' || $objSubpages->type == 'forward')
			{
				continue;
			}
			

			$subitems = '';
			$_groups = deserialize($objSubpages->groups);

			// Do not show protected pages unless a back end or front end user is logged in
			if (!$objSubpages->protected || BE_USER_LOGGED_IN || (is_array($_groups) && count(array_intersect($_groups, $groups))) || $this->showProtected)
			{

				// Get href
				$href = $this->generateFrontendUrl($objSubpages->row());
				
				$objArticle = $this->Database->prepare("SELECT a.id AS aid, a.title AS title, a.alias AS aalias, a.teaser AS teaser, a.teaserSRC AS teaserSRC, a.teaserSize AS teaserSize, a.inColumn AS inColumn, a.teaserCssID AS teaserCssID FROM tl_article a WHERE a.pid=? AND inColumn = 'main' ORDER BY sorting")
				->limit(1)
				->execute($objSubpages->id);

				if ($objArticle->numRows < 1)
				{
					continue;
				}
				
				$objContent = $this->Database->execute("SELECT count(id) as `count` FROM tl_content WHERE pid = '".$objArticle->aid."'");
				
				$row = $objSubpages->row();

				// Add an image
				if ($this->showTeaserImg && $objArticle->teaserSRC != '')
				{
					$arrData = array();
					$objClass = new \stdClass();
					$objModel = \FilesModel::findByUuid($objArticle->teaserSRC);

					// Override the default image size
					if ($this->imgSize != '')
					{
						$size = deserialize($this->imgSize);

						if ($size[0] > 0 || $size[1] > 0)
						{
							$arrData['size'] = $this->imgSize;
						}
					} else {
						$arrData['size'] = $objArticle->teaserSize;
					}

					if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path))
					{
						$arrData['singleSRC'] = $objModel->path;
						$arrData['alt'] = specialchars($objSubpages->title);
						$this->addImageToTemplate($objClass, $arrData);
						$row['picture'] = $objClass;
					}

				}

				$row['isActive'] = ($objPage->id == $objSubpages->id ? true : false);
				$row['subitems'] = (bool) $subitems;
				list($row['cssId'], $row['class']) = (deserialize($objArticle->teaserCssID));
				$row['title'] = $objSubpages->title;
				$row['pageTitle'] = $objSubpages->pageTitle;
				$row['href'] = $href;

				$row['headline'] = $objArticle->title;
				$row['text'] = $objArticle->teaser;
				if ($objContent->count > 0)
				{
					$row['readMore'] = specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['readMore'], $objArticle->title));
					$row['more'] = $GLOBALS['TL_LANG']['MSC']['more'];
				}

				$items[] = $row;
			}
		}

		// Add classes first and last
		if (count($items))
		{
			$last = count($items) - 1;

			$items[0]['class'] = trim($items[0]['class'] . ' first');
			$items[$last]['class'] = trim($items[$last]['class'] . ' last');
		}

		$objTemplate->items = $items;
		return count($items) ? $objTemplate->parse() : '';
	}


}