<?php
/**
 * Export module - word
 * 
 * Contains all functions to generate Word file
 * 
 * @package linea21\utils\export
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 * Define, compose and generate a SDI (Sustainable Development Indicators) Word report
 */


/********************************************************************************************
 *
* Following functions are used to generate projects reports
*
********************************************************************************************/


/**
 * project_display_info()
 * Affiche les infos générales d'un projet
 *
 * @param int $pointer
 * @return bool true
 */
function project_display_info($pointer)
{
	
	global $project;
	global $section;
	global $report_settings;
	global $pageBreak;
	global $current_root_level;
	global $bookmark_level;

	$current_record = $project[$pointer];

	// we retrieve root level
	$levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
	$root_level = getLevelParent($levels, $current_record['level_id'], 0);

	// we display Finalities as chapters if asked
	if ($report_settings['finalities'] ===  true && $current_record['project_level_id'] !== 0) {

		if(is_array($root_level) && $root_level['id'] != $current_root_level) {
			project_display_root_level($root_level);
			$current_root_level = $root_level['id'];
		} elseif(!is_array($root_level)) {
				$section->addTitle(do_strip(_t('report', 'no-finality')), $bookmark_level);
		}

	}

	// titre du projet
	$out_title = formatText(mb_ucfirst($current_record['project_name']));
	
	// si non publié
	if ($current_record['project_statut'] == 'D') {
		$out_title .= ' / ' . strtolower(_t('statut', 'draftpdf'));
	}
	
	$section->addTitle(do_strip($out_title), $bookmark_level+1);

	// parent project
	if($current_record['project_parent_id'] != 0) {
	    project_display_parent($current_record['parent_project_name']);
	}

	// Niveau d'appartenance
	// root parent has been retrieved before
	if(is_array($root_level) && $root_level['id'] != 0) {
		$out_level = formatText('» ' . mb_ucfirst($current_record['level_label']). ' : ' . $current_record['level_name']) ;
		$out_level .=  ' / '. formatText( mb_ucfirst($root_level['label']) . ' : ' . $root_level['name']). PHP_EOL;
		$section->addText(do_strip($out_level), 'attachedTheme');
		$section->addTextBreak(1);
	} elseif(!empty($current_record['level_name'])) {
	    $out_level = formatText('» ' . mb_ucfirst($current_record['level_label']). ' : ' . $current_record['level_name']) ;
	    $section->addText(do_strip($out_level), 'attachedTheme');
	    $section->addTextBreak(1);
	}

	
	
	// finalities project
	if(defined('PROJECT_FINALITIES') && PROJECT_FINALITIES == 1) {
	    $section->addTextBreak(1);
	    $out_finalities_item = formatText(mb_ucfirst(_t('project', 'finalities')));
	    $section->addTitle(do_strip($out_finalities_item), ($bookmark_level+2));
	    
	    $sdfinalities = getFinalities($current_record['project_id'], 'array');

	    foreach ($sdfinalities as $finality) {
	        $section->addText('       ' . $finality['state_utf8'] . ' ' . do_strip($finality['name']), 'defaultF', 'defaultP');
	    }
	    $section->addTextBreak(2);
	    
	}
	
	// operationnal goal
	if(!empty($current_record['project_opgoal'])) {
	    $out_opgoal = formatText(empty_nc(do_strip($current_record['project_opgoal']))) . PHP_EOL;
	    $out_opgoal_item = formatText(mb_ucfirst(_t('project', 'opgoal')));
	    $section->addTitle(do_strip($out_opgoal_item), ($bookmark_level+2));
	    
	    $section->addText(do_strip($out_opgoal), 'defaultF', 'defaultP');
	    $section->addTextBreak(1);
	}

	// goal
	if(!empty($current_record['project_goal'])) {
		$out_goal = formatText(empty_nc(do_strip($current_record['project_goal']))) . PHP_EOL;
		$out_goal_item = formatText(mb_ucfirst(_t('project', 'goal')));
		$section->addTitle(do_strip($out_goal_item), ($bookmark_level+2));
		
		$section->addText(do_strip($out_goal), 'defaultF', 'defaultP');
		$section->addTextBreak(1);
	}

	// description
	//   $out_desc = formatText(empty_nc(strip_tags($current_record['project_description']))) . PHP_EOL;
	if(!empty($current_record['project_description'])) {
		$out_desc = formatText(empty_nc(do_strip($current_record['project_description']))) . PHP_EOL;
		$out_desc_item = formatText(mb_ucfirst(_t('project', 'description')));
		$section->addTitle(do_strip($out_desc_item), ($bookmark_level+2));
		
		$section->addText($out_desc, 'defaultF', 'defaultP');
		$section->addTextBreak(1);
	}

	// body	
	$out_body = formatText(empty_nc(do_strip($current_record['project_body']))) . PHP_EOL;
	$out_body_item = formatText(mb_ucfirst(_t('project', 'body')));
	$section->addTitle(do_strip($out_body_item), ($bookmark_level+2));
	
	$section->addText($out_body, 'defaultF', 'defaultP');
	$section->addTextBreak(1);

	project_complement($current_record);
	
	project_display_calendar($current_record);
	project_display_steering_budget($current_record);

	project_associated_indicators($current_record);
	if($report_settings['dashboard_values']) project_associated_dashboard($current_record);

	// because $section->addPageBreak(); does not work in current version
	$section->addTextBreak(null, null, $pageBreak);
	
	return true;
}


/**
 * project_associated_dashboard()
 * Affiche l'image des dernières valeurs des indicateurs
 *
 * @param int $current_record
 * @return bool true
 */
function project_associated_dashboard($current_record)
{
	global $section;

	// $section->addTextBreak(1);
	
	// Affichage de l'image si elle existe
	if(file_exists(SITE_PATH. 'tmp/report/project-'.$current_record['project_id'].'-dashboard.png')) {
		$section->addImage(SITE_PATH. 'tmp/report/project-'.$current_record['project_id'].'-dashboard.png', array('align' => 'center', 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(12)));
	}

	$section->addTextBreak(1);
	
	return true;
}



/**
 * project_display_steering_budget()
 * Affiche les tableaux contenant information 'animation / comité de pilotage'
 * et budget
 *
 * @param int $current_record
 * @return bool true
 */
function project_display_calendar($current_record)
{
	global $section;
	global $phpWord;
	global $cellalign;
	global $styleTable;
	global $firstRowStyle;
	global $bookmark_level;
	
	$out_item = formatText(mb_ucfirst(_t('project', 'calendar_title'))) ;
	
	$section->addTitle($out_item, $bookmark_level+2);
	
	$phpWord->addTableStyle('calendar', $styleTable, $firstRowStyle);
	$table = $section->addTable('calendar');
	
	$fStyle = array('size' => FONT_SIZE_MIN);
	$cStyle = array('align' => 'center');
	
	// header
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(mb_ucfirst(_t('project', 'begin_date')), 'arrayHeader', $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(mb_ucfirst(_t('project', 'estimated_date')), 'arrayHeader', $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(mb_ucfirst(_t('project', 'end_date')), 'arrayHeader', $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(mb_ucfirst(_t('project', 'progression')), 'arrayHeader', $cStyle);
	
	// values
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(empty_nc($current_record['project_begin_date_display']), $fStyle, $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(empty_nc($current_record['project_estimated_date_display']), $fStyle, $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(empty_nc($current_record['project_end_date_display']), $fStyle, $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText(empty_nc($current_record['project_completed']) . ' %', $fStyle, $cStyle);
	
	$section->addTextBreak(3);
	
	return true;

}

/**
 * project_associated_indicators()
 * Affiche la liste des indicateurs associés
 *
 * @param int $current_record
 * @return bool true
 */
function project_associated_indicators($current_record)
{
	global $section;
	global $bookmark_level;

	$out_indicators_item = formatText(mb_ucfirst(_t('project', 'sdi')));
	$section->addTitle($out_indicators_item, ($bookmark_level+2));

	$query = SQL_getProjectSdi($current_record['project_id']);
	$data = $GLOBALS['sql_object']->DBSelect($query);


	if(isset($data[0]['sdii_id'])) {
		foreach ($data as &$value) {
			$section->addListItem(do_strip($value['sdii_name']), 0, 'list');
		}
	} else $section->addText(mb_ucfirst(_t('divers','none')));

	$section->addTextBreak(2);

	return true;
}


/**
 * project_complement()
 * Affiche la priorité et l'échelle de rattachement
 *
 * @param int $current_record
 * @return bool true
 */
function project_complement($current_record)
{
	global $section;

	$textrun = $section->addTextRun('align-right');
	$textrun->addText(mb_ucfirst(_t('project', 'statut')). ' : ', 'softLabelMin');
	$textrun->addText(display_statut($current_record['project_statut']), 'softMinBold');
	$textrun->addText(' / ' . mb_ucfirst(_t('project', 'priority')). ' : ', 'softLabelMin');
	$textrun->addText($current_record['priority_name'], 'softMinBold');
	if($current_record['scale_id'] != 0 ) {
		$textrun->addText(' / ' . mb_ucfirst(_t('project', 'scale')). ' : ', 'softLabelMin');
		$textrun->addText(do_strip($current_record['scale_denomination']) , 'softMinBold');
	}
	
	$section->addTextBreak(2);

	return true;
}


/**
 * project_display_steering_budget()
 * Affiche les tableaux contenant information 'animation / comité de pilotage'
 * et budget
 *
 * @param int $current_record
 * @return bool true
 */
function project_display_steering_budget($current_record)
{
	global $section;
	global $phpWord;
	global $cellalign;
	global $styleTable;
	global $firstRowStyle;
	global $bookmark_level;

	$section->addTitle(_t('project','steering_title') . ' - ' . _t('project','budget_title'), $bookmark_level+2);

	$coordinator = getAssociatedActors($current_record['project_id'], 'coordinator');
	$partners = getAssociatedActors($current_record['project_id'], 'partner');
	$manager = getAssociatedManagers($current_record['project_id']);

	$fStyle = array('size' => FONT_SIZE_MIN);
	$cStyle = array('align' => 'center');
	
	$phpWord->addTableStyle('steering_budget', $styleTable, $firstRowStyle);
	$table = $section->addTable('steering_budget', array('cellMargin' => 5));
	
	// header
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH / 2, $cellalign)->addText(mb_ucfirst(_t('project', 'steering_title')), 'arrayHeader', $cStyle);
	$row->addCell(PAGE_WIDTH / 2, $cellalign)->addText(mb_ucfirst(_t('project', 'budget_title')), 'arrayHeader', $cStyle);
	
	// content 
	$row = $table->addRow();
	$table_steering = $row->addCell(PAGE_WIDTH / 2, $cellalign)->addTable(array('width' =>  'auto', 'align' => 'left'));
	$table_budget = $row->addCell(PAGE_WIDTH / 2, $cellalign)->addTable(array('width' =>  'auto', 'align' => 'left'));
	
	// nested tables
	$r1 = $table_steering->addRow()->addCell(PAGE_WIDTH / 2);
	
	$textrun = $r1->addTextRun();
	$textrun->addText(mb_ucfirst(_t('project', 'elected')). ' : ', 'softLabelMin');
	$textrun->addText(empty_nc(do_strip($current_record['project_elected'])), 'softMinBold');
	
	$r2 = $table_steering->addRow()->addCell(PAGE_WIDTH / 2);
	$textrun = $r2->addTextRun();
	$textrun->addText(mb_ucfirst(_t('project', 'coordinator')). ' : ', 'softLabelMin');
	$textrun->addText(empty_nc($coordinator), 'softMinBold');
	
	$r3 = $table_steering->addRow()->addCell(PAGE_WIDTH / 2);
	$textrun = $r3->addTextRun();
	$textrun->addText(mb_ucfirst(_t('project', 'manager')). ' : ', 'softLabelMin');
	$textrun->addText(empty_nc($manager), 'softMinBold');
	
	$r4 = $table_steering->addRow()->addCell(PAGE_WIDTH / 2);
	$textrun = $r4->addTextRun();
	$textrun->addText(mb_ucfirst(_t('project', 'partners')). ' : ', 'softLabelMin');
	$textrun->addText(empty_nc($partners), 'softMinBold');
	
	$r5 = $table_steering->addRow()->addCell(PAGE_WIDTH / 2);
	$r5->addText(mb_ucfirst(_t('project', 'team')). ' : ', 'softLabelMin');
	$r5->addText(empty_nc(do_strip($current_record['project_team'])), 'softMinBold');
	
	$r1 = $table_budget->addRow()->addCell(PAGE_WIDTH / 2);
	$textrun = $r1->addTextRun();
	$textrun->addText(mb_ucfirst(_t('project', 'budget')). ' : ', 'softLabelMin');
	$textrun->addText(empty_nc(fnumber_format($current_record['project_budget'], 0, false)), 'softMinBold');
	
	$r2 = $table_budget->addRow()->addCell(PAGE_WIDTH / 2);
	$r2->addText(mb_ucfirst(_t('project', 'budget_comment')). ' : ', 'softLabelMin');
	$r2->addText(empty_nc(do_strip($current_record['project_budget_comment'])), 'softMinBold');

	
	// EXEMPLE NESTED
// 	$table = $section->addTable(array('width' => 50 * 50, 'unit' => 'pct', 'align' => 'center'));
// 	$cell = $table->addRow()->addCell();
// 	$cell->addText('This cell contains nested table.');
// 	$innerCell = $cell->addTable(array('align' => 'center'))->addRow()->addCell();
// 	$innerCell->addText('Inside nested table');
	
	
	$section->addTextBreak(3);
	

	return true;
}

function project_display_parent($name)
{
	global $section;

	$out = formatText(empty_nc(do_strip($name))) . PHP_EOL;
	$out_item = formatText('⬉ '. mb_ucfirst(_t('project', 'parent')));
	
	$textrun = $section->addTextRun();
	$textrun->addText(do_strip($out_item) . ' : ', 'softLabelMin');
	$textrun->addText(do_strip($out), 'softMinBold');
	$section->addTextBreak(1);

}

/**
 * project_display_root_level()
 * display root level as chapter
 * @param string $level
 */
function project_display_root_level($level)
{
	
	global $section;
	global $report_settings;
	global $pageBreak;
	global $bookmark_level;

	$section->addTextBreak(4);
	$section->addTitle(mb_ucfirst($level['name']), $bookmark_level);
	$section->addTextBreak(2);


	if ($report_settings['finalities_description'] === true) {
		$section->addText(do_strip($level['main_desc']));
	}
	
	// because $section->addPageBreak(); does not work in current version
	$section->addTextBreak(null, null, $pageBreak);

}



/********************************************************************************************
 *
* Following functions are used to generate dashboard reports
*
********************************************************************************************/


/**
 * indicator_display_info()
 * Affiche un IDD + infos satellites
 *
 * @param int $pointer
 * @return bool true
 */
function indicator_display_info($pointer)
{
  global $sdi;
  global $section;
  global $report_settings;
  global $pageBreak;


  indicator_display_main($sdi[$pointer]);
  indicator_display_values($sdi[$pointer]['sdii_id']);
  if ($report_settings['display_provider'] === true) indicator_display_provider($sdi[$pointer]);
  if ($report_settings['display_reglementation'] === true) indicator_display_rules($sdi[$pointer]);
  if ($report_settings['display_evaluation'] === true) indicator_display_assessment($sdi[$pointer]);

  // because $section->addPageBreak(); does not work in current version
  $section->addTextBreak(null, null, $pageBreak);
  
  return true;
}


/**
 * indicator_display_main()
 * Affiche les infos générales d'un IDD
 *
 * @param int $current_record
 * @return bool true
 */
function indicator_display_main($current_record)
{
  global $section;
  global $report_settings;

  // titre d'un indicateur
  $out_title = formatText($current_record['sdii_name']);

  // si non publié
  if ($current_record['sdii_statut'] == 'D') {
    $out_title .= ' / ' . strtolower(_t('statut', 'draftpdf'));
  }
  // si non attaché au tableau de bord
  if ($current_record['sdii_to_dashboard'] == 'N') {
  	$out_title .= ' (' . strtolower(_t('sdi', 'not_attached_to_dashboard').')');
  }
  
  $section->addTitle($out_title, 1);
  
  // thème d'appartenance
  $out_level = formatText('» ' . mb_ucfirst(_t('sdi', 'level')). ' : ' . $current_record['level_name']) . PHP_EOL;
  // we retrieve root level
  $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
  $a = getLevelParent($levels, $current_record['level_id'], 0);
  if(is_array($a) && $a['id'] != $current_record['level_id']) $out_level .=  ' / ' .formatText( mb_ucfirst($a['label']) . ' : ' . $a['name']) . PHP_EOL;
  
  $section->addText(do_strip($out_level), 'attachedTheme');
  
  // description
  $out_desc = formatText(do_strip($current_record['sdii_description'])) . PHP_EOL;
  $section->addText($out_desc);
  $section->addTextBreak(1);
  
  // objectif
  $out_goal = formatText(empty_nc(do_strip($current_record['sdii_goal']))) . PHP_EOL;
  $out_goal_item = formatText(mb_ucfirst(_t('sdi', 'goal')));
  $section->addTitle($out_goal_item, 2);
  
  $section->addText($out_goal);
  $section->addTextBreak(1);
  
  // conseil d'amélioration
  $out_consulting = formatText(empty_nc(do_strip($current_record['sdii_consulting']))) . PHP_EOL;
  $out_consulting_item = formatText(mb_ucfirst(_t('sdi', 'consulting')));
  $section->addTitle($out_consulting_item, 2);
  $section->addText($out_consulting);
  $section->addTextBreak(1);

  // informations de mesure
  $out_mesures_item = formatText(ucfirst(_t('sdi', 'info_mesure')));
  $out_mesures_behavior = ($current_record['sdii_threshold_relative'] == 'Y' ? _t('sdi', 'threshold_relative_Y'): _t('sdi', 'threshold_relative_N'));
  $out_mesures_unit = formatText(mb_ucfirst(_t('sdi', 'unit'))) . ' : ' . $current_record['sdii_unit'] . PHP_EOL;
  $section->addTitle($out_mesures_item, 2);

  // unitée de mesure
  $section->addText($out_mesures_unit);
  // $section->addTextBreak(1);
 
  // tableau de valeurs
  indicator_display_mesures($current_record);
  // comportement
  $section->addText(mb_ucfirst($out_mesures_behavior), array('size' => FONT_SIZE_MIN, 'italic' => true, 'color' => '555555'), array('align' => 'right'));
  $section->addTextBreak(2);
}

/**
 * indicator_display_mesures()
 * Dessine le tableau des valeurs IDD
 *
 * @param  $current_record
 * @return bool true
 */
function indicator_display_mesures($current_record)
{

  global $section;
  global $phpWord;
  global $cellalign;
  global $cellHeaderStyle;
  global $styleTable;
  global $firstRowStyle;
  
  $a = getBooleanValues($current_record);
  
  // if indicator is boolean or qualitative and mask is defined
  if(($current_record['sdii_type'] == 'boolean' || $current_record['sdii_type'] == 'qualitative') && $a) {
	  if($a) {
	  		$index = array();
	  		foreach ($a as $key => $value) {
	  			array_push($index, $key);
	  		}
	  	
	  		$display_minvalue = $a[min($index)];
	  		$display_maxvalue = $a[max($index)];
	  		($current_record['sdii_threshold_value'] != '') ? $display_threshold = $a[$current_record['sdii_threshold_value']] : $display_threshold = empty_nc('');
	  	} 
  } else {
  	$display_minvalue = empty_nc($current_record['sdii_min_value']);
  	$display_maxvalue = empty_nc($current_record['sdii_max_value']);
  	$display_threshold = empty_none(fnumber_format($current_record['sdii_threshold_value'], 'auto', false));
  	 
  }
  
  $fStyle = array('size' => FONT_SIZE_MIN);
  $cStyle = array('align' => 'center');
  
  $phpWord->addTableStyle('units', $styleTable, $firstRowStyle);
  $table = $section->addTable('units');
  

	// row 1 - header
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH / 4, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'min_value')), 'arrayHeader', $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'max_value')), 'arrayHeader', $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'initial_threshold_value')), 'arrayHeader', $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'frequency')), 'arrayHeader', $cStyle);
	
	// row 2
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText($display_minvalue, $fStyle, $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText($display_maxvalue, $fStyle, $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText($display_threshold, $fStyle, $cStyle);
	$row->addCell(PAGE_WIDTH / 4, $cellalign)->addText($current_record['sdii_frequency'], $fStyle, $cStyle);
	
	$section->addTextBreak(1);
	
  return true;
}

/**
 * indicator_display_provider()
 * Affiche les informations Fournisseurs d'un IDD
 *
 * @param  $current_record
 * @return bool true
 */
function indicator_display_provider($current_record)
{
  global $section;
  
  $lwidth = 0.29;

  $out_name = formatText($current_record['sdip_name']);
  if (!empty($current_record['sdip_service'])) $out_name .= ' - ' . formatText($current_record['sdip_service']);
  if (!empty($current_record['sdip_incharge'])) $out_name .= ' - ' . formatText($current_record['sdip_incharge']) . ' (' . _t('sdi', 'p_incharge') . ')';
  $out_adress = formatText(empty_nc(do_strip($current_record['sdip_address'])));
  $out_phone_fax = mb_ucfirst(_t('sdi', 'p_phone')) . ' : ' . formatText(empty_nc($current_record['sdip_phone']));
  $out_phone_fax .= ' - ' . mb_ucfirst(_t('sdi', 'p_fax')) . ' : ' . formatText(empty_nc($current_record['sdip_fax']));
  $out_email_item = mb_ucfirst(_t('sdi', 'p_email')) . ' : ';
  $out_email = formatText($current_record['sdip_email']);
  $out_desc = formatText(empty_nc(do_strip($current_record['sdip_description'])));
  $out_provider_item = formatText(ucfirst(_t('sdi', 'p_title'))) ;

  $section->addTitle($out_provider_item, 2);
  
  $styleTable = array('cellMargin' => 50);
  $table = $section->addTable($styleTable);
  
  $fStyle = array();
  $clStyle = array('align' => 'right');
  $crStyle = array('align' => 'left');
  
  $row = $table->addRow();
  $row->addCell(PAGE_WIDTH * $lwidth)->addText('');
  $row->addCell(PAGE_WIDTH * (1 - $lwidth))->addText(do_strip($out_name), $fStyle, $crStyle);
  
  $row = $table->addRow();
  $row->addCell(PAGE_WIDTH * $lwidth)->addText('');
  $row->addCell(PAGE_WIDTH * (1 - $lwidth))->addText($out_adress, $fStyle, $crStyle);
  
  $row = $table->addRow();
  $row->addCell(PAGE_WIDTH * $lwidth)->addText('');
  $row->addCell(PAGE_WIDTH * (1 - $lwidth))->addText($out_phone_fax, $fStyle, $crStyle);
  
  $row = $table->addRow();
  $row->addCell(PAGE_WIDTH * $lwidth)->addText('');
  $cell = $row->addCell(PAGE_WIDTH * (1 - $lwidth));
  $textrun = $cell->addTextRun();
  $textrun->addText($out_email_item, $fStyle);
	if (empty($out_email)) {
		$textrun->addText(empty_nc($out_email), $fStyle);
	} else {
		$textrun->addLink('mailto:' . $out_email, $out_email, $fStyle);
	}

	$section->addTextBreak(1);

  return true;
}

/**
 * indicator_display_rules()
 * Affiche la réglementation d'un IDD
 *
 * @param  $current_record
 * @return bool true
 */
function indicator_display_rules($current_record)
{
  global $section;
  
  $lwidth = 0.29;

  $out_name = formatText(empty_nc(do_strip($current_record['sdir_title']))) . PHP_EOL;
  $out_body = formatText(empty_nc(do_strip($current_record['sdir_body']))) . PHP_EOL;
  $out_uri = formatText(do_strip($current_record['sdir_mask_uri']));
  $out_uri_href = do_strip($current_record['sdir_referer_uri']);

  $out_name_item = mb_ucfirst(_t('sdi', 'r_title')) . ' : ';
  $out_body_item = mb_ucfirst(_t('sdi', 'r_body')) . ' : ';
  $out_uri_item = mb_ucfirst(_t('sdi', 'r_referer_uri')) . ' : ';

  $out_reglementation_item = formatText(ucfirst(_t('sdi', 'add_step4'))) ;

  $section->addTitle($out_reglementation_item, 2);
  
  $styleTable = array('cellMargin' => 50);
  $table = $section->addTable($styleTable);

	$fStyle = array();
	$clStyle = array('align' => 'right');
	$crStyle = array('align' => 'left');

	// nom de l'organisme fournisseur
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH * $lwidth)->addText($out_name_item, 'softLabel', $clStyle);
	$row->addCell(PAGE_WIDTH  * (1 - $lwidth))->addText($out_name, $fStyle, $crStyle);

  // détail reglementation
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH * $lwidth)->addText($out_body_item, 'softLabel', $clStyle);
	$row->addCell(PAGE_WIDTH  * (1 - $lwidth))->addText($out_body, $fStyle, $crStyle);
	
  // lien internet reglementation
	$row = $table->addRow();
	$row->addCell(PAGE_WIDTH * $lwidth)->addText($out_uri_item, 'softLabel', $clStyle);
	if (!empty($out_uri_href)) {
		if (!empty($out_uri)) $row->addCell(PAGE_WIDTH  * (1 - $lwidth))->addLink($out_uri_href, $out_uri, $fStyle);
	} else {
		$row->addCell(PAGE_WIDTH  * (1 - $lwidth))->addText(empty_nc($out_uri), $fStyle, $crStyle);
	}
	
	$section->addTextBreak(1);
	
  return true;
}

/**
 * indicator_display_assessment()
 * Affiche le tableau de critères d'évaluation
 *
 * @param int $current_record
 * @return bool true
 */
function indicator_display_assessment($current_record)
{
  global $section;
  global $phpWord;
  global $cellalign;
  global $cellHeaderStyle;
  global $styleTable;
  global $firstRowStyle;

  $out_eval_item = formatText(mb_ucfirst(_t('sdi', 'e_title'))) ;


  $section->addTitle($out_eval_item, 2);
  
  $phpWord->addTableStyle('evaluation', $styleTable, $firstRowStyle);
  $table = $section->addTable('evaluation');
  
  $fStyle = array('size' => FONT_SIZE_MIN);
  $cStyle = array('align' => 'center');
  
  // header
  $row = $table->addRow();
  $row->addCell(PAGE_WIDTH / 6, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'e_scale_compare')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'e_fiability')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'e_accessibility')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'e_lisibility')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'e_relevance')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'e_global_performance')), 'arrayHeader', $cStyle);
  
  // values
  $row = $table->addRow();
  $row->addCell(PAGE_WIDTH / 6, $cellalign)->addText($current_record['sdie_scale_compare'], $fStyle, $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellalign)->addText($current_record['sdie_fiability'], $fStyle, $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellalign)->addText($current_record['sdie_accessibility'], $fStyle, $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellalign)->addText($current_record['sdie_lisibility'], $fStyle, $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellalign)->addText($current_record['sdie_relevance'], $fStyle, $cStyle);
  $row->addCell(PAGE_WIDTH / 6, $cellalign)->addText($current_record['sdie_global_performance'], $fStyle, $cStyle);

  $section->addTextBreak(1);

  return true;
}


/**
 * indicator_display_values()
 * Affiche les valeurs d'un IDD.
 *
 * @param int $sdi_id
 * @return bool true
 **/
function indicator_display_values($sdi_id)
{
  global $section;
  global $report_settings;
  global $scale_array;
  global $sql_object;
  global $scale_denomination_array;

  if(count($scale_array) == 0) return true;
  
  if ($report_settings['graphic_values'] === true && $report_settings['table_values'] === true) $mode = 'TWICE';
  elseif ($report_settings['graphic_values'] === true || $report_settings['table_values'] === true) $mode = 'ONE';
  else return false;

  $out_values_item = mb_ucfirst(_t('dashboard', 'all_value'));
  
  $section->addTitle($out_values_item, 2);

  $scale_no_values = array(); // recipient no values
  $scale_insuffisant_values = array(); // recipient insuffisant values graph


  for($i = 0; $i < count($scale_array); $i++) {

  	// we print chart if asked
  	if ($report_settings['graphic_values'] === true) {
      if (indicator_display_graphic_values($sdi_id, $scale_array[$i], indicator_get_status($report_settings['status']), $mode) === false) array_push($scale_insuffisant_values, $scale_array[$i]);
    }

    // we print values if asked
    if ($report_settings['table_values'] === true) {
    	if (indicator_table_values($sdi_id, $scale_array[$i], indicator_get_status($report_settings['status']), $mode) === false) array_push($scale_no_values, $scale_array[$i]);
    }

  }
  indicator_no_values_for($scale_no_values, _t('report', 'no_values_for'));
  indicator_no_values_for($scale_insuffisant_values, _t('report', 'insuffisant_values'), $mode, $scale_no_values);

  return true;
}


/**
 * indicator_get_status()
 * Formattage du statut pour requête SQL
 *
 * @param string $current_status
 * @return string $status
 **/
function indicator_get_status($current_status)
{
  switch ($current_status) {
    case 'ALL':
      $status = 'SCA';
      break;
    case 'PUBLIC':
      $status = 'SCP';
      break;
  }
  return $status;
}

/**
 * indicator_no_values_for()
 * Affiche les échelles ne contenant pas de valeurs ou insuffisamment
 *
 * @param array $array_scale
 * @param string $message
 * @param integer $mode
 * @param integer $array
 * @return bool true
 **/
function indicator_no_values_for($array_scale, $message, $mode = -1, $array = -1)
{
  global $section;
  global $scale_denomination_array;
  $content = '';
  $sep = '';
  // si mode TWICE et deuxième tableau fourni. On le soustrait au premier.
  if ($array != -1 && $mode == 'TWICE') $array_scale = array_values(array_diff($array_scale, $array));

  if (count($array_scale) == 0) return true;

  for($i = 0; $i < count($array_scale); $i++) {
    $content .= $sep . $scale_denomination_array[$array_scale[$i]];
    $sep = ', ';
  }
  if (empty($content)) return true;
  
  $textrun = $section->addTextRun();
  $textrun->addText($message, 'noValueFor');
  $textrun->addText($content, array());
  $section->addTextBreak(1);

  return true;
}

/**
 * indicator_display_graphic_values()
 * Gènère et affiche les valeurs sous forme graphique
 *
 * @param int $sdi_id
 * @param int $current_scale
 * @param string $status
 * @param string $mode
 * @return bool true
 **/
function indicator_display_graphic_values($sdi_id, $current_scale, $status, $mode)
{
	global $section;
	global $sql_object;
	global $scale_denomination_array;
	
	// getting chart sizes
	list($width, $height) = explode('x', CHART_DEFAULT_SIZE);
	
	// We retrieve indicator type to see if we generate graph or not
	$result_sdii = $sql_object -> DBSelect(SQL_getInfoSdi($sdi_id));
	$indicator_type = $result_sdii[0]['sdii_type'];
	

	include_once(override('../dashboard/graph.php'));
	
 	$values = $sql_object->DBSelect(SQL_getAllValue($status, $current_scale, $sdi_id));
	
// 	// renversement des valeurs pour affichage chronologique
// 	if(is_array($values)) $values = @array_reverse ($values, false);

// 	$result_sdii = $sql_object->DBSelect(SQL_getInfoSdi($sdi_id));

 	if (!is_array($values) || count($values) < 2) 	return false;
	
	if($indicator_type == 'quantitative') {

	    generateGraphic($sdi_id, $current_scale, $status, 'auto', false, $width, $height, '../tmp/report');
		
		// /////////////////////////////
		// Affichage
		
		// Affichage du titre
		$out_scale_item = $scale_denomination_array[$current_scale];
		
		$scaleStyle = array('bold' => true);
		$section->addText($out_scale_item, $scaleStyle);
		// $section->addTextBreak(1);
		
		// Affichage de l'image
		$section->addImage('../tmp/report/'.$sdi_id.'_'.$current_scale.'.png', array('align' => 'center', 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(12)));
	
		$section->addTextBreak(1);
	}
	
	if($indicator_type == 'qualitative') {
		indicator_display_qualitative_array($values,$result_sdii[0]);
		// @todo display graphic  
		// http://stackoverflow.com/questions/23005670/how-to-convert-the-html-tag-string-to-a-word-document-using-phpword
		// https://github.com/PHPOffice/PHPWord/blob/master/samples/Sample_26_Html.php
		//		https://phpword.readthedocs.io/en/latest/
// 			$r = getQualitativeViz($values, $result_sdii[0], 'short', true, false);
// 			\PhpOffice\PhpWord\Shared\Html::addHtml($section, $r);
	}

	return true;
	
}


/**
 * indicator_display_qualitative_array()
 * Dessine le tableau des valeurs qualitatives
 *
 * @param  $current_record
 * @return bool true
 */
function indicator_display_qualitative_array($values, $current_record, $dateFormat = 'short') {

	global $section;
	global $phpWord;

	$a = getBooleanValues($current_record);
	// get get color ramp
	$colors = getColorRamp($a);
	

	$styleTable = array('borderSize' => 0, 'borderColor' => 'ffffff',  'cellMargin' => 25, 'width' => 100);
	$firstRowStyle = array('bgColor' => ARRAY_HEADER_BG);
	
	$cStyle = array('align' => 'center', 'color' => '777777', 'size' => FONT_SIZE_MIN);
	
	
	$total = count($values);
	// if there is no result we quit the function
	if(!isset($values[0]['sdiv_value'])) return false;
	
	$section->addTextBreak(1);
	$phpWord->addTableStyle('qualitative-viz', $styleTable, $firstRowStyle);
	$table = $section->addTable('qualitative-viz');
	
		
	$values = array_reverse($values);
	
	// row 1 - header
	$row = $table->addRow();
	foreach ($values as $entry) {
		if($dateFormat == 'short') $date = substr(formatDate($entry['date_p'], true), 0, 4);
		else $date = $entry['date_p'];
		$row->addCell(PAGE_WIDTH / $total, array())->addText($date, $cStyle, array('align' => 'center'));
		
	}
	// row 2
	$row = $table->addRow();
	foreach ($values as $entry) {
		$fStyle = array('size' => FONT_SIZE_MIN, 'color' => $colors[$entry['sdiv_value']]['color']);
		$c2Style = array('align' => 'center', 'bgColor' => $colors[$entry['sdiv_value']]['background-color']);
		$row->addCell(PAGE_WIDTH / $total, $c2Style)->addText("\n\n".$a[$entry['sdiv_value']]."\n\n", $fStyle, array('align'=> 'center'));
	}
	
	$section->addTextBreak(2);
	
	// adding legend
	$table = $section->addTable('qualitative-viz-legend');
	$row = $table->addRow();
	for($i=0; $i<count($a); $i++) {
		$legendColorStyle = array('align' => 'center', 'bgColor' => $colors[$i]['background-color']);
		$row->addCell(PAGE_WIDTH / (count($a)*8), $legendColorStyle);
		$row->addCell(PAGE_WIDTH / (count($a)*1.7), array())->addText($a[$i], $cStyle, array('align' => 'left'));
	}
	$section->addTextBreak(2);

	return true;
}

/**
 * indicator_table_values()
 * Affiche un tableau de valeurs a une échelle donnée
 *
 * @param int $sdi_id
 * @param int $current_scale
 * @param string $status
 * @param string $mode
 * @return bool true
 **/
function indicator_table_values($sdi_id, $current_scale, $status, $mode)
{
	
	global $section;
	global $phpWord;
	global $sql_object;
	global $scale_denomination_array;
	global $cellalign;
	global $cellHeaderStyle;
	global $styleTable;
	global $firstRowStyle;

	$values = array();

	
	// setting $default_threshold value
	// By default initial value
	$result_sdii = $sql_object -> DBSelect(SQL_getInfoSdi($sdi_id));
	$default_threshold = $result_sdii[0]['sdii_threshold_value'];

	$sdi_values = $sql_object->DBSelect(SQL_getAllValue($status, $current_scale, $sdi_id));
	

	if (!is_array($sdi_values) || count($sdi_values) <= 1) return false;

	// we prepare values for displaying
	for($i = 0; $i < count($sdi_values); $i++) {

		if(!empty($sdi_values[$i]['sdiv_multivalue'])) {

			$data = unserialize($sdi_values[$i]['sdiv_multivalue']);
			$current_value = $data;
			
			if($i == 0) {
				$lastValue = $data[0]['_total']; // we store data to compute TCAM and global rate
				$year_end = substr(formatDate($sdi_values[$i]['date_p'], true), 0, 4);
			}
			if($i == count($sdi_values)-1) {
				$firstValue = $data[0]['_total']; // we store data to compute TCAM and global rate
				$year_start = substr(formatDate($sdi_values[$i]['date_p'], true), 0, 4);
			}
			
		} else {
			
			$current_value = '';
			
			// If indicator is boolean or quantitative
			if($result_sdii[0]['sdii_type'] == 'boolean' || $result_sdii[0]['sdii_type'] == 'qualitative') {
				$a = getBooleanValues($result_sdii[0]);
				if($a) {
					$current_value .= $a[$sdi_values[$i]['sdiv_value']];
				} else {
					$current_value .= empty_none(fnumber_format($sdi_values[$i]['sdiv_value'], 'auto', false));
				}
				 
			} else {
				$current_value .= fnumber_format($sdi_values[$i]['sdiv_value'], 'auto', false);
				
				if($i == 0) {
					$lastValue = $sdi_values[$i]['sdiv_value']; // we store data to compute TCAM and global rate
					$year_end = substr(formatDate($sdi_values[$i]['date_p'], true), 0, 4);
				}
				if($i == count($sdi_values)-1) {
					$firstValue = $sdi_values[$i]['sdiv_value']; // we store data to compute TCAM and global rate
					$year_start = substr(formatDate($sdi_values[$i]['date_p'], true), 0, 4);
				}
			}
			
		}
		 
		// if set, we get it from the table
		if(!is_null($sdi_values[$i]['sdiv_threshold'])) {
			// If indicator is boolean or quantitative
			if($result_sdii[0]['sdii_type'] == 'boolean' || $result_sdii[0]['sdii_type'] == 'qualitative') {
				$threshold = $a[$sdi_values[$i]['sdiv_threshold']];
			} else {
				$threshold = empty_none(fnumber_format($sdi_values[$i]['sdiv_threshold'], 'auto', false));
			}
			
		} else {
			// If indicator is boolean or quantitative
			if($result_sdii[0]['sdii_type'] == 'boolean' || $result_sdii[0]['sdii_type'] == 'qualitative') {
				if(!is_null($default_threshold)) $threshold = $a[$default_threshold];
				else $threshold = empty_none('');
			} else {
				$threshold = empty_none(fnumber_format($default_threshold, 'auto', false));
			}
		}
		 
		if ($sdi_values[$i]['sdiv_statut'] == 'D') $current_value .= ' *';
		if (!empty($sdi_values[$i]['sdiv_comment'])) {
			if($sdi_values[$i]['sdiv_comment_display']=='Y') {
				$comment_status = _t('dashboard', 'public');
			} else {
				$comment_status = _t('dashboard', 'private');
			}
			
			$comments = formatText(do_strip($sdi_values[$i]['sdiv_comment'])) .' ('.$comment_status.')'.PHP_EOL;

		} else {
			$comments = '';
		}
		
		$current_date = formatText($sdi_values[$i]['date_p']);
		
		$values[$i]['current'] = $current_value;
		$values[$i]['threshold'] = $threshold;
		$values[$i]['date'] = $current_date;
		$values[$i]['comment'] = $comments;

	}

	// Affichage des données
	
	// Affichage du titre seulement si affichage des valeurs en standalone
	// ou si la génération des graphiques est infaisables car moins de 3 valeurs
	if ($mode != 'TWICE' || (count($sdi_values) >= 1 && count($sdi_values) < 3)) {
		$out_scale_item = $scale_denomination_array[$current_scale];
	
		$scaleStyle = array('bold' => true);
		$section->addText($out_scale_item, $scaleStyle);
	}
	
	// Affichage de l'astérisque - avertissement
	$section->addText('* ' . strtolower(_t('statut', 'draftpdf')).' ', array('size' => FONT_SIZE_MIN, 'italic' => true, 'color' => '555555'), array('align' => 'right'));
	
	$phpWord->addTableStyle('values', $styleTable, $firstRowStyle);
	$table = $section->addTable('values');
	
	$fStyle = array('size' => FONT_SIZE_MIN);
  $cStyle = array('align' => 'center');
  $clStyle = array('align' => 'left');

  
  // header
  $row = $table->addRow();
  $row->addCell(PAGE_WIDTH * 0.4, $cellHeaderStyle)->addText(mb_ucfirst(_t('dashboard', 'name_pluriel')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH * 0.2, $cellHeaderStyle)->addText(mb_ucfirst(_t('dashboard', 'threshold_value')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH * 0.2, $cellHeaderStyle)->addText(mb_ucfirst(_t('statut', 'published_on')), 'arrayHeader', $cStyle);
  $row->addCell(PAGE_WIDTH * 0.2, $cellHeaderStyle)->addText(mb_ucfirst(_t('sdi', 'comment')), 'arrayHeader', $cStyle);
	
  // values
	foreach ($values as &$val) {
		$row = $table->addRow();
		
		$cell = $row->addCell(PAGE_WIDTH * 0.4, $cellalign);
		
		if(is_array($val['current'])) {
			foreach($val['current'] as &$el) {
			
				$textrun = $cell->addTextRun();
				
				if(!empty($el['label'])) $disp = mb_ucfirst($el['label']). ' : ';
				$disp .= $el['value'];
				
				$textrun->addText($disp, 'arrayValue');
				$textrun->addText(' ('.fnumber_format($el['_percentage'], 2, false).' %)', 'percentageValue');

			}
			// we display the total
			$cell->addText(mb_ucfirst(_t('dashboard', 'multivalue_total')) . ' : ' . $val['current'][0]['_total'], array('size' => FONT_SIZE_MIN, 'bold' => true));
			

		} else {
			$cell->addText($val['current'], 'arrayValue', $cStyle);
		}
		
		
		$row->addCell(PAGE_WIDTH * 0.2, $cellalign)->addText($val['threshold'], $fStyle, $cStyle);
		$row->addCell(PAGE_WIDTH * 0.2, $cellalign)->addText($val['date'], $fStyle, $cStyle);
		$row->addCell(PAGE_WIDTH * 0.2, $cellalign)->addText($val['comment'], $fStyle, $clStyle);
	}
	
	// affichage des taux
	if($result_sdii[0]['sdii_type'] == 'quantitative') {
		$rates = getRates($firstValue, $lastValue, $year_start, $year_end, 'txt');
		$section->addTextBreak(1);
		$section->addText($rates, array('size' => FONT_SIZE_MIN, 'italic' => false));
	}
	$section->addTextBreak(2);
		
	return true;
}

/**
 * do_strip()
 * @param string $content
 * @return string
 */
function do_strip($content) {

	global $report_settings;
	
	$replace_array = array("\r\n", "\n\r", "\\r\\n", "\\n\\r", "\r", "\\r", "\\n");
	
	if($report_settings['export_format'] === 'html') {
		
		return $content;
		
	} else { 
		
		$converted = new html2text($content);
	
		// @see https://github.com/PHPOffice/PHPWord/issues/384
		// this will convert all "\n" to new lines when generating Word files
		$str = str_replace($replace_array,"\n", $converted->get_text()); // cleaning new line syntax
		$str = htmlspecialchars($str, ENT_NOQUOTES, CHARSET);
		$str = str_replace("\n", "</w:t><w:br/><w:t>", $str); // should be after htmlspecialchars()
		return $str;
	}
}


?>