<?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';

  /**
   * Layout template
   * @var string
   */
  protected $strItemsTemplate = 'espl_default';

	/**
	 * 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;
		}

		// Custom layout template
		if (strlen($this->eSM_pagelist_template))
		{
			$this->strItemsTemplate = $this->eSM_pagelist_template;
		}

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

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

		// 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());
				
				$row = $objSubpages->row();

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

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

						if ($size[0] > 0 || $size[1] > 0 || is_numeric($size[2]))
						{
							$arrData['size'] = $this->imgSize;
              $objTemplate->imgSize = deserialize($this->imgSize);
						}
					} else {
						$arrData['size'] = $objSubpages->teaserSize;
            $objTemplate->imgSize = deserialize($objSubpages->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($objSubpages->teaserCssID));
				$row['title'] = $objSubpages->title;
				$row['pageTitle'] = $objSubpages->pageTitle;
				$row['href'] = $href;

				$row['headline'] = $objSubpages->title;
				$row['text'] = $objSubpages->teaser;
        $row['readMore'] = specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['gotoPage'], $objSubpages->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() : '';
	}


}