<?php
namespace App\Dashboard\Widget;

class LastTasks extends \Engine\Dashboard\Widgets\WidgetAbstract
{
	/**
	* The default cache lifetime.
	* @var Int
	*/
	protected $cacheLifetime = 120;

	/**
	 * The default options associated when the widget is added.
	 * @var array
	 */
	protected function getDefaultOptions() {
		$return = [
			'taskStartDate' => 			'2months',
			'responsibleCategory' => 	'user',
			'taskStatus' => 			['notDistributed', 'distributed', 'pending', 'inProgress', 'onHold'],
			'deadline' => 				'1week',
			'displayFreeTasks' => 		'1',
			'columnsList' =>		 	['description', 'status', 'deadline', 'priority', 'supervisor', 'viewOption'],
			'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']);

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

		// responsible category
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['respCateg'], 'responsibleCategory', $this->options['responsibleCategory']);
		$vals = [
			'user' => 	$_LANG['dashboard']['widgetsList'][$calledClass]['options']['respCateg_user'],
			'office' => $_LANG['dashboard']['widgetsList'][$calledClass]['options']['respCateg_office']
		];
		$field->setPossibleValues($vals);
		$field->setTooltip($_LANG['dashboard']['widgetsList'][$calledClass]['options']['respCategTooltip']);
		$fieldset->addElement($field);

		// task deadine
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['taskDeadline'], 'deadline', $this->options['deadline']);
		$periods = ['1hour', '2hours', '3hours', '4hours', '6hours', '8hours', '12hours', '1day', '2days', '3days', '4days', '5days', '1week', '2weeks', '3weeks', '1month'];
		$vals = [];
		foreach($periods as $per) {
			$vals[$per] = $_LANG['dashboard']['widgets']['_GENERAL_']['timePeriods'][$per];
		}
		$field->setPossibleValues($vals);
		$field->setTooltip($_LANG['dashboard']['widgetsList'][$calledClass]['options']['taskDeadlineTooltip']);
		$fieldset->addElement($field);

		// free tasks
		$field = new \Engine\Form\Input\Radio($_LANG['dashboard']['widgetsList'][$calledClass]['options']['freeTasks'], 'displayFreeTasks', $this->options['displayFreeTasks']);
		$field->setPossibleValues(['1'=>$_LANG['yes'], '0'=>$_LANG['no']]);
		$field->setTooltip($_LANG['dashboard']['widgets'][$calledClass]['options']['freeTaskTooltip']);
		$fieldset->addElement($field);

		// task status
		$field = new \Engine\Form\Input\Checkboxes($_LANG['dashboard']['widgetsList'][$calledClass]['options']['taskStatus'], 'taskStatus', $this->options['taskStatus']);
		$statuses = ['notDistributed', 'distributed', 'refused', 'pending', 'inProgress', 'onHold', 'finished'];
		$vals = [];
		foreach($statuses as $sts) {
			$vals[$sts] = $_LANG['tasks']['statusName'][$sts];
		}
		$field->setPossibleValues($vals);
		$fieldset->addElement($field);

		// listing columns
		$field = new \Engine\Form\Input\Checkboxes($_LANG['dashboard']['widgetsList'][$calledClass]['options']['chooseColumns'], 'columnsList', $this->options['columnsList']);
		$cols = ['description', 'status', 'deadline', 'priority', 'responsible', 'department', 'supervisor', 'viewOption'];
		$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['taskStartDate'], ['', '1day', '2days', '3days', '4days', '5days', '1week', '2week', '3weeks', '1month', '2months', '3months'])) {
			$options['taskStartDate'] = $formData['taskStartDate'];
		}
		if (in_array($formData['responsibleCategory'], ['user', 'office'])) {
			$options['responsibleCategory'] = $formData['responsibleCategory'];
		}
		if (in_array($formData['deadline'], ['', '1hour', '2hours', '3hours', '4hours', '6hours', '8hours', '12hours', '1day', '2days', '3days', '4days', '5days', '1week', '2weeks', '3weeks', '1month'])) {
			$options['deadline'] = $formData['deadline'];
		}
		if (is_array($formData['taskStatus'])) {
			$options['taskStatus'] = $formData['taskStatus'];
		}
		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;
		}


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

		$output = [];

		// GET THE TASKS LIST /////////////////////////////////////////////////////////////////////
		$tasksList=  new \App\EntityList\Tasks();

		// APPLY CERTAIN FILTERS ON THE LIST ------------------------------------------------------

		// apply invoice date filter
		$value = '- '.$this->options['taskStartDate'];
		$taskStartDate = \Engine\DateTime::create($value)->formatDateIso();
		$tasksList->setFilter('task.taskDate', '>=', $taskStartDate);

		// apply task status
		if (is_array($this->options['taskStatus']) and $this->options['taskStatus'] and count($this->options['taskStatus']) < 7) {
			$tasksList->setFilter('task.status', 'IN', $this->options['taskStatus']);
		}

		// apply deadline
		$deadlineTime = strtotime('+ '.$this->options['deadline']);
		$tasksList->setFilter('task.deadline', '<=', $deadlineTime);

		// apply responsible category and displayFreeTasks  filter

		// responsible category = office (display all office tasks)
		if ($this->options['responsibleCategory'] == 'office') {
			$tasksList->setFilter('task.idOffice', '=', CURRENT_ID_OFFICE);
		}
		// responsible category = user (display all office tasks)
		elseif ($this->options['responsibleCategory'] == 'user') {
			// freeTasks is not set - only the user's tasks are displayed
			if (!$this->options['displayFreeTasks']) {
				$tasksList->setFilter('task.idResponsibleUser', '=', CURRENT_ID_USER);
			// freeTasks is set - display the user's tasks and the ones that are free on the current office
			}
			else {
				$tasksList->setCustomFilter("task.idResponsibleUser=? OR (task.free AND task.idOffice=?)", [CURRENT_ID_USER, CURRENT_ID_OFFICE]);
			}
		}

		// ASSOCIATE COLUMNS FOR THIS LISTING -----------------------------------------------------
		if ($colsAssoc['description']) {
			$tasksList->setColumn('task.description');
		}
		if ($colsAssoc['status']) {
			$tasksList->setColumns(['task.status', 'task.free']);
		}
		if ($colsAssoc['deadline']) {
			$tasksList->setColumn('task.deadline');
		}
		if ($colsAssoc['priority']) {
			$tasksList->setColumn('task.priority');
		}
		if ($colsAssoc['responsible']) {
			$tasksList->setColumn('task.idResponsibleUser');
		}
		if ($colsAssoc['department']) {
			$tasksList->setColumn('task.idDepartment');
		}
		if ($colsAssoc['supervisor']) {
			$tasksList->setColumn('task.idAssignorUser');
		}
		$tasksList->setColumn('task.addTime'); // so we can order by this column

		// OTHER CLAUSES --------------------------------------------------------------------------
		$tasksList->setOrderBy('addTime', 'DESC');
		$tasksList->setLimit($this->options['selectLimit']);

		// ASSOCIATE THE DATA FOR THE LISTING /////////////////////////////////////////////////////
		$output['tasksList'] = $tasksList->exportRecords();

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

		return $output;

	}
}