<?php
namespace Tanzsport;

use Contao\StringUtil;
use Contao\Widget;

\System::loadLanguageFile('nameEmailWidget');

class NameEmailWidget extends Widget
{

	/**
	 * Submit user input
	 * @var boolean
	 */
	protected $blnSubmitInput = true;

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

	public function generate()
	{
		$GLOBALS['TL_JAVASCRIPT'][] = "bundles/contaoformationen/js/widgets/tdNameEmailWidget.js";

		$arrButtons = array('copy', 'delete', 'drag', 'up', 'down');
		$strCommand = 'cmd_' . $this->strField;

		// Change the order
		if (\Input::get($strCommand) && is_numeric(\Input::get('cid')) && \Input::get('id') == $this->currentRecord) {
			switch (\Input::get($strCommand)) {
				case 'copy':
					if (is_array($this->varValue)) {
						$this->varValue[] = $this->getDefaultEntry();
					} else {
						$this->varValue = array($this->getDefaultEntry());
					}
					break;

				case 'up':
					$this->varValue = array_move_up($this->varValue, \Input::get('cid'));
					break;

				case 'down':
					$this->varValue = array_move_down($this->varValue, \Input::get('cid'));
					break;

				case 'delete':
					$this->varValue = array_delete($this->varValue, \Input::get('cid'));
					break;
			}
		}

		// Get the new value
		if (\Input::post('FORM_SUBMIT') == $this->strTable) {
			$this->varValue = \Input::post($this->strId);
		}

		// Make sure there is at least an empty array
		if (!is_array($this->varValue) || !$this->varValue[0]) {
			$this->varValue = array($this->getDefaultEntry());
		}

		// Initialize the tab index
		if (!\Cache::has('tabindex')) {
			\Cache::set('tabindex', 1);
		}

		$tabindex = \Cache::get('tabindex');

		$return = '<table id="ctrl_' . $this->strId . '" class="tl_nameEmailWidget" style="width:100%">
  <thead>
  <tr>
    <th>' . $GLOBALS['TL_LANG']['tl_nameEmailWidget']['name'] . '</th>
    <th>' . $GLOBALS['TL_LANG']['tl_nameEmailWidget']['email'] . '</th>
    <th>&nbsp;</th>
  </tr>
  </thead>
  <tbody class="sortable" data-tabindex="' . $tabindex . '">';

		for ($i = 0, $c = count($this->varValue); $i < $c; $i++) {

			$return .= '
  <tr>
    <td style="width:33%;"><input type="text" style="width:95%" tabindex="'. $tabindex++ .'" name="' . $this->strId . '[' . $i . '][name]" class="tl_text" tabindex="' . $tabindex++ . '" onfocus="Backend.getScrollOffset()" value="' . $this->varValue[$i]["name"] . '" /></td>';

			$return .= '
    <td style="width:33%"><input type="text" style="width:95%" tabindex="'. $tabindex++ .'"name="' . $this->strId . '[' . $i . '][email]" class="tl_text" tabindex="' . $tabindex++ . '" onfocus="Backend.getScrollOffset()" value="' . $this->varValue[$i]["email"] . '" /></td>
    <td style="width:34%">';

			// Add buttons
			foreach ($arrButtons as $button) {
				$class = ($button == 'up' || $button == 'down') ? ' class="button-move"' : '';

				if ($button == 'drag') {
					$return .= ' ' . \Image::getHtml('drag.gif', '', 'class="drag-handle" title="' . sprintf($GLOBALS['TL_LANG']['MSC']['move']) . '"');
				} else {
					$return .= ' <a href="' . $this->addToUrl('&amp;' . $strCommand . '=' . $button . '&amp;cid=' . $i . '&amp;id=' . $this->currentRecord) . '"' . $class . ' title="' . specialchars($GLOBALS['TL_LANG']['MSC']['mw_' . $button]) . '" onclick="NameEmailWidget.doCommand(this,\'' . $button . '\',\'ctrl_' . $this->strId . '\');return false">' . \Image::getHtml($button . '.gif', $GLOBALS['TL_LANG']['MSC']['mw_' . $button], 'class="tl_listwizard_img"') . '</a>';
				}
			}

			$return .= '</td></tr>';
		}
		return $return . '
  </tbody>
  </table>';
	}

	private function getDefaultEntry()
	{
		return array('name' => '', 'email' => '');
	}

	public static function saveCallback($value, \DataContainer $dc)
	{
		$arrValue = StringUtil::deserialize($value, true);
		$remove = array();
		foreach ($arrValue as $i => $arrEntry) {
			$empty = true;
			if (isset($arrEntry["name"]) && $arrEntry["name"]) {
				$empty = false;
			}
			if ($empty) {
				$remove[] = $i;
			}
		}
		foreach ($remove as $r) {
			unset($arrValue[$r]);
		}
		return serialize(array_values($arrValue));
	}

}
