<?php
namespace App\Dashboard\Widget;

// TODO: [notImportant] ar trebui sa fie o coloana care sa ma lase sa autoprocesez un serviciu nepreluat
class LastImportedServices extends \Engine\Dashboard\Widgets\WidgetAbstract
{
	/**
	 * The default cache lifetime.
	 * @var Int
	 */
	protected $cacheLifetime=600;


	/**
	 * The default options associated when the widget is added.
	 * @var array
	 */
	protected function getDefaultOptions() {
		$return = [
				'resStartDate'=>'2weeks',
				'responsible'=>'',
				'idSystem'=>'0',
				'serviceCode'=>'',
				'processStatus'=>['new', 'processed', 'blocked'],
				'columnsList'=>['date', 'passenger', 'serviceType', 'status'],
				'selectLimit'=>5,
		];
		return $return;
	}



	/**
	 * Generate the options form
	 */
	protected function populateLocalOptionsForm(\Engine\Form\Container\GeneralAbstract $form)
	{
		$calledClass = get_called_class();
		$className = stripClassNamespace($calledClass);

		// load lang
		$loaderLang = \App\Loader_Lang::getInstance();
		$loaderLang->loadAppFile("_customLoad/dashboard/widgets/_general.lang.php");
		$loaderLang->loadAppFile("_customLoad/dashboard/widgets/{$className}.lang.php");
		$_LANG = $loaderLang->getAll();

		$fieldset = \Engine\Form\Container\Fieldset::create($_LANG['dashboard']['widgets']['_GENERAL_']['formFields']['specificFieldsLegend']);

		// reservation period
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['resStartDate'], 'resStartDate', $this->options['resStartDate']);
		$periods = ['', '1day', '2days', '3days', '4days', '5days', '1week', '2weeks', '3weeks', '1month', '2months'];
		$vals = [];
		foreach($periods as $per) {
			$vals[$per] = $_LANG['dashboard']['widgets']['_GENERAL_']['timePeriods'][$per];
		}
		$field->setPossibleValues($vals);
		$fieldset->addElement($field);

		// responsible type
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['responsible'], 'responsible', $this->options['responsible']);
		$vals = [ ''=>$_LANG['dashboard']['widgetsList'][$calledClass]['options']['responsible_all'], 'user'=>$_LANG['dashboard']['widgetsList'][$calledClass]['options']['responsible_user'] ];
		$field->setPossibleValues($vals);
		$field->setTooltip($_LANG['dashboard']['widgetsList'][$calledClass]['options']['responsibleTooltip']);
		$fieldset->addElement($field);

		// system
		$field = new \App\Form\Input\Select_OrdersExternalSystem($_LANG['dashboard']['widgetsList'][$calledClass]['options']['system'], 'idSystem', $this->options['idSystem']);
		$field->showDefaultOption();
		$fieldset->addElement($field);

		// service status
		$field = new \Engine\Form\Input\Checkboxes($_LANG['dashboard']['widgetsList'][$calledClass]['options']['processStatus'], 'processStatus', $this->options['processStatus']);
		$field->setPossibleValues( [ 'new'=>$_LANG['importedService']['statusName']['new'], 'processed'=>$_LANG['importedService']['statusName']['processed'], 'blocked'=>$_LANG['importedService']['statusName']['blocked'] ] );
		$fieldset->addElement($field);

		// service code
		$field = new \App\Form\Input\Select_Service($_LANG['dashboard']['widgetsList'][$calledClass]['options']['serviceCode'], 'serviceCode', $this->options['serviceCode']);
		$field->showDefaultOption(true);
		$field->setTooltip($_LANG['dashboard']['widgetsList'][$calledClass]['options']['serviceCodeTooltip']);
		$fieldset->addElement($field);

		// listing columns
		$field = new \Engine\Form\Input\Checkboxes($_LANG['dashboard']['widgetsList'][$calledClass]['options']['chooseColumns'], 'columnsList', $this->options['columnsList']);
		$cols = [ 'id', 'date', 'passenger', 'serviceType', 'offer', 'extResId', 'status' ];
		$vals = [];
		foreach($cols as $col) {
			$vals[$col] = $_LANG['dashboard']['widgetsList'][$calledClass]['options']['columnsList'][$col];
		}
		$field->setPossibleValues($vals);
		$fieldset->addElement($field);

		// listing limit
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['selectLimit'], 'selectLimit', $this->options['selectLimit']);
		$vals = [
			'5' => 	$_LANG['dashboard']['widgets']['_GENERAL_']['selectLimits']['5'],
			'10' => $_LANG['dashboard']['widgets']['_GENERAL_']['selectLimits']['10']
		];
		$field->setPossibleValues($vals);
		$fieldset->addElement($field);

		$form->addContainer($fieldset);
		return $form;
	}


	/**
	 * Extract data from the form return($R) and sets internal configs($this->options) accordingly
	 */
	protected function extractFormOptions($formData)
	{

		$options = [];

		if (in_array($formData['resStartDate'], ['', '1day', '2days', '3days', '4days', '5days', '1week', '2weeks', '3weeks', '1month', '2months'])) {
			$options['resStartDate'] = $formData['resStartDate'];
		}
		if (in_array($formData['responsible'], ['', 'user'])) {
			$options['responsible'] = $formData['responsible'];
		}
		if (is_numeric($formData['idSystem']) and $formData['idSystem']>0) {
			$options['idSystem'] = $formData['idSystem'];
		}
		if (mb_strlen($formData['serviceCode']) <= 2) {
			$options['serviceCode'] = $formData['serviceCode'];
		}
		if (is_array($formData['processStatus'])) {
			$options['processStatus'] = array_keys($formData['processStatus']);
		}
		if (is_array($formData['columnsList'])) {
			$options['columnsList'] = array_keys($formData['columnsList']);
		}
		if ($formData['selectLimit'] <= 20 and $formData['selectLimit'] > 0 and is_numeric($formData['selectLimit'])) {
			$options['selectLimit'] = $formData['selectLimit'];
		}

		$this->setOptions($options);
	}



	/**
	 * Sets the collected processed data.
	 * @return Array
	 */
	protected function getData()
	{

		// if no columns selected - do not go on
		if (!$this->options['columnsList'] or !is_array($this->options['columnsList'])) {
			return false;
		}
		// if no system id - do not go on
		if (!$this->options['idSystem']) {
			return false;
		}

		// get columns in an associative array
		$colsAssoc = array_combine($this->options['columnsList'], array_fill(0, count($this->options['columnsList']), true));

		$output = [];

		// GET THE IMPORTED RESERVATIONS LIST /////////////////////////////////////////////////////

		$impServListObj = new \App\EntityList\ImportedServices();
		$impServListObj->setColumns(['importedOrder.date'=>'orderDate', 'importedService.processStatus', 'importedService.idServiceTina', 'importedService.serviceCode', 'importedService.offerExternalSystemReservationId'=>'extResId']);
		$impServListObj->setColumns(['importedService.offerTotalValue', 'importedService.offerTotalCurrency', 'importedService.passengerLastName', 'importedService.passengerFirstName']);
		$impServListObj->setFilter('importedOrder.date', '>=', date(MYSQL_FORMAT, strtotime('- '.$this->options['resStartDate'])));
		$impServListObj->setFilter('importedService.idSystem', '=', $this->options['idSystem']);
		if ($this->options['processStatus']) {
			$impServListObj->setFilter('importedService.processStatus', 'IN', $this->options['processStatus']);
		}
		if ($this->options['serviceCode']) {
			$impServListObj->setFilter('importedService.serviceCode', '=', $this->options['serviceCode']);
		}
		if ($this->options['responsible'] == 'user') {
			$impServListObj->setFilter('importedService.idUser', '=', CURRENT_ID_USER);
		}
		$impServListObj->setOrderBy('importedService.addTime', 'DESC');
		$impServListObj->setLimit((Int)$this->options['selectLimit']);
		$impServList = $impServListObj->exportRecords();

		// ASSOCIATE NEW INFO /////////////////////////////////////////////////////////////////////
		foreach($impServList as $idx=>$row) {
			if ($row['serviceCode']) {
				$impServList[$idx]['serviceName'] = \App\Config\Services_Basic::getInstance()->getServiceName($row['serviceCode']);
			}
		}

		// ASSOCIATE THE DATA FOR THE LISTING /////////////////////////////////////////////////////
		$output['resList'] = $impServList;

		// ASSOCIATE OTHER INFO ///////////////////////////////////////////////////////////////////
		$output['columnsListAssoc'] = $colsAssoc;

		return $output;

	}

}