<?php

/**
 * Clients for Contao
 *
 * Copyright (c) 2014 Benjamin Roth [http://www.esales-media.de]
 *
 * @package eSM_clients
 * @link    http://www.esales-media.de
 * @license commercial
*/


/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace eSM_clients;


/**
 * Shows a list of clients which have active projects
 *
 * @package   Modules
 * @author    Benjamin Roth <http://www.esales-media.de>
 * @copyright eSales Media 2014
 */
class ModuleClientsProject extends \Module
{
	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'mod_clientsProject';

	protected $objProject = null;


	public function generate()
	{
		if (TL_MODE == 'BE')
		{
			$objTemplate = new \BackendTemplate('be_wildcard');

			$objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['clientsProject'][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();
		}

		// Set the item from the auto_item parameter
		if (!isset($_GET['items']) && \Config::get('useAutoItem') && isset($_GET['auto_item']))
		{
			\Input::setGet('items', \Input::get('auto_item'));
		}

		$this->objProject = EsmClientsProjectsModel::findByIdOrAlias($_GET['items']);

		if ($this->objProject === null)
		{
			global $objPage;
			$objHandler = new $GLOBALS['TL_PTY']['error_404']();
			$objHandler->generate($objPage->id);
		}

		return parent::generate();
	}

	/**
	 * Compile the current element
	 */
	protected function compile()
	{
		global $objPage;

		$Client = $this->objProject->getRelated('pid');

		// Get the previous and next project
		$subSql = "SELECT ri.*, @row_num := @row_num+1 AS RN FROM (SELECT p.id, p.alias, p.title, c.title as 'client', p.sorting FROM tl_esm_clients c, tl_esm_clients_projects p WHERE p.pid=c.id ORDER BY c.sorting, p.sorting) ri, (SELECT @row_num := 0) r";
		$Current = \Database::getInstance()->prepare("SELECT sq.RN FROM (".$subSql.") sq WHERE sq.id = ?")->execute($this->objProject->id);

		if ($Current->numRows)
		{
			// Get previous
			$Previous = \Database::getInstance()->prepare("SELECT sq.id, sq.alias, sq.title, sq.client FROM (".$subSql.") sq WHERE sq.RN = ?")->execute($Current->RN-1);

			// Get next
			$Next = \Database::getInstance()->prepare("SELECT sq.id, sq.alias, sq.title, sq.client FROM (".$subSql.") sq WHERE sq.RN = ?")->execute($Current->RN+1);

			// Set projects nav vars
			$strJumpTo = ampersand($this->generateFrontendUrl($objPage->row(), ((\Config::get('useAutoItem') && !\Config::get('disableAlias')) ?  '/%s' : '/items/%s')));

			if ($Previous->numRows)
			{
				$this->Template->prevProject = array_merge($Previous->row(),array('link'=>sprintf($strJumpTo,(!\Config::get('disableAlias') && $Previous->alias != '') ? $Previous->alias : $Previous->id)));
			}

			if ($Next->numRows)
			{
				$this->Template->nextProject = array_merge($Next->row(),array('link'=>sprintf($strJumpTo,(!\Config::get('disableAlias') && $Next->alias != '') ? $Next->alias : $Next->id)));
			}
		}


		// Get the file entries from the database
		$objFiles = \FilesModel::findMultipleByUuids(deserialize($this->objProject->gallerySRC,true));

		// Get all images
		$images = array();
		$auxDate = array();

		if (!is_null($objFiles))
		{
			while ($objFiles->next())
			{
				// Continue if the files has been processed or does not exist
				if (isset($images[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path))
				{
					continue;
				}

				// Single files
				if ($objFiles->type == 'file')
				{
					$objFile = new \File($objFiles->path, true);

					if (!$objFile->isImage)
					{
						continue;
					}

					$arrMeta = $this->getMetaData($objFiles->meta, $objPage->language);

					if (empty($arrMeta))
					{
						$arrMeta = $this->getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
					}

					// Use the file name as title if none is given
					if ($arrMeta['title'] == '')
					{
						$arrMeta['title'] = specialchars($objFile->basename);
					}

					// Add the image
					$images[$objFiles->path] = array
					(
						'id' => $objFiles->id,
						'uuid' => $objFiles->uuid,
						'name' => $objFile->basename,
						'singleSRC' => $objFiles->path,
						'alt' => $arrMeta['title'],
						'imageUrl' => $arrMeta['link'],
						'caption' => $arrMeta['caption'],
						'size' => $this->imgSize,
						'fullsize' => $this->fullsize
					);

					$auxDate[] = $objFile->mtime;
				} // Folders
				else
				{
					$objSubfiles = \FilesModel::findByPid($objFiles->uuid);

					if ($objSubfiles === null)
					{
						continue;
					}

					while ($objSubfiles->next())
					{
						// Skip subfolders
						if ($objSubfiles->type == 'folder')
						{
							continue;
						}

						$objFile = new \File($objSubfiles->path, true);

						if (!$objFile->isImage)
						{
							continue;
						}

						$arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->language);

						if (empty($arrMeta))
						{
							$arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->rootFallbackLanguage);
						}

						// Use the file name as title if none is given
						if ($arrMeta['title'] == '')
						{
							$arrMeta['title'] = specialchars($objFile->basename);
						}

						// Add the image
						$images[$objSubfiles->path] = array
						(
							'id' => $objSubfiles->id,
							'uuid' => $objSubfiles->uuid,
							'name' => $objFile->basename,
							'singleSRC' => $objSubfiles->path,
							'alt' => $arrMeta['title'],
							'imageUrl' => $arrMeta['link'],
							'caption' => $arrMeta['caption'],
							'size' => $this->imgSize,
							'fullsize' => $this->fullsize
						);

						$auxDate[] = $objFile->mtime;
					}
				}
			}

			if ($this->objProject->galleryOrder != '')
			{
				$tmp = deserialize($this->objProject->galleryOrder);

				if (!empty($tmp) && is_array($tmp))
				{
					// Remove all values
					$arrOrder = array_map(function ()
					{
					}, array_flip($tmp));

					// Move the matching elements to their position in $arrOrder
					foreach ($images as $k => $v)
					{
						if (array_key_exists($v['uuid'], $arrOrder))
						{
							$arrOrder[$v['uuid']] = $v;
							unset($images[$k]);
						}
					}

					// Append the left-over images at the end
					if (!empty($images))
					{
						$arrOrder = array_merge($arrOrder, array_values($images));
					}

					// Remove empty (unreplaced) entries
					$images = array_values(array_filter($arrOrder));
					unset($arrOrder);
				}
			}
			$images = array_values($images);
		}

		// Add images to Template
		$arrImages = array();
		foreach ($images as $image)
		{
			$objImage = new \stdClass();
			$this->addImageToTemplate($objImage, $image, null, 'lightbox[lb' . $this->id . ']');

			$arrImages[] = $objImage;
		}
		$this->Template->screenshots = $arrImages;

		// Set header vars
		$this->Template->client_title = $Client->title;
		$this->Template->title = $this->objProject->title;

		// Set client summary
		$this->Template->client_summary = $Client->text;

		// Set project summary vars
		$this->Template->text = $this->objProject->text;
		$this->Template->link = $this->objProject->projectUrl;
		$this->Template->services = $this->getOptions(explode(',',$this->objProject->services));
		$this->Template->features = deserialize($this->objProject->features,true);
		$this->Template->techs = $this->getOptions(explode(',',$this->objProject->tech));

	}

	protected function getOptions(array $values)
	{
		$arrOptions = array();

		$Types = \EsmClientsSettingsModel::findMultipleByIds($values);

		if (!is_null($Types))
		{
			while($Types->next())
			{
				$arrOptions[] = array('title'=>$Types->title,'url'=>$Types->url);
			}
		}

		return $arrOptions;
	}


}