<?php
namespace Modules\Bsp\Settlement;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract
{
	protected $listOrderingColumns = ['balanceStatus', 'ticketNumber', 'ticketDate',];

	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['exportCurrentRecords'] =     	['authType' => 'easy', 'checkSection'=>false, 'checkOption'=>false];
		$this->actionsCfg['changeStatus'] =     			['authType' => 'easy', 'checkSection'=>false, 'checkOption'=>false];
	}

	/**
	 * (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 'exportCurrentRecords':
			break;

			case 'changeStatus':
			case 'changeStatusBulk':
			break;

			default:
				return false;
		}

		return true;
	}

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

	/**
	 * Export records as seen in the listing
	 * @return \Engine\Mvc\Response\BigFileDownload
	 */
	protected function actionExportCurrentRecords($R)
	{
		$msgs = \App\MessagesCollector::create();

		$closePopup = false;

		// step 1
		if ($R['save']) {
			\DB::prepareForLongRunningScript();
			// increase the time limit
			set_time_limit(1800);
			session_write_close();

			$listingParams = clone($this->loadListingParams($R)->getListingParams());
			$extension = '???';
			switch ($R['reportStyle']) {
				case 'bspReconciliationReport':
					$generator = new ModelGenerateReportBspReconciliationReport();
					$extension = 'csv';
				break;

				case 'bspExceptionsReport':
					$generator = new ModelGenerateReportBspExceptionsReport();
					$extension = 'xls';
				break;

				default:
					throw new \Exception(sprintf("[%s] Unknown report style: %s", __METHOD__, $R['reportStyle']));
			}
			$outputFile = \Engine\File::tempnam(sprintf("%s-%s.%s", __CLASS__, time(), $extension));	// write file to temporary location

			$generator->setListingParams($listingParams);
			$generator->generate($outputFile);


			// compose filename from the used filters
			$formFilters = new View_Utils_FormFilters($this);
			$formFilters->setValue('listingParams', $listingParams);
			$filterOverview = $formFilters->getForm()->getFilterOverviewValues();

			usort($filterOverview, function($a, $b) {
				return strcmp($a['id'], $b['id']);
			});

			$overviewStr = implode(", ", array_map(function($f) {
				return sprintf("%s-%s",
					preg_replace("/(filters_|_)/", '', $f['id']),
					trim(preg_replace("/[^a-zA-Z0-9\s]/", '', $f['overview']))
				);
			}, $filterOverview));

			// download & delete
			$fileName = sprintf("BSPSettlement, exported at %s%s.%s", \Engine\DateTime::create()->format('Ymd His'),
				($overviewStr?sprintf(", filtered by %s", $overviewStr):', default filters'),
				$extension
			);
			$response = new \Engine\Mvc\Response\BigFileDownload($outputFile);
			$response->body->setOption('deleteAfterSend', true);
			$response->setFilename($fileName);
			return $response;
		}

		$view = new View_GenerateReport($this);

		// send data to the view
		$view->addInput('formData', $R);
		$view->setClosePopup($closePopup);
		$view->getMessagesCollector()->appendMessages($msgs);

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

	protected function actionChangeStatus($R)
	{
		$msgs = \App\MessagesCollector::create();

		$closePopup = false;

		$view = new View_ChangeStatus($this);

		if ($R['save']) {
			\DB::startTransaction();

			foreach ($R['ids'] as $id) {
				$bspSettlementRecordUpd = \Entity\BspSettlementRecord::updateOperationalStatus($id);
				$bspSettlementRecordUpd->operationalStatus = $R['newStatus'];
				$bspSettlementRecordUpd->save();
			}
			\DB::commitTransaction();

			$msgs->addSuccess($this->lang['changeStatus']['success']);
			$closePopup = true;
		}

		// send data to the view
		$view->addInput('formData', $R);
		$view->setClosePopup($closePopup);
		$view->getMessagesCollector()->appendMessages($msgs);

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

}
