<?php

namespace Modules\Admin\UsersProfiles;

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

	/**
	 * Indicates if the entity execution should use or not a transaction. It left to 'null' the
	 * class won't work correctly - the concrete class must set it to true/false.
	 * @var Boolean
	 */
	protected $useSqlTransaction = true;

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

		$this->actionsCfg['insert'] 	 = [ 'checkOption' => false];
		$this->actionsCfg['update'] 	 = [ 'checkOption' => false];
		$this->actionsCfg['delete'] 	 = [ 'checkOption' => false];
		$this->actionsCfg['copyProfile'] = [ 'checkOption' => false];
	}

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

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::insert_createEntityObject()
	 */
	protected function insert_createEntityObject($formData)
	{
		$entityObj = \Entity\UserProfile::insert();
		$entityObj->name = $formData['name'];
		return $entityObj;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::update_getDefaultFormData()
	 */
	protected function update_getDefaultFormData($idEntity)
	{
		$formData = [];
		$formData['name']=\Entity\UserProfile::select($idEntity)->name;
		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::update_createEntityObject()
	 */
	protected function update_createEntityObject($formData)
	{
		$entityObj = \Entity\UserProfile::update($this->updateIdRecord);
		$entityObj->name = $formData['name'];
		return $entityObj;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::delete_createEntityObject()
	 */
	protected function delete_createEntityObject($idRecord)
	{
		return \Entity\UserProfile::delete($idRecord);
	}


	/**
	 * @param array $R
	 * @return \Engine\Mvc\Response\Html
	 */
	protected function actionCopyProfile($R)
	{
		$msgs = \App\MessagesCollector::create();
        $modelOutput = false;

		// get form data for this operation
		if ($R[$this->formSubmitButtonName]) {
			// start transaction and check info

			\DB::startTransaction();
			$initialProfile = \Entity\UserProfile::selectForUpdate($R['id']);
			$sourceProfile = \Entity\UserProfile::selectForUpdate($R['idUsersAccessProfile']);

			if (!$initialProfile->recordExists()) {
				$msgs->addError($this->lang['copyProfile']['msgs']['noInitialProfile']);
			}
			elseif ($initialProfile->deleted) {
				$msgs->addWarning($this->lang['copyProfile']['msgs']['initialProfileDeleted']);
			}

			if ($R['id'] == $R['idUsersAccessProfile']) {
				$msgs->addWarning($this->lang['copyProfile']['msgs']['sameProfile']);
			}

			if (!$sourceProfile->recordExists()) {
			    $msgs->addWarning($this->lang['copyProfile']['msgs']['noNewProfile']);
			}
			elseif ($sourceProfile->deleted) {
			    $msgs->addWarning($this->lang['copyProfile']['msgs']['newProfileDeleted']);
			}

			if (!$msgs->hasErrorOrWarning()) {
				try {

					$profile = \Entity\UserProfile::update($R['id']);
					$profile->accessSectionsList = 	$sourceProfile->accessSectionsList;
					$profile->accessOptionsList = 	$sourceProfile->accessOptionsList;

					$profile->save();
					\DB::commitTransaction();

					$msgs->addSuccess($this->lang['copyProfile']['msgs']['success']);
					$modelOutput = true;

				} catch (\App\Entity\Exception $e) {
					\DB::rollbackTransaction();
					$msgs->appendMessages($e->getMessagesCollector());
				}

			}
			else {
			    \DB::rollbackTransaction();
			}
		}

		// create view object
		$view = new View_CopyProfile($this);

		// attach messages to view
		$view->getMessagesCollector()->appendMessages($msgs);

		// if everything ok close popup
		if ($modelOutput) {
			$view->setClosePopup(true);
		}

		// send data to the view
		$view->addInput('formData', $R);
		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);

		// render the view
		return new \Engine\Mvc\Response\Html($view->render());

	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionDefineParams()
	 */
	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		switch($option->getId()){
			case 'insert':
			break;

			case 'updateAccess':
				foreach ($selection as $selectedItem) {
					if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Admin/UsersProfiles-updateAccess')) {
						$option->setDisabled();
						break;
					}
				}
			break;

			case 'update': case 'copyProfile':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\UserProfile::update($selectedItem))) {
						break;
					}
				}
			break;

			case 'delete':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\UserProfile::delete($selectedItem))) {
						break;
					}
				}
			break;

			default:
				return false;
		}

		return true;

	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		return \Entity\UserProfile::select($id)->name;
	}
}
