<?php

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

namespace eSM_clients;


/**
 * Class tl_esm_clients
 * Provide miscellaneous methods that are used by the data configuration array.
 */
class tl_esm_clients extends \Backend
{
	/**
	 * Import the back end user object
	 */
	public function __construct()
	{
		parent::__construct();
		$this->import('BackendUser', 'User');
	}

	/**
	 * Return the file picker wizard
	 * @param \DataContainer
	 * @return string
	 */
	public function filePicker(\DataContainer $dc)
	{
		return ' <a href="contao/file.php?do='.\Input::get('do').'&amp;table='.$dc->table.'&amp;field='.$dc->field.'&amp;value='.$dc->value.'" title="'.specialchars(str_replace("'", "\\'", $GLOBALS['TL_LANG']['MSC']['filepicker'])).'" onclick="Backend.getScrollOffset();Backend.openModalSelector({\'width\':768,\'title\':\''.specialchars($GLOBALS['TL_LANG']['MOD']['files'][0]).'\',\'url\':this.href,\'id\':\''.$dc->field.'\',\'tag\':\'ctrl_'.$dc->field . ((\Input::get('act') == 'editAll') ? '_' . $dc->id : '').'\',\'self\':this});return false">' . \Image::getHtml('pickfile.gif', $GLOBALS['TL_LANG']['MSC']['filepicker'], 'style="vertical-align:top;cursor:pointer"') . '</a>';
	}

	/**
	 * Return the "toggle visibility" button
	 * @param array
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @return string
	 */
	public function toggleIcon($row, $href, $label, $title, $icon, $attributes)
	{
		if (strlen(\Input::get('tid')))
		{
			$this->toggleVisibility(\Input::get('tid'), (\Input::get('state') == 1));
			$this->redirect($this->getReferer());
		}

		// Check permissions AFTER checking the tid, so hacking attempts are logged
		if (!$this->User->hasAccess('tl_esm_clients::invisible', 'alexf'))
		{
			return '';
		}

		$href .= '&amp;id='.\Input::get('id').'&amp;tid='.$row['id'].'&amp;state='.$row['invisible'];

		if ($row['invisible'])
		{
			$icon = 'invisible.gif';
		}

		return '<a href="'.$this->addToUrl($href).'" title="'.specialchars($title).'"'.$attributes.'>'.\Image::getHtml($icon, $label).'</a> ';
	}


	/**
	 * Toggle the visibility of an element
	 * @param integer
	 * @param boolean
	 */
	public function toggleVisibility($intId, $blnVisible)
	{
		// Check permissions to edit
		\Input::setGet('id', $intId);
		\Input::setGet('act', 'toggle');

		// The onload_callbacks vary depending on the dynamic parent table (see #4894)
		if (is_array($GLOBALS['TL_DCA']['tl_esm_clients']['config']['onload_callback']))
		{
			foreach ($GLOBALS['TL_DCA']['tl_esm_clients']['config']['onload_callback'] as $callback)
			{
				if (is_array($callback))
				{
					$this->import($callback[0]);
					$this->$callback[0]->$callback[1]($this);
				}
				elseif (is_callable($callback))
				{
					$callback($this);
				}
			}
		}

		// Check permissions to publish
		if (!$this->User->hasAccess('tl_esm_clients::invisible', 'alexf'))
		{
			$this->log('Not enough permissions to show/hide content element ID "'.$intId.'"', __METHOD__, TL_ERROR);
			$this->redirect('contao/main.php?act=error');
		}

		$objVersions = new \Versions('tl_esm_clients', $intId);
		$objVersions->initialize();

		// Trigger the save_callback
		if (is_array($GLOBALS['TL_DCA']['tl_esm_clients']['fields']['invisible']['save_callback']))
		{
			foreach ($GLOBALS['TL_DCA']['tl_esm_clients']['fields']['invisible']['save_callback'] as $callback)
			{
				if (is_array($callback))
				{
					$this->import($callback[0]);
					$blnVisible = $this->$callback[0]->$callback[1]($blnVisible, $this);
				}
				elseif (is_callable($callback))
				{
					$blnVisible = $callback($blnVisible, $this);
				}
			}
		}

		// Update the database
		$this->Database->prepare("UPDATE tl_esm_clients SET tstamp=". time() .", invisible='" . ($blnVisible ? '' : 1) . "' WHERE id=?")
			->execute($intId);

		$objVersions->create();
		$this->log('A new version of record "tl_esm_clients.id='.$intId.'" has been created', __METHOD__, TL_GENERAL);
	}

	public function getBranches(\DataContainer $dc)
	{
		$arrOptions = array();

		$Branches = \EsmClientsSettingsModel::findByType('branch');

		if (!is_null($Branches))
		{
			while($Branches->next())
			{
				$arrOptions[$Branches->id] = $Branches->title;
			}
		}

		return $arrOptions;
	}

	/**
	 * Auto-generate alias if it has not been set yet
	 * @param $varValue
	 * @param \DataContainer $dc
	 * @return string
	 * @throws \Exception
	 * @internal param $mixed
	 * @internal param $ \DataContainer
	 */
	public function generateAlias($varValue, \DataContainer $dc)
	{
		$autoAlias = false;

		// Generate alias if there is none
		if ($varValue == '')
		{
			$autoAlias = true;
			$varValue = standardize(\String::restoreBasicEntities($dc->activeRecord->title));
		}

		$objAlias = $this->Database->prepare("SELECT id FROM tl_esm_clients_projects WHERE alias=?")
			->execute($varValue);

		// Check whether the alias exists
		if ($objAlias->numRows > 1 && !$autoAlias)
		{
			throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $varValue));
		}

		// Add ID to alias
		if ($objAlias->numRows && $autoAlias)
		{
			$varValue .= '-' . $dc->id;
		}

		return $varValue;
	}

	/**
	 * Automatically generate the folder URL aliases
	 * @param array
	 * @param \DataContainer
	 * @return array
	 */
	public function addAliasButton($arrButtons, \DataContainer $dc)
	{
		// Generate the aliases
		if (\Input::post('FORM_SUBMIT') == 'tl_select' && isset($_POST['alias']))
		{
			$session = $this->Session->getData();
			$ids = $session['CURRENT']['IDS'];

			foreach ($ids as $id)
			{
				$objClients = EsmClientsModel::findByPk($id);

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

				$dc->id = $id;
				$dc->activeRecord = $objClients;

				$strAlias = '';

				// Generate new alias through save callbacks
				foreach ($GLOBALS['TL_DCA'][$dc->table]['fields']['alias']['save_callback'] as $callback)
				{
					if (is_array($callback))
					{
						$this->import($callback[0]);
						$strAlias = $this->$callback[0]->$callback[1]($strAlias, $dc);
					}
					elseif (is_callable($callback))
					{
						$strAlias = $callback($strAlias, $dc);
					}
				}

				// The alias has not changed
				if ($strAlias == $objClients->alias)
				{
					continue;
				}

				// Initialize the version manager
				$objVersions = new \Versions($dc->table, $id);
				$objVersions->initialize();

				// Store the new alias
				$this->Database->prepare("UPDATE tl_esm_clients SET alias=? WHERE id=?")
					->execute($strAlias, $id);

				// Create a new version
				$objVersions->create();
			}

			$this->redirect($this->getReferer());
		}

		// Add the button
		$arrButtons['alias'] = '<input type="submit" name="alias" id="alias" class="tl_submit" accesskey="a" value="'.specialchars($GLOBALS['TL_LANG']['MSC']['aliasSelected']).'"> ';

		return $arrButtons;
	}

	public function renderSortingPage()
	{
		// Load Template
		$objTemplate = new \BackendTemplate('be_clientsShowcase_sorting');

		$Clients = EsmClientsModel::getReferenceClients();

		$arrClients = array();
		if (!is_null($Clients))
		{
			while($Clients->next())
			{
				$arrClients[] = array('label'=>$Clients->title, 'value'=>$Clients->id);
			}
		}

		$Sortfield = new \SortWizard(array
		(
			'label'      => &$GLOBALS['TL_LANG']['tl_esm_clients']['sort'][0],
			'name'       => 'sorting',
			'id'       => 'sorting',
			'options'    => $arrClients
		));

		if (\Input::post('FORM_SUBMIT') == 'tl_esm_clients__sorting' && \Input::post('sorting') && is_array(\Input::post('sorting')))
		{
			$Clients = EsmClientsModel::findMultipleByIds(\Input::post('sorting'));

			if (!is_null($Clients))
			{
				$iterator = 1;
				foreach ($Clients as $client)
				{
					$client->sorting = 128 * $iterator++;
					$client->save();
				}
			}

            if (isset($_POST['saveNclose']))
            {
                $this->redirect($this->getReferer());
            }

			$this->reload();
		}


		$objTemplate->fields =  $Sortfield->parse();

		return $objTemplate->parse();
	}
}