<?php

namespace App\Reports\Sources\DocsList;


class PopulateInitialImport extends \App\Reports\Sources\PopulateAbstract
{

	/**
	 * {@inheritDoc}
	 * @see \App\Reports\Sources\PopulateAbstract::populate()
	 */
	public function populate() :void
	{

		// INITS //////////////////////////////////////////////////////////////////////////////////

		global $DBTRd_documents, $DBTRd_users;

		$reportTable = $this->tableManager->getTableName();

		$activeColumns = array_keys( $this->columnsManager->getStdColumns() );

		$stdFilters = $this->filtersManager->getStdFilters();


		// CREATE SQL FOR COPYING DOCUMENTS LIST //////////////////////////////////////////////////

		// refresh report status
		$this->reportGenerationStatusUpdate('extractMainDataFromDb', 'runningMainSQL', 0);
		$reportCopyInfo = new \App\Reports\Db\ManageRecords\Insert($reportTable);
		$reportCopyInfo->setMainTable($DBTRd_documents,	'doc');
		$reportCopyInfo->addJoinTable($DBTRd_users,		'addUser',	'doc.idAddUser=addUser.id', 'LEFT');

		$cols = [
			'doc_id'				=> 'doc.id',
			'doc_typeCode'			=> 'doc.docType',
			'doc_number'			=> 'doc.docNumber',
			'doc_date'				=> 'doc.docDate',
			'doc_format'			=> 'doc.format',
			'doc_generationType'	=> 'doc.generation',
			'doc_idTemplate'		=> 'doc.idTemplate',
			'doc_idSeries'			=> 'doc.idDocSeries',
			'doc_idAutoProcessRule' => 'doc.idAutoProcessRule',
			'doc_comments'			=> 'doc.comments',
			'doc_isPreview'			=> 'doc.preview',

			'pivot_id'				=> 'doc.idPivot',
			'pivot_code'			=> 'doc.pivot',

			'doc_addUserId'			=> 'doc.idAddUser',
			'doc_addUserOffId'		=> 'addUser.idOffice',
			'doc_addUserDeptId'		=> 'addUser.idDepartment',
			'doc_addTime'			=> 'doc.addTime',

			'doc_fieldsDetails'		=> 'doc.fieldsDetails',
		];

		$reportCopyInfo->setStructureColumns($cols);
		$reportCopyInfo->addStructureColumn("doc_dateYM",			"DATE_FORMAT(doc.docDate, '%Y-%m-01')");
		$reportCopyInfo->addStructureColumn("doc_dateY", 			"YEAR(doc.docDate)");
		$reportCopyInfo->addStructureColumn("email_sent", 			"IF(doc.emailDetails != '', 1, 0)");
		$reportCopyInfo->addStructureColumn("doc_addUserName", 		"CONCAT(addUser.lastName, ' ', addUser.firstName)", 'addUser');

		$reportCopyInfo->setActiveColumns($activeColumns);

		// ADD FILTERS ////////////////////////////////////////////////////////////////////////////
		if ($stdFilters['docDate']['start']) {
			$reportCopyInfo->addFilter('doc.docDate', '>=', $stdFilters['docDate']['start']);
		}
		if ($stdFilters['docDate']['end']) {
			$reportCopyInfo->addFilter('doc.docDate', '<=', $stdFilters['docDate']['end']);
		}

		if ($stdFilters['docType']) {
			$reportCopyInfo->addFilter('doc.docType', 'IN', $stdFilters['docType']);
		}

		if ($stdFilters['docGroupType'] == 'groupByPivotDoc') {
			$reportCopyInfo->addGroupBy(['doc.pivot', 'doc.idPivot', 'doc.docType']);
			$reportCopyInfo->addOrderBy('doc.idPivot', 'DESC');
		}

		$reportCopyInfo->populate();

	}

}
