/**
  * function __construct
  * <pre>
  * Initialize the object.
  * </pre>
  * @param $pathModuleRoot [STRING] The path to the module's root dir.
  * @param $viewer [OBJECT] The viewer object.
  * @param $sortBy [STRING] Field data to sort listManager by.
  * @param $managerInit [INTEGER] Initialization value for the listManager.
  * @return [void]
  */
 function __construct($pathModuleRoot, $viewer, $customreport_id, $disable_heading = false)
 {
     $this->is_blank_page = false;
     $this->disable_heading = $disable_heading;
     // store field display types
     $DISPLAY_FIELDS = $this->getDisplayFields($customreport_id);
     parent::__construct($DISPLAY_FIELDS);
     //         parent::__construct( page_ViewCustomReport::DISPLAY_FIELDS );
     $this->pathModuleRoot = $pathModuleRoot;
     $this->viewer = $viewer;
     $this->disableHeading = $disable_heading;
     $this->customreport_id = $customreport_id;
     $this->fields_id_array = array();
     $this->listLabels = array();
     // Get fields for the custom report; required for retrieving data in column format
     //         $columns = 'customfields_id,report_id,cim_hrdb_customfields.fields_id,count(person_id)';
     $groupBy = 'cim_hrdb_customfields.fields_id';
     $dbFunction = 'COUNT';
     $funcParam = 'person_id';
     $reportFields = new MultiTableManager();
     $customfields = new RowManager_CustomFieldsManager();
     $customfields->setReportID($this->customreport_id);
     // TODO?  error checking on ID
     $fieldvalues = new RowManager_FormFieldValueManager();
     $reportFields->addRowManager($customfields);
     $reportFields->addRowManager($fieldvalues, new JoinPair($customfields->getJoinOnFieldID(), $fieldvalues->getJoinOnFieldID()));
     // use GROUP BY and $dbFunction = 'COUNT' to quickly get summary data per campus
     if ($groupBy != '') {
         $reportFields->setGroupBy($groupBy);
         //'campus_desc');
     }
     if ($dbFunction != '') {
         $reportFields->setFunctionCall($dbFunction, $funcParam);
     }
     $reportFields->setSortOrder('COUNT(person_id) DESC');
     // 	     $reportFields->setFieldList($columns);
     $customFieldsList = $reportFields->getListIterator();
     $customFieldsArray = $customFieldsList->getDataList();
     //         echo '<pre>'.print_r($customFieldsArray,true).'</pre>';
     $i = 0;
     foreach (array_keys($customFieldsArray) as $key) {
         $record = current($customFieldsArray);
         $this->fields_id_array[$i] = $record['fields_id'];
         $i++;
         next($customFieldsArray);
     }
     // Ensure that the custom report has been given at least one field
     if (count($this->fields_id_array) > 0) {
         // Default sorting: by person name, since this is the only standard field
         $this->sortBy = 'person_lname,person_fname';
         // TODO: need to add person table to allow person_name sorting
         // Now load the access Privilege manager of this viewer
         $this->adminManager = new RowManager_AdminManager();
         // Get the person ID
         $accessManager = new RowManager_AccessManager();
         $accessManager->loadByViewerID($this->viewer->getViewerID());
         $personID = $accessManager->getPersonID();
         // Get the permissions the person has.
         $this->adminManager->loadByPersonID($personID);
         $directed_staff = '';
         $directed_people = '';
         // Super-admin
         if ($this->adminManager->hasSitePriv()) {
             $this->access_level = page_ViewCustomReport::SUPERADMIN;
         } else {
             if ($this->adminManager->isStaff($viewer->getID())) {
                 $director_id = $this->getStaffIDfromViewerID();
                 $staffManager = new RowManager_StaffDirectorManager();
                 $staffManager->setDirectorID($director_id);
                 /* Retrieve all directors under the current director */
                 $hierarchy_result = $staffManager->getDirectorHierarchy($director_id);
                 $hierarchy_result->setFirst();
                 $hierarchy_array = array();
                 $directed_staff = '';
                 while ($hierarchy_result->moveNext()) {
                     $staff_ids = $hierarchy_result->getCurrentRow();
                     // 	           echo 'array = <pre>'.print_r($hierarchy_array,true).'</pre>';
                     for ($lvl = 1; $lvl <= MAX_DIRECTOR_LEVELS; $lvl++) {
                         $staff_id = $staff_ids['staff_lvl' . $lvl];
                         if ($staff_id != null) {
                             $directed_staff .= $staff_id . ',';
                         }
                     }
                 }
                 if ($directed_staff != '') {
                     $directed_staff = substr($directed_staff, 0, -1);
                     $this->access_level = page_ViewCustomReport::DIRECTOR;
                 } else {
                     $directed_staff = page_ViewCustomReport::NON_DIRECTOR;
                     $this->access_level = page_ViewCustomReport::NON_DIRECTOR;
                 }
                 $personGetter = new MultiTableManager();
                 $person_info = new RowManager_PersonManager();
                 $staff = new RowManager_StaffManager();
                 $personGetter->addRowManager($person_info);
                 $personGetter->addRowManager($staff, new JoinPair($staff->getJoinOnPersonID(), $person_info->getJoinOnPersonID()));
                 $personGetter->addSearchCondition('staff_id in (' . $directed_staff . ')');
                 $staffPersonList = $personGetter->getListIterator();
                 $staffPersonArray = $staffPersonList->getDataList();
                 foreach (array_keys($staffPersonArray) as $key) {
                     $record = current($staffPersonArray);
                     $directed_people .= $record['person_id'] . ',';
                     next($staffPersonArray);
                 }
                 $directed_people = substr($directed_people, 0, -1);
                 //remove last comma
             } else {
                 $this->access_level = page_ViewCustomReport::UNAUTHORIZED_DIRECTOR;
             }
         }
         // Retrieve custom report fields and store them in data columns for easy display
         $dataAccessObject = new MultiTableManager();
         $person_manager = new RowManager_PersonManager();
         $dataAccessObject->addRowManager($person_manager);
         $fieldList = '';
         $temp_tables = array();
         for ($i = 0; $i < count($this->fields_id_array); $i++) {
             $tempTableCreationSQLmaker = new MultiTableManager();
             $fieldvalue_manager = new RowManager_FormFieldValueManager();
             $fieldvalue_manager->setFieldID($this->fields_id_array[$i]);
             // 			  if ($this->access_level == page_ViewCustomReport::UNAUTHORIZED_DIRECTOR)
             // 			  {
             //  			  		$fieldvalue_manager->setPersonID($personID);		// only show staff's own data
             // 		  	  }
             // 		  	  else if ($this->access_level == page_ViewCustomReport::DIRECTOR)
             // 		  	  {
             // 					$fieldvalue_manager->addSearchCondition('person_id in ('.$directed_people.')');
             // 		  	  }
             // 		  	  else if ($this->access_level == page_ViewCustomReport::NON_DIRECTOR)		// director with no underlings
             // 		  	  {
             // 			  	  $fieldvalue_manager->setPersonID($personID);		// only show staff's own data
             // 		  	  }
             // 		  	  else if ($this->access_level == page_ViewCustomReport::SUPERADMIN)
             // 		  	  {
             // 			  	  // no restrictions
             // 		  	  }
             // Create a temporary table from a SQL join retrieving the data for a particular form field
             $tempTableCreationSQLmaker->addRowManager($fieldvalue_manager);
             $fields_manager = new RowManager_FormFieldManager();
             $tempTableCreationSQLmaker->addRowManager($fields_manager, new JoinPair($fieldvalue_manager->getJoinOnFieldID(), $fields_manager->getJoinOnFieldID()));
             $customfields_manager = new RowManager_CustomFieldsManager();
             $customfields_manager->setReportID($this->customreport_id);
             $tempTableCreationSQLmaker->addRowManager($customfields_manager, new JoinPair($fieldvalue_manager->getJoinOnFieldID(), $customfields_manager->getJoinOnFieldID()));
             $tempFieldList = 'person_id,fieldvalues_value';
             $tempTableCreationSQLmaker->setFieldList($tempFieldList);
             $tempTableCreationSQL = $tempTableCreationSQLmaker->createSQL();
             $temp_tables[$i] = new TempTableManager('temptable' . $i, $tempTableCreationSQL, $tempFieldList, 'temptable' . $i);
             //$PRIMARY_ID=-1
             $temp_tables[$i]->createTable(true);
             // Join the temporary tables together to get a table of n+1 columns where n = count($this->field_ids_array) and the extra column stores person_id
             if ($i > 0) {
                 $fieldList .= ',temptable' . $i . '.fieldvalues_value as value' . $i;
                 $i_minus = $i - 1;
                 $dataAccessObject->addRowManager($temp_tables[$i], new JoinPair($temp_tables[$i_minus]->getJoinOnFieldX(page_ViewCustomReport::JOIN_FIELD), $temp_tables[$i]->getJoinOnFieldX(page_ViewCustomReport::JOIN_FIELD), JOIN_TYPE_LEFT));
             } else {
                 $fieldList .= 'cim_hrdb_person.person_id,temptable' . $i . '.fieldvalues_value as value' . $i;
                 $dataAccessObject->addRowManager($temp_tables[0], new JoinPair($person_manager->getJoinOnFieldX(page_ViewCustomReport::JOIN_FIELD), $temp_tables[0]->getJoinOnFieldX(page_ViewCustomReport::JOIN_FIELD)));
             }
         }
         // Filter results by directed people IDs (if viewer is NOT super-admin)
         if ($this->access_level != page_ViewCustomReport::SUPERADMIN) {
             // 			  	  for ($i=0; $i < count($this->fields_id_array); $i++)
             // 				  {
             // 					  if ($this->access_level == page_ViewCustomReport::UNAUTHORIZED_DIRECTOR)
             // 					  {
             // 						  	$dataAccessObject->addSearchCondition('temptable'.$i.'.person_id in ('.$personID.')');			// only show staff's own data
             // 				  	  }
             // 				  	  else if ($this->access_level == page_ViewCustomReport::DIRECTOR)
             // 				  	  {
             // 							$dataAccessObject->addSearchCondition('temptable'.$i.'.person_id in ('.$directed_people.')');
             // 				  	  }
             // 				  	  else if ($this->access_level == page_ViewCustomReport::NON_DIRECTOR)		// director with no underlings
             // 				  	  {
             // 						  	$dataAccessObject->addSearchCondition('temptable'.$i.'.person_id in ('.$personID.')');			// only show staff's own data
             // 				  	  }
             // 			  	  }
             $dataAccessObject->addSearchCondition('cim_hrdb_person.person_id in (' . $directed_people . ')');
         }
         // 	  	  echo '<pre>'.print_r($temp_tables[0]->getListIterator()->getDataList(),true).'</pre>';
         // $temp_tables[0]->db->runSQL('select * from temptable0');
         $dataAccessObject->setFieldList($fieldList);
         $dataAccessObject->setSortOrder($this->sortBy);
         $this->listManager = $dataAccessObject->getListIterator();
         // 			echo '<pre>'.print_r($this->listManager->getDataList(),true).'</pre>';
     } else {
         $dataAccessObject = new MultiTableManager();
         $person_manager = new RowManager_PersonManager();
         $person_manager->setPersonID(page_ViewCustomReport::NO_FIELDS_SET);
         $dataAccessObject->addRowManager($person_manager);
         $dataAccessObject->setSortOrder($this->sortBy);
         $this->listManager = $dataAccessObject->getListIterator();
         $this->is_blank_page = true;
     }
     // now initialize the labels for this page
     // start by loading the default field labels for this Module
     $languageID = $viewer->getLanguageID();
     $seriesKey = modulecim_hrdb::MULTILINGUAL_SERIES_KEY;
     $pageKey = modulecim_hrdb::MULTILINGUAL_PAGE_FIELDS;
     $this->labels = new MultilingualManager($languageID, $seriesKey, $pageKey);
     // then load the page specific labels for this page
     $pageKey = page_ViewCustomReport::MULTILINGUAL_PAGE_KEY;
     $this->labels->loadPageLabels($pageKey);
     $this->labels->setSeriesKey(SITE_LABEL_SERIES_SITE);
     $this->labels->loadPageLabels(SITE_LABEL_PAGE_FORM_LINKS);
     $this->listLabels = $this->getListLabels($this->customreport_id);
     // NOTE: parameter *required*
     //        foreach (array_keys($this->listLabels,true) as $key)
     //        {
     // 	       $label = current($this->listLabels);
     //        	 $this->labels->setLabelTag('[title_value0]', '<title in tool_setup>', 'Monthly Support Goal');   // NOTE: cannot be used because nothing set in tool_setup
     //        echo 'labels = <pre>'.print_r($this->listLabels,true).'</pre>';
 }