<?php
namespace App\Dashboard\Widget;

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


	/**
	 * The default options associated when the widget is added.
	 * @var array
	 */
	protected function getDefaultOptions()
	{
		$return = [
			'docStartDate'=>	'1month',
			'invClientType'=>	'',
			'docVoided'=>		'0',
			'invUserType'=>		'responsible',
			'columnsList'=>		['docNumber', 'docDate', 'docType', 'docValue', 'invClient', 'viewInvOption'],
			'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']);

		// invoice period
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['docStartDate'], 'docStartDate', $this->getOption('docStartDate'));
		$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);

		// invoice client type
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['invClientType'], 'invClientType', $this->getOption('invClientType'));
		$vals = [
			'' => 				$_LANG['dashboard']['widgetsList'][$calledClass]['options']['clientType_any'],
			'legalEntity' => 	$_LANG['dashboard']['widgetsList'][$calledClass]['options']['clientType_corp'],
			'individual' => 	$_LANG['dashboard']['widgetsList'][$calledClass]['options']['clientType_cust']];
		$field->setPossibleValues($vals);
		$fieldset->addElement($field);

		// document void status
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['voidStatus'], 'docVoided', $this->getOption('docVoided'));
		$vals = [
			2 => 	$_LANG['dashboard']['widgetsList'][$calledClass]['options']['voidStatus_2'],
			0 =>	$_LANG['dashboard']['widgetsList'][$calledClass]['options']['voidStatus_0'],
			1 =>	$_LANG['dashboard']['widgetsList'][$calledClass]['options']['voidStatus_1']];
		$field->setPossibleValues($vals);
		$fieldset->addElement($field);

		// invoice user type
		$field = new \Engine\Form\Input\Select($_LANG['dashboard']['widgetsList'][$calledClass]['options']['invUserType'], 'invUserType', $this->getOption('invUserType'));
		$vals = [
			'all' => 			$_LANG['dashboard']['widgetsList'][$calledClass]['options']['invUserType_all'],
			'responsible'=>		$_LANG['dashboard']['widgetsList'][$calledClass]['options']['invUserType_resp'],
			'kam'=>				$_LANG['dashboard']['widgetsList'][$calledClass]['options']['invUserType_kam'],
			'both'=>			$_LANG['dashboard']['widgetsList'][$calledClass]['options']['invUserType_both']];
		$field->setTooltip($_LANG['dashboard']['widgetsList'][$calledClass]['options']['invUserTypeTooltip']);
		$field->setPossibleValues($vals);
		$fieldset->addElement($field);

		// listing columns
		$field = new \Engine\Form\Input\Checkboxes($_LANG['dashboard']['widgetsList'][$calledClass]['options']['chooseColumns'], 'columnsList', $this->getOption('columnsList'));
		$cols = ['docNumber', 'docDate', 'docType', 'docValue', 'docUser', 'invDetails', 'invDue', 'invClient', 'invUser', 'viewInvOption'];
		$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->getOption('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['docStartDate'], ['', '1day', '2days', '3days', '4days', '5days', '1week', '2week', '3weeks', '1month', '2months', '3months'])) {
			$options['docStartDate'] = $formData['docStartDate'];
		}
		if (in_array($formData['invClientType'], ['', 'legalEntity', 'individual'])) {
			$options['invClientType'] = $formData['invClientType'];
		}
		if (in_array($formData['docVoided'], [0, 1, 2])) {
			$options['docVoided'] = $formData['docVoided'];
		}
		if (in_array($formData['invUserType'], ['all', 'responsible', 'kam', 'both'])) {
			$options['invUserType'] = $formData['invUserType'];
		}
		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->getOption('columnsList') or !is_array($this->getOption('columnsList'))) {
			return false;
		}

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

		$output = [];

		// GET THE INVOICES LIST //////////////////////////////////////////////////////////////////
		$docsList = new \App\EntityList\InvoiceCashings();


		// APPLY CERTAIN FILTERS ON THE INVOICES --------------------------------------------------

		// apply invoice date filter
		$startDate = \Engine\DateTime::create($this->getOption('docStartDate'))->formatDateIso();

		$value = '- '.$this->getOption('docStartDate');
		$startDate = \Engine\DateTime::create($value)->formatDateIso();
		$docsList->setFilter('doc.docDate', '>=', $startDate);

		// apply voided doc filter
		if ($this->getOption('docVoided') == 1) {
			$docsList->setFilter('doc.voidTime', '>', 0);
		}
		elseif ($this->getOption('docVoided') == 0) {
			$docsList->setFilter('doc.voidTime', '=', 0);
		}

		// apply client type filter
		if ($this->getOption('invClientType') == 'legalEntity') {
			$docsList->setFilter('inv.idCustomer', '=', 0);
		}
		elseif ($this->getOption('invClientType') == 'individual') {
			$docsList->setFilter('inv.idCorporate', '=', 0);
		}

		// user type = all
		if ($this->getOption('invUserType') == 'all') {
			// nothing to filter
		}
		// user type = responsible
		elseif ($this->getOption('invUserType') == 'responsible') {
			$docsList->setFilter('inv.idUser', '=', CURRENT_ID_USER);
		}
		// user type = kam
		elseif ($this->getOption('invUserType') == 'kam') {
			$corpsList=\Entity\User::selectCurrent()->kamCorporatesList;
			if ($corpsList) {
				$docsList->setFilter('inv.idCorporate', 'IN', $corpsList);
			}
			else {
				$docsList->setFilter('inv.idCorporate', '0', 0);
			}
		}
		// user type = both
		elseif ($this->getOption('invUserType') == 'both') {
			$corpsList=\Entity\User::selectCurrent()->kamCorporatesList;
			$bv = [];
			$filter="inv.idUser=?";
			$bv[]=CURRENT_ID_USER;
			if ($corpsList) {
				$filter.=" OR inv.idCorporate IN (".implode(',', array_fill(0, count($corpsList), '?')).")";
				$bv=array_merge($bv, $corpsList);
			}
			$docsList->setCustomFilter($filter, $bv);
		}

		// apply user restrictions
		$docsList->applyUserRestriction(true);

		// ASSOCIATE COLUMNS FOR THIS LISTING -----------------------------------------------------
		if ($colsAssoc['docNumber']) {
			$docsList->setColumn('doc.docNumber');
		}

		if ($colsAssoc['docDate']) {
			$docsList->setColumn('doc.docDate');
		}
		if ($colsAssoc['docType']) {
			$docsList->setColumn('doc.docType');
		}
		if ($colsAssoc['docValue']) {
			$docsList->setColumns(['doc.value', 'doc.currency']);
		}
		if ($colsAssoc['docUser']) {
			$docsList->setColumn('doc.idUser', 'idDocUser');
		}
		if ($colsAssoc['invDetails']) {
			$docsList->setColumns(['inv.invoiceNumber', 'inv.invoiceDate']);
		}
		if ($colsAssoc['invDue']) {
			$docsList->setColumn('inv.dueDate');
		}
		if ($colsAssoc['invClient']) {
			$docsList->setColumns(['inv.idCorporate', 'inv.idCustomer']);
		}
		if ($colsAssoc['invUser']) {
			$docsList->setColumn('inv.idUser', 'idInvUser');
		}
		$docsList->setColumn('inv.id', 'idInvoice'); // so we can view this invoice and also forces this table to be used in sql
		$docsList->setColumn('doc.addTime'); // so we can order by this column

		// OTHER CLAUSES --------------------------------------------------------------------------
		$docsList->setOrderBy('addTime', 'DESC');
		$docsList->setLimit($this->getOption('selectLimit'));

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

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

		return $output;

	}
}