<?php

namespace Modules\Admin\Config\SupplierInvoicesPayments\DocsList;

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

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

	/**
	 *
	 * {@inheritDoc}
	 * @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['moveUp'] 		= [ 'checkSection' => true, 'checkOption' => false ];
		$this->actionsCfg['moveDown'] 		= [ '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)
	{
		switch ($option->getId()) {
			case 'insert': case 'update': {
				break;
			}

			case 'save': case 'reset': {
				if (!\App\Config\PaymentDocuments::getAdmin()->getChangedFlag()) {
					$option->setDisabled();
				}
				break;
			}

			case 'delete': {
				$existingDocs = \App\Config\PaymentDocuments::getInstance()->getAll();
				if (array_intersect(array_keys($existingDocs), $selection)) {
					$option->setDisabled();
					$option->addMessage('info', $this->lang['delete']['cannotDeletePrevDoc']);
				}
				break;
			}


			case 'moveUp': {
				$docTypes = \App\Config\PaymentDocuments::getAdmin()->getAll();
				reset($docTypes);
				$firstElement = key($docTypes);
				if (in_array($firstElement, $selection)) {
					$option->setDisabled(true);
				}
				break;
			}

			case 'moveDown': {
				$docTypes = \App\Config\PaymentDocuments::getAdmin()->getAll();
				end($docTypes);
				$lastElement = key($docTypes);
				if (in_array($lastElement, $selection)) {
					$option->setDisabled(true);
				}
				break;
			}

			default:
				return false;
		}

		return true;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::insert_getDefaultFormData()
	 */
	protected function insert_getDefaultFormData($R)
	{
		return [];
	}


	/**
	 * Does the actual "insert" operation upon form submit.
	 */
	protected function insert_doInsert($formData, \App\MessagesCollector $msgs)
	{

		$docsCfgAdmin = \App\Config\PaymentDocuments::getAdmin();

		// determine sign
		if (!$formData['sign']) {
			$sign = 'invalid';
		} elseif ($formData['sign']==2) {
			 $sign = 0;
		} else {
			$sign = $formData['sign'];
		}

		$docDetails = [
			'name'					=> $formData['name'],
			'active'				=> $formData['active'],
			'number'				=> $formData['number'],
			'sign'					=> $sign,
			'bankAccount'			=> $formData['bankAccount'],
			'explanations'			=> $formData['explanations'],
			'comments'				=> $formData['comments'],
		];

		try {
			$docsCfgAdmin->itemInsert($formData['id'], $docDetails);
			$msgs->addSuccess($this->lang['insert']['successMessage']);
			$this->insertIdRecord = $formData['id'];
			return true;
		}
		catch (\App\Config\MessageException $e) {
			$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)
	{
		$docDetails = \App\Config\PaymentDocuments::getAdmin()->get($id);

		$formData['id']						= $id;
		$formData['name']					= $docDetails['name'];
		$formData['active']					= $docDetails['active'];
		$formData['number']					= $docDetails['number'];
		$formData['sign']					= $docDetails['sign']?:2;
		$formData['bankAccount']			= $docDetails['bankAccount'];
		$formData['explanations']			= $docDetails['explanations'];
		$formData['comments']				= $docDetails['comments'];

		return $formData;
	}

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

		$docsCfgAdmin = \App\Config\PaymentDocuments::getAdmin();

		// determine sign
		if (!$formData['sign']) {
			$sign = 'invalid';
		} elseif ($formData['sign']==2) {
			 $sign = 0;
		} else {
			$sign = $formData['sign'];
		}

		$docDetails = [
			'name'					=> $formData['name'],
			'active'				=> $formData['active'],
			'number'				=> $formData['number'],
			'sign'					=> $sign,
			'bankAccount'			=> $formData['bankAccount'],
			'explanations'			=> $formData['explanations'],
			'comments'				=> $formData['comments'],
		];

		try {

			$docsCfgAdmin->itemUpdate($formData['id'], $docDetails);
			// show success message
			$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;

		}

	}

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

		foreach ($recordsIds as $docCode) {

			try {

				$mngDocsCfg->itemDelete($docCode);
				// remove this record from the internal list
				$this->getListingSelection()->delete([$docCode]);
				$msgs->addSuccess($this->lang['delete']['successMessage']);

			}
			catch (\App\Config\MessageException $e) {

				$msgs->addError($e->getMessage());

			}
		}

	}


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

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

		$mngDocsCfg = \App\Config\PaymentDocuments::getAdmin();
		try {

			$mngDocsCfg->save();
			$msgs->addSuccess($this->lang['save']['successMessage']);

		}
		catch (\App\Config\MessageException $e) {

			$msgs->addError($e->getMessage());

		}

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

		return $response;
	}


	/**
	 * Reset the changes.
	 * @param array $R
	 */
	protected function actionReset($R)
	{

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

		$recordsIds = $this->getListingSelection()->getList();
		if ($R['listing']['selection']) {
			$recordsIds = $this->setListingSelection($R['listing']['selection'])->getList();
		}

		$mngDocsCfg = \App\Config\PaymentDocuments::getAdmin();

		try {
			$mngDocsCfg->reset();
			foreach ($recordsIds as $id ) {
				$this->getListingSelection()->delete([$id]);
			}
			$msgs->addSuccess($this->lang['reset']['successMessage']);
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addError($e->getMessage());
		}

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

		return $response;
	}


	/**
	 * Move doc type up
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveUp(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{

		// first order the codes as they appear inside the configuration
		$orderedIds = [];
		foreach(\App\Config\PaymentDocuments::getAdmin()->getAll() as $code => $details) {

			if (in_array($code, $recordsIds)) {
				$orderedIds[] = $code;
			}

		}

		foreach ($orderedIds as $code) {

			try {

				\App\Config\PaymentDocuments::getAdmin()->itemMoveUp($code);
				if (count($orderedIds)>1) {
					$msgs->addSuccess($this->lang['moveUp']['successMessage']);
				}

			}
			catch (\App\Config\MessageException $e) {

				$msgs->addError($e->getMessage());

			}

		}

		$msgs->groupMessagesByTypeAndText();

	}

	/**
	 * Move doc type down
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveDown(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		//first order the codes as they appear inside the configuration
		$order = [];
		foreach(\App\Config\PaymentDocuments::getAdmin()->getAll()as $code => $details) {

			if (in_array($code,$recordsIds)) {
				$order[] = $code;
			}

		}

		// then reverse them as we are moving them down
		$orderedIds = array_reverse($order);

		foreach ($orderedIds as $code) {
			try {

				\App\Config\PaymentDocuments::getAdmin()->itemMoveDown($code);
				if (count($orderedIds)>1) {
					$msgs->addSuccess($this->lang['moveDown']['successMessage']);
				}

			}
			catch (\App\Config\MessageException $e) {

				$msgs->addError($e->getMessage());

			}
		}

		$msgs->groupMessagesByTypeAndText();

	}


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