<?php

// TODO: vezi TODOs de la clasele din app

// TODO: cleanup director: eliminat module vechi si cleanup: tktAutobalance si autobalance din files/cache

namespace Modules\Invoices\BalancesAuto;

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

	protected $listOrderingColumns = ['score'];

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

		$this->actionsCfg['balanceBulk'] 		= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['delete'] 			= ['checkSection' => true, 	'checkOption' => false];
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::index_alterListParams()
	 */
	protected function index_alterListParams($R)
	{
		$filters = [];

		if ($R['filters']['idSupplierInvoice']) {
			$filters['orderDate']['start'] = '';
			$filters['orderDate']['end'] = '';
		}

		if ($filters) {
			$this->listingParams->mergeFilters($filters);
			$this->listingParams->save();
		}
	}

	/**
	 * (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 'createBalance': case 'createBalanceWithoutConfirmation': case 'balanceBulk': case 'delete': case 'bulkDelete':
			break;

			default:
				return false;
		}

		return true;
	}

	protected function bulkActionBalanceBulk(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{

		$suggestions = \App\AutoBalanceServices\ListManager::getInstance()->getServiceDetails($recordsIds);

		if ($suggestions) {

			foreach ($suggestions as $idService => $suggestion) {

				\DB::startTransaction();

				try {
					if ($suggestion['component'] == 'refund') {
						$idReservationServices = ['R'.$idService];
					}
					elseif ($suggestion['component']=='both') {
						$idReservationServices = [$idService, 'R'.$idService];
					}
					else {
						$idReservationServices = [$idService];
					}

					$idSupplierInvoiceRowsArr = explodeClean('|',$suggestion['idSupplierInvoiceRows']);
					$balance = \Entity\Balance::insert();
					$balance->balanceStatus = "final";
					$balance->generation = 'auto';
					$balance->idUser = CURRENT_ID_USER;
					$balance->idOffice = CURRENT_ID_OFFICE;
					$balance->idReservationServices = $idReservationServices;
					$balance->idSupplierInvoiceRows = $idSupplierInvoiceRowsArr;
					$balance->save();

					\App\AutoBalanceServices\ListManager::getInstance()->deleteService($idService);
					$msgs->addSuccess($this->lang['index']['successMessages']['balanceBulk']);

					$this->getListingSelection()->delete([$idService]);
					\DB::commitTransaction();

				}
				catch (\App\Entity\Exception $e) {
					\DB::rollbackTransaction();
					$msgs->addError(sprintf($this->lang['index']['errorMessages']['balanceBulk'], $idService, $e->getMessagesCollector()->getMessageBulk()));
				}

			}
		}
		$msgs->groupMessagesByTypeAndText();
	}

	protected function bulkActionDelete(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{

		foreach ($recordsIds as $idService) {
			try {
				\App\AutoBalanceServices\ListManager::getInstance()->deleteService($idService);
				$msgs->addSuccess($this->lang['index']['successMessages']['delete']);
				// remove this record from the internal list
				$this->getListingSelection()->delete([$idService]);
			}
			catch (\App\AutoBalanceServices\Exception $e) {
				$msgs->addError($e->getMessage());
			}
		}

		$msgs->groupMessagesByTypeAndText();

	}


	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		return $id;
	}

}