<?php

namespace Modules\Admin\Config\CustomerCollectionProfiles;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing
{

	/**
	 * The list of columns which support ordering.
	 * @var array
	 */
	protected $listOrderingColumns = [];

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['insert']			= [ 'checkSection' => true, 'checkOption' => false ];
		$this->actionsCfg['update']			= [ 'checkSection' => true, 'checkOption' => false ];
		$this->actionsCfg['delete']			= [ 'checkSection' => true, 'checkOption' => false ];
		$this->actionsCfg['save']			= [ 'checkSection' => true, 'checkOption' => false ];
		$this->actionsCfg['reset']			= [ 'checkSection' => true, 'checkOption' => false ];
	}

	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		$cfgAdmin = \App\Config\CustomerCollectionProfiles::getAdmin();
		switch($option->getId()){
			case 'update': case 'insert':
			break;

			case 'save':
			case 'reset':
			if (!$cfgAdmin->getChangedFlag()) {
				$option->setDisabled();
			}
			break;

			case 'delete':
				$selectedItem = reset($selection);
				if($cfgAdmin->getDefaultItem()==$selectedItem) {
					$option->setDisabled();
					$option->addMessage('info', $this->lang['index']['options']['reasons']['delete']['cannotDeleteDefault']);
				}
				break;

			default:
				return false;
		}

		return true;
	}


	/**
	 * Does the actual "insert" operation upon form submit.
	 */
	protected function insert_doInsert($formData, \App\MessagesCollector $msgs)
	{
		$cfgAdmin = \App\Config\CustomerCollectionProfiles::getAdmin();

		$profileDetails = [
			'name'					=> $formData['name'],
			'recipientToAuto'		=> $formData['recipientToAuto'],
			'recipientToManual'		=> array_map( 'trim', explodeClean(';', $formData['recipientToManual']) ),
			'recipientBccManual'	=> array_map( 'trim', explodeClean(';', $formData['recipientBccManual']) ),
			'emailSubject'			=> $formData['emailSubject'],
			'emailBody'				=> $formData['emailBody'],
			'dueInDaysPeriod'		=> $formData['dueInDaysPeriod'],
		];

		$idProfile = uniqid();
		try {

			$cfgAdmin->itemInsert($idProfile, $profileDetails);
			// show success message
			$msgs->addSuccess($this->lang['insert']['successMessage']);
			$this->insertIdRecord = $idProfile;
			return true;

		}
		catch (\App\Config\MessageException $e) {
			// show error message
			$msgs->addWarning(sprintf($this->lang['insert']['errorMessage'], $e->getMessage()));
			return false;
		}
	}


	/**
	 * Returns an array of default values for "update" form
	 * @return Array
	 */
	protected function update_getDefaultFormData($id)
	{
		$profile = \App\Config\CustomerCollectionProfiles::getAdmin()->get($id);

		$formData['id'] = $id;
		$formData['name']				= $profile['name'];
 		$formData['recipientToAuto']	= $profile['recipientToAuto'];
 		$formData['recipientToManual']	= implode('; ', (array)$profile['recipientToManual']);
 		$formData['recipientBccManual']	= implode('; ', (array)$profile['recipientBccManual']);
		$formData['emailSubject']		= $profile['emailSubject'];
		$formData['emailBody']			= $profile['emailBody'];
		$formData['dueInDaysPeriod']	= $profile['dueInDaysPeriod'];
		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::update_createEntityObject()
	 */
	protected function update_doUpdate($formData, \App\MessagesCollector $msgs)
	{

		$cfgAdmin = \App\Config\CustomerCollectionProfiles::getAdmin();

		$profileDetails = [
			'name'					=> $formData['name'],
			'recipientToAuto'		=> $formData['recipientToAuto'],
			'recipientToManual'		=> array_map( 'trim', explodeClean(';', $formData['recipientToManual']) ),
			'recipientBccManual'	=> array_map( 'trim', explodeClean(';', $formData['recipientBccManual']) ),
			'emailSubject'			=> $formData['emailSubject'],
			'emailBody'				=> $formData['emailBody'],
			'dueInDaysPeriod'		=> $formData['dueInDaysPeriod'],
		];

		try {

			$cfgAdmin->itemUpdate($formData['id'], $profileDetails);
			$msgs->addSuccess($this->lang['update']['successMessage']);
			return true;

		}
		catch (\App\Config\MessageException $e) {
			// show error message
			$msgs->addWarning(sprintf($this->lang['update']['errorMessage'], $e->getMessage()));
			return false;
		}
	}


	/**
	 * Save the changes
	 * @param array $R
	 */
	protected function actionSave($R)
	{

		$msgs = \App\MessagesCollector::create();

		try {
			\App\Config\CustomerCollectionProfiles::getAdmin()->save();
			$msgs->addSuccess($this->lang['save']['successMessage']);
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addWarning($e->getMessage());
		}

		$R['listing']['options'] = [
			'render' => 'json',
			'section' => [ 'bulk', 'global', ],
		];
		$response = $this->actionListRecords($R);
		$response->headers->loadMessages($msgs);

		return $response;
	}


	/**
	 * Reset settings to original state
	 * @param array $R
	 */
	protected function actionReset($R)
	{
		$msgs = \App\MessagesCollector::create();

		$cfgAdmin = \App\Config\CustomerCollectionProfiles::getAdmin();

		try {
			$cfgAdmin->reset();
			$msgs->addSuccess($this->lang['reset']['successMessage']);
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addWarning($e->getMessage());
		}

		$R['listing']['options'] = [
			'render' => 'json',
			'section' => [ 'bulk', 'global', ],
		];
		$response = $this->actionListRecords($R);
		$response->headers->loadMessages($msgs);

		return $response;
	}


	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::delete_doDelete()
	 */
	protected function delete_doDelete(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{

		foreach ($recordsIds as $record) {
			try {
				\App\Config\CustomerCollectionProfiles::getAdmin()->itemDelete($record);
				// remove this record from the internal list
				$this->getListingSelection()->delete([$record]);
				$msgs->addSuccess($this->lang['delete']['successMessage']);
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addWarning($e->getMessage());
			}
		}

	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		return \App\Config\CustomerCollectionProfiles::getAdmin()->get($id)['name'];
	}

}