<?php
/**
 * Export module - pdf
 * 
 * Contains all functions to generate PDF 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) PDF report
 */


/**
 * cleanHTMLList()
 * remove unique p tag in li
 * @param string $content
 * @return string
 * @see https://simplehtmldom.sourceforge.io/docs/1.9/api/api/
 */

if(!function_exists('cleanHTMLList')) {

    function cleanHTMLList($content) {

        if(empty($content)) return '';

        $html = new simple_html_dom();

        $html->load($content);
        $el = $html->find('ul li, ol li');

        if(is_null($el) || count($el) === 0) return $content;  // necessary to prevent crash
        foreach($el as $e) {
            $ptags = $e->find('p');
            if(is_null($ptags) || count($ptags) === 0) return $content; // necessary to prevent crash
            // if a unique p tag in li we remove it to prevent extra gap on list
            if(count($ptags) === 1) {
                 is_null($ptags[0]->innertext) ? $ptags[0]->outertext = '' : $ptags[0]->outertext = $ptags[0]->innertext;
            }
        }
        $clean = $html;
        $html->clear();
        unset($html);

        return $clean;

    }

}

/**
 * fixImageWidth()
 * remove given style (such as float or image width)
 * @param string $content
 * @return string
 */
if(!function_exists('fixImageWidth')) {
    function fixImageWidth($content) {
        
        $html = new simple_html_dom();
        
        $html->load($content);
        
        foreach ($html->find('img') as $el) {
            $el->{'style'} = ''; // we empty style attribute to remove float and width / height attributes 
            $el->outertext = '<p style="text-align:center;">' . $el->outertext . '<br /></p>';
        }
        
        $content = $html;
        
        unset($html);
        
        return $content;
        
    }
}

/**
 * rmUnwantedTags()
 * remove unwanted tags
 * @param string $content
 * @return string
 */
if(!function_exists('rmUnwantedTags')) {
    function rmUnwantedTags($content) {
        
        $html = new simple_html_dom();
        $html->load($content);
        
        foreach ($html->find('caption') as $el) {
            $el->outertext = '';
        }
        $content = $html;
        unset($html);

        $content = cleanHTMLList($content); // we also clean lists
        return $content;
        
    }
}

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

if(!function_exists('project_display_projects_completion')) {
    function project_display_projects_completion($status) {
        
        $comp = $GLOBALS['sql_object']->DBSelect(SQL_getTotalProjectCompletion($status));
        
        if(isset($comp) && is_array($comp)) $content = sprintf(_t('project', 'completion-percentage'), round($comp[0]['completion'], 0));
        else $content = '';
        
        return $content;
    }
}

if(!function_exists('project_recursive')) {
    function project_recursive($levels, $bookmark_level) {
        
        global $ordered_items;
        global $project;
        global $pdf;
        global $report_settings;
    
        $debug = false;
        
        // we retrieve all root levels if not given - when first run
        if($levels === null) {
            $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList(true));
            // we add PDF page, only on individual export
            // to prevent "TCPDF ERROR: Wrong page number on setPage() function: 0" error
            $pdf->addPage();
        }
        
        // if($debug) print_r($levels);
        
        // for each root level ...
        foreach($levels as $l) {
            
            // on affiche ici le nom du thèmes
            // et la description si demandée
            if($debug) echo "<h1>". $l['level_name'] . "</h1><p>". $l['level_desc_project'] . "</p><br /><br />";
            
            
            // if there is action related to current level we display them
            // first we prepare them
            $associated_projects = array();
            foreach($project as $p) {
                if($p['project_level_id'] == $l['level_id']) {
                    if($debug) echo "on affiche le projet ". $p['project_id'] ." (p-level-id".$p['project_level_id']. ") associé directement à ". $l['level_id']."<br />\n<br />\n";
                    array_push($associated_projects, $p);
                    array_push($ordered_items, $p);
                }
            }
            
            // we get levels children
            $levelschildren = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $l['level_id']);
            if($debug) echo "<h1>----- Here are children -----</h1>";
            if($debug) print_r($levelschildren);
            
            // we display level if they have associated projects or children levels and or we we display empty levels
            if($report_settings['levels'] ==  true && (count($associated_projects) > 0 || count($levelschildren) > 0 || $report_settings['display_empty_levels'] ===  true)) {
                project_display_level($l, $bookmark_level);
            } // elseif($report_settings['quick_export'] ==  false) $pdf->addPage();
            
            // we display project if any
            if(count($associated_projects) > 0) {
                
                $associated_projects = sort_projects($associated_projects);
                
                foreach($associated_projects as $proj) project_display_by_levels($proj, $bookmark_level +1);
            }
            
            if(count($levelschildren) > 0 ) project_recursive($levelschildren, $bookmark_level+1);

            
        }
        
    }
}

function sort_projects($projects) {
    
    // we init values each time we iterate
    $project_range = array();
    $project_name = array();
    
    // First we prepare multi-sort
    // @see http://php.net/manual/fr/function.array-multisort.php
    foreach ($projects as $key => $row) {
        $project_range[$key] = $row['project_range'];
        $project_name[$key] = $row['project_name'];
    }
    
    array_multisort($project_range, SORT_ASC, $project_name, SORT_ASC, $projects);
    
    return $projects;
    
}

function display_orphan_projects ($bookmark_level) {
    
    global $ordered_items;
    global $project;
    global $pdf;
    global $report_settings;
    global $pageBreak;
    
    $associated_projects = array();
    foreach($project as $p) {
        if($p['project_level_id'] == 0) {
            array_push($associated_projects, $p);
            array_push($ordered_items, $p);
        }
    }
    
    if(count($associated_projects) < 1) return false;
    
    if($report_settings['levels'] ==  true) {
        $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+8);
        $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
    } else {
        $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+4);
        $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
    }
    
    if ($report_settings['levels'] ==  true) {
        // chapter title
        $out_title = formatText(mb_ucfirst(_t('report', 'no-first-level')));
//         $pdf->SetTextColorArray(getColor('SDI_TITLE_COLOR'));
//         $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
        $pdf->Bookmark(mb_ucfirst($out_title), $bookmark_level);
        $pdf->Write(DOC_HEIGHT, $out_title);
        ParagraphBreak();
        ParagraphBreak();
    }
    
    $associated_projects = sort_projects($associated_projects);
    foreach($associated_projects as $proj) project_display_by_levels($proj, $bookmark_level+1);
    
    return true;
}

/**
 * project_display_info()
 * Affiche les infos générales d'un projet
 *
 * @param int $pointer
 * @return bool true
 */
if(!function_exists('project_display_by_levels')) {
    function project_display_by_levels($project, $bookmark_level)
    {
        
    
        global $report_settings;
        global $extraCSS;
        global $pdf;

		// we override dynamic $bookmark_level
        if($report_settings['levels'] ==  false) $bookmark_level = -1;
        
        $current_record = $project;
        if(defined('EXPORT_LOG') && EXPORT_LOG == 1) file_put_contents('../tmp/export-logs/pdf-projects.txt', $current_record['project_id']."\n", FILE_APPEND);
        
        $pdf->Ln(DOC_HEIGHT);
        
        // we retrieve root level
        $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
        $root_level = getLevelParent($levels, $current_record['level_id'], 0);

        // affichage du niveau d'avancement si existant
        if($current_record['project_achievement'] != '') {

            $out_stage  = ' <style>
                            .to_start {background-color: #d5d2d2;color:#333;font-size: 11px;}
                            .in_progress {background-color: #89c588;color:#333;}
                            .over {background-color: #4da148;color: #ffffff;font-size: 9px;}
                            .postponed {background-color: #f19749;color: #ffffff;}
                            .stopped {background-color: #da2648;color: #e8e8e8;}
                            </style>';
            $out_stage .= '<span  class="'.$current_record['project_achievement'] .'">  ' .mb_ucfirst($GLOBALS['lang']['project']['achievementItems'][$current_record['project_achievement']]) .'  </span>';
            $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE -2);
            $pdf->WriteHTML($out_stage, true, false, true, false, '');
            $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
        }

        // titre du projet
        $out_title = formatText(mb_ucfirst($current_record['project_name']));
        $pdf->SetTextColorArray(getColor('SDI_TITLE_COLOR'));
        $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
		$pdf->Bookmark(mb_ucfirst($out_title), $bookmark_level);
        $pdf->Write(DOC_HEIGHT, $out_title);

        
        // si non publié
        if ($current_record['project_statut'] == 'D') {
            $pdf->SetTextColorArray(getColor('DOC_ADVISE_COLOR'));
            $pdf->SetFont(DOC_POLICE, '', SDI_TITLE_SIZE);
            $out_status = ' / ' . strtolower(_t('statut', 'draftpdf'));
            $pdf->Write(DOC_HEIGHT, $out_status);
            $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
            $pdf->SetTextColorArray(getColor('DOC_COLOR'));
        }

        $pdf->Ln(DOC_HEIGHT);
        
        // parent project
        if($current_record['project_parent_id'] != 0) {
            $pdf->SetY($pdf->GetY() + 2);
            project_display_parent($current_record['parent_project_name']);
        }
        
        // Root levels
        // root parent has been retrieved before
        if ($report_settings['levels'] !==  true) {
            if(!defined('EXPORT_NOLEVELLABEL') || EXPORT_NOLEVELLABEL == 0) $out_level = formatText('» ' . mb_ucfirst($current_record['level_label']) . ' : ' . $current_record['level_name'] );
            else $out_level = formatText($current_record['level_name']);
            
            // root parent has been retrieved before
            if(is_array($root_level) && $root_level['id'] != $current_record['level_id']) {
                if(!defined('EXPORT_NOLEVELLABEL') || EXPORT_NOLEVELLABEL == 0) $out_level .=  ' / '. formatText( mb_ucfirst($root_level['label']) . ' : ' . $root_level['name']). PHP_EOL;
                else $out_level .=  ' / '. formatText($root_level['name']). PHP_EOL;
            }
            
            if(!empty($current_record['level_name'])) {
                $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
                $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
                $pdf->SetY($pdf->GetY() + 2);
                $pdf->Write(DOC_HEIGHT, $out_level);
                $pdf->SetTextColorArray(getColor('DOC_COLOR'));
            }
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        }
        
        // cibles de l'action
        $pdf->SetTextColorArray(getColor('SDI_TITLE_COLOR'));
        $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
        $targets = getAssociatedActors($current_record['project_id'], 'target');
        if(!empty($targets)) $pdf->Write(DOC_HEIGHT, mb_ucfirst(strip_tags(_t('project', 'target'))). ' : '. $targets);
        $pdf->SetTextColorArray(getColor('DOC_COLOR'));
        $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        
        // finalities project
        if(defined('PROJECT_FINALITIES') && PROJECT_FINALITIES == 1) {
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
            $out_finalities_item = formatText(mb_ucfirst(strip_tags(_t('project','finalities'))));
            //$pdf->Bookmark($out_finalities_item, ($bookmark_level+1), -1);
            project_format_item($out_finalities_item);
            $sdfinalities = getFinalities($current_record['project_id'], 'read');
            project_display_finalities($sdfinalities);
            
        }
        
        
        // operationnal goal
        if(!empty($current_record['project_opgoal'])) {
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
            $converted =  \Soundasleep\Html2Text::convert($current_record['project_opgoal']);
            $out_opgoal = formatText($converted) . PHP_EOL;
            $out_opgoal_item = formatText(mb_ucfirst(strip_tags(_t('project', 'opgoal'))));
            // $pdf->Bookmark($out_opgoal_item, ($bookmark_level+1), -1);
            project_format_item($out_opgoal_item);
            
            if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $current_record['project_opgoal'] = removeDomElement('img', $current_record['project_opgoal']);
            
            if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($current_record['project_opgoal']))), true, false, false, false, 'J');
            else $pdf->MultiCell(0, DOC_HEIGHT, $out_opgoal, 0, 'J');
            
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        }
        
        // goal
        if(!empty($current_record['project_goal'])) {
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
            $converted =  \Soundasleep\Html2Text::convert($current_record['project_goal']);
            $out_goal = formatText($converted) . PHP_EOL;
            $out_goal_item = formatText(mb_ucfirst(strip_tags(_t('project', 'goal'))));
            // $pdf->Bookmark($out_goal_item, ($bookmark_level+1), -1);
            project_format_item($out_goal_item);
            
            if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $current_record['project_goal'] = removeDomElement('img', $current_record['project_goal']);
            
            if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($current_record['project_goal']))), true, false, false, false, 'J');
            else $pdf->MultiCell(0, DOC_HEIGHT, $out_goal, 0, 'J');
            
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        }
        
        // description
        //   $out_desc = formatText(empty_nc(strip_tags($current_record['project_description']))) . PHP_EOL;
        if(!empty($current_record['project_description'])) {
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
            $converted =  \Soundasleep\Html2Text::convert($current_record['project_description']);
            $out_desc = formatText(empty_nc($converted)) . PHP_EOL;
            $out_desc_item = formatText(mb_ucfirst(strip_tags(_t('project', 'description'))));
            // $pdf->Bookmark($out_desc_item, ($bookmark_level+1), -1);
            project_format_item($out_desc_item);
            
            if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $current_record['project_description'] = removeDomElement('img', $current_record['project_description']);
            
            if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($current_record['project_description']))), true, false, false, false, 'J');
            else $pdf->MultiCell(0, DOC_HEIGHT, $out_desc, 0, 'J');
            
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        }
        
        // body
        //   $out_body = formatText(empty_nc(strip_tags($current_record['project_body']))) . PHP_EOL;
        if(!empty($current_record['project_body'])) {
            $converted =  \Soundasleep\Html2Text::convert($current_record['project_body']);
            $out_body = formatText(empty_nc($converted)) . PHP_EOL;
            $out_body_item = formatText(mb_ucfirst(strip_tags(_t('project', 'body'))));
            // $pdf->Bookmark($out_body_item, ($bookmark_level+1), -1);
            project_format_item($out_body_item);
            
            if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $current_record['project_body'] = removeDomElement('img', $current_record['project_body']);
            
            if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($current_record['project_body']))), true, false, false, false, 'J');
            else $pdf->MultiCell(0, DOC_HEIGHT, $out_body, 0, 'J');
            // $pdf->MultiCell(0, DOC_HEIGHT, $out_body, 0, 'J');
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        }
        
        // comment only if EXPLICITLY called
        if(defined('EXPORT_COMMENT') && (stripos(EXPORT_COMMENT, 'project') !== false) && !empty($current_record['project_comment'])) {
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
            $converted =  \Soundasleep\Html2Text::convert($current_record['project_comment']);
            $out_comment = formatText($converted) . PHP_EOL;
            $out_comment_item = formatText(mb_ucfirst(strip_tags(_t('project', 'comment'))));
            project_format_item($out_comment_item);
            
            if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $current_record['project_goal'] = removeDomElement('img', $current_record['project_comment']);
            
            if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($current_record['project_comment']))), true, false, false, false, 'J');
            else $pdf->MultiCell(0, DOC_HEIGHT, $out_comment, 0, 'J');
            
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        }

        
        
        project_complement($current_record);
        
        project_tasks($current_record, $bookmark_level+1);
        
        project_display_calendar($current_record, $bookmark_level+1);
        project_display_steering_budget($current_record, $bookmark_level+1, 2);
        
        project_display_impacts($current_record, $bookmark_level+1);
        
        // project_associated_indicators($current_record, $bookmark_level+1); // display indicators name or not ? @todo remove ?
        // if($report_settings['dashboard_values']) project_associated_dashboard($current_record); // old code generated from html2canvas @todo remove ?
        if($report_settings['dashboard_values']) project_associated_indicators_values($current_record);
    
    
        // we add page only if this is not a quick export
        if($report_settings['quick_export'] === false) $pdf->addPage();
        
        return true;
    }
}

/**
 * project_display_impacts()
 * Affiche les impacts de chacun des projets
 *
 * @param int $current_record
 * @return bool true
 */
if(!function_exists('project_display_impacts')) {
    function project_display_impacts($current_record, $bookmark_level) {
        
        global $pdf;
        
        // if not defined or not enabled we return false
        if (!defined('PROJECT_IMPACTS') || PROJECT_IMPACTS == 0) return false;

        $project_impacts = unserialize($current_record['project_impact']);

        // no values, we return empty string
        if (!is_array($project_impacts)) return false;
        
        ParagraphBreak();
        $out_tasks_item = formatText(mb_ucfirst(strip_tags(_t('project','impacts'))));
        // $pdf->Bookmark($out_tasks_item, $bookmark_level, -1);
        project_format_item($out_tasks_item);
        $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
        
        
        $tbl = '<style>
              	table {
              		border:1px solid #E2E2E2;
              		}
              	.header {
              		color:#777777;
            			background-color:#E2E2E2;
              		font-weight:bold;
              		font-size:7pt;
              	}
                td {
                	text-align:center;
              		color:#777777;
                }
              	td.br {
              		border-right:1px solid #E2E2E2;
              		}
            	</style>
              <table cellspacing="0" cellpadding="5" border="0" nobr="true">
              <thead>
                  <tr>%s</tr>
              </thead>
                  <tr>%s</tr>
              </table>';
        
        $td_header = '';
        $td_body = '';
        foreach ($project_impacts as $k => $v) {

            $td_header .= '<td class="header">' . formatText($GLOBALS['lang']['project']['impactsItems'][$k], '2HTML') . ' (' . $v . '/' . PROJECT_IMPACTS . ')</td>';
            $td_body .= '<td class="br">';
            for ($i = 0; $i < PROJECT_IMPACTS; $i ++) {
                if ($v >= $i + 1)
                    $td_body .= '<span style="color:#e98e4e;font-weight:bold;">+</span>';
                else
                    $td_body .= '<span style="color:#c1c1c1;font-weight:bold;">+</span>';
            }
            $td_body .= '</td>';
        }

        $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
        $pdf->writeHTML(sprintf($tbl, $td_header, $td_body), true, false, false, false, '');
        $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
    }
}

/**
 * project_tasks()
 * Affiche les tâches associées au projet
 *
 * @param int $current_record
 * @return bool true
 */
if(!function_exists('project_tasks')) {
    function project_tasks($current_record, $bookmark_level) {
        
        global $pdf;
        global $sql_object;
        
        
        if(defined('PROJECT_TASK') && PROJECT_TASK == 1) {
            
            $otask = new projectTask();
            $tasks = $otask->get_project_tasks($current_record['project_id'], $sql_object);
            
            if(!is_array($tasks)) return true;
            
            ParagraphBreak();
            $out_tasks_item = formatText(mb_ucfirst(strip_tags(_t('project','tasks_title'))));
            // $pdf->Bookmark($out_tasks_item, $bookmark_level, -1);
            project_format_item($out_tasks_item);
            $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
            
            $tasksp =  get_task_progress_bar($current_record['project_id'], true);
            $tasks =   get_tasks_for_report($tasks);
            
            $str ='';
            foreach($tasks as $el) {
                
                $task = formatText($el['label']);
                if(isset($el['done'])) $task .= '<br><span class="achieved">'.$el['done'].'</span>';
                $str .= '<tr>';
                
                $str .= '<td class="status task-'.$el['status_raw'].'">'.mb_strtoupper($el['status'], CHARSET).'</td>';
                $str .= '<td class="status-border status-'.$el['status_raw'].'"></td>';
                $str .= '<td class="task">'.nl2br($task).'</td>';
                $str .= '</tr>';
            }
            
            $pdf->MultiCell(0, DOC_HEIGHT, $tasksp, 0, 'R');
            
            $tbl = '<style>
            /* !!! duplicate .status-wip, .task-wip STYLES is necessary - some bugs !!???  */
			table {border:1px solid #ffffff;}
            td {border-bottom:1px solid #ffffff;}
            .status-border {width:1%;}
			.status {
				color:#333333;
				font-size:8pt;
                text-align:center;
                width:22%;
                text-transform:uppercase;
			}
            .task {text-align:left;width:77%;font-size:9pt;color:#333333;}
            .status-todo {background-color:#dadada;}
            .task-todo {color:#958b8b;}
            .status-wip {background-color:#fbbf50;}
            .task-wip  {color:#eab045;}
            .status-done  {background-color:#61d3a4;}
            .task-done  {color:#48a880;}
            .achieved {color:#444444;font-size:8pt;}
            
			</style>
      <table cellspacing="0" cellpadding="5" nobr="true">@@@</table>';
            
            $tasks = str_replace('@@@', $str, $tbl);
//             echo htmlentities($tasks);
//             exit;
            
            $pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
            $pdf->writeHTML($tasks, true, false, false, false, '');
            $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
            
            ParagraphBreak();
            
            return true;
            
        }
    }
}

/**
 * project_display_calendar()
 * Affiche les tableaux contenant information 'animation / comité de pilotage'
 * et budget
 *
 * @param int $record
 * @return bool true
 */
function project_display_calendar($record, $bookmark_level)
{
	global $pdf;

	ParagraphBreak();
	$out_cal_item = formatText(mb_ucfirst(strip_tags(_t('project','calendar_title'))));
	// $pdf->Bookmark($out_cal_item, ($bookmark_level), -1);
	project_format_item($out_cal_item);
	$pdf->SetY($pdf->GetY() + DOC_INTERVAL);

	$tbl = '<style>
			table {
  			   border:1px solid #E2E2E2;
				color:#777777;
  		    }
			.header {	
				color:#777777;
				background-color:#E2E2E2;
				font-size:7pt;
			}
		  td.br {
		    	border-right:1px solid #E2E2E2;
		  }
			td {
				text-align:center;
			}
			</style>
      <table cellspacing="0" cellpadding="5" nobr="true">
          <tr>
              <td class="header">'.mb_ucfirst(strip_tags(_t('project', 'begin_date'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('project', 'estimated_date'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('project', 'end_date'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('project', 'progression'))).'</td>
          </tr>
        <tr>
        	<td class="br">'.empty_nc($record['project_begin_date_display']).'</td>
        	<td class="br">'.empty_nc($record['project_estimated_date_display']).'</td>
        	<td class="br">'.empty_nc($record['project_end_date_display']).'</td>
        	<td>'.empty_nc($record['project_completed']).'% </td>
      	</tr>
      </table>';

	$pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
	$pdf->writeHTML($tbl, true, false, false, false, '');
	if(!empty($record['project_cal_comment'])) $pdf->writeHTML('<div>' . empty_nc($record['project_cal_comment']) . '</div>', true, false, false, false, '');
	$pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);

	// project_completion($record);
}

function getRawTendency($values, $indicator) {
    
    $tendency = '';
    
    $percentage = '';
    $evolution = '';

    // we handle multivalues
    // if there is a previous value
    if($indicator['sdii_value_type'] == 'multiple') {
        $data = unserialize($values[0]['sdiv_multivalue']);
        $dataPlusOne = unserialize($values[1]['sdiv_multivalue']);
        
        if($indicator['sdii_nature'] == 'quantitative') {

            if($indicator['sdii_multiple_type'] == 'sum')  $cfield = '_total';
            if($indicator['sdii_multiple_type'] == 'mean')  $cfield = '_mean';
            $current_value = $data[0][$cfield];

            if($indicator['sdii_multiple_type'] != 'none' && $dataPlusOne[0][$cfield] != 0  && !is_null($data[0][$cfield]) && !is_null($dataPlusOne[0][$cfield]))  {
                $percentage = ($data[0][$cfield] - $dataPlusOne[0][$cfield]) / $dataPlusOne[0][$cfield] * 100;
                $evolution = ' (' . round($percentage, 0) . '%)';
                $pvalue = $dataPlusOne[0][$cfield];
            } else {
                $evolution = '';
                $pvalue = empty_nc('');
            }


        }
        // @todo fix bug d'affichage UTF-8 avec ' 🡽   🢆  🡺'
//         if ($data[0][$cfield] > $dataPlusOne[0][$cfield]) {
//             $tendency.="<img src=\"" .ADMIN_THEME_URL. "images/ico_asc.png\" />". sprintf(_t('dashboard','previous_value'), fnumber_format($dataPlusOne[0][$cfield], 'auto', false)).$evolution;
//             //$tendency.= ' 🡽 '. sprintf(_t('dashboard','previous_value'), fnumber_format($dataPlusOne[0][$cfield], 'auto', false)).$evolution;
//         } elseif($data[0][$cfield] < $dataPlusOne[0][$cfield]) {
//             $tendency.="<img src=\"" .ADMIN_THEME_URL. "images/ico_desc.png\" />". sprintf(_t('dashboard','previous_value'), fnumber_format($dataPlusOne[0][$cfield], 'auto', false)).$evolution;
// //             $tendency.= ' 🢆 '. sprintf(_t('dashboard','previous_value'), fnumber_format($dataPlusOne[0][$cfield], 'auto', false)).$evolution;
//         } else {
//             $tendency.="<img src=\"" .ADMIN_THEME_URL. "images/ico_stable.png\" />". sprintf(_t('dashboard','previous_value'), fnumber_format($dataPlusOne[0][$cfield], 'auto', false)).$evolution;
// //             $tendency.= ' 🡺 '.sprintf(_t('dashboard','previous_value'), fnumber_format($dataPlusOne[0][$cfield], 'auto', false));
//         }
        if(!is_null($data[0][$cfield]) && !is_null($dataPlusOne[0][$cfield])) {
            $tendency .= sprintf(_t('dashboard', 'previous_value'), fnumber_format($pvalue, 'auto', false)) . $evolution;
        }
        
        // we handle simple values
        // if there is a previous value
    } elseif(isset($values[1]['sdiv_value'])) {

        if(is_null($values[1]['sdiv_value'])) $previous_value = _t('dashboard','no_data');
        else $previous_value = fnumber_format($values[1]['sdiv_value'], 'auto', false);
        
        if($indicator['sdii_nature'] == 'quantitative') {
			if($values[1]['sdiv_value'] != 0 && !is_null($values[1]['sdiv_value']) && !is_null($values[0]['sdiv_value'])) {
				$percentage = ($values[0]['sdiv_value'] - $values[1]['sdiv_value']) / $values[1]['sdiv_value'] * 100;
				$evolution = ' ('.round($percentage, 0). '%)';
			}  else {
	  	        $evolution = ' '. empty_nc('');
	  	    }

            
        } else {
            
            $a = getBooleanValues($indicator);
            if($a) {
                $index = array();
                foreach ($a as $key => $value) {
                    array_push($index, $key);
                }
                $previous_value = $a[$values[1]['sdiv_value']];
            }
        }
        // @todo fix bug d'affichage UTF-8 avec ' 🡽   🢆  🡺'
//         if ($values[0]['sdiv_value'] > $values[1]['sdiv_value']) {
//             $tendency.="<img src=\"" .ADMIN_THEME_URL. "images/ico_asc.png\" />".sprintf(_t('dashboard','previous_value'), fnumber_format($previous_value, 'auto', false)).$evolution;
// //             $tendency.= ' 🡽 '. sprintf(_t('dashboard','previous_value'), fnumber_format($previous_value, 'auto', false)).$evolution;
//         } elseif($values[0]['sdiv_value'] < $values[1]['sdiv_value']) {
//             $tendency.="<img src=\"" .ADMIN_THEME_URL. "images/ico_desc.png\" />". sprintf(_t('dashboard','previous_value'), fnumber_format($previous_value, 'auto', false)).$evolution;
// //             $tendency.= '🢆 '. sprintf(_t('dashboard','previous_value'), fnumber_format($previous_value, 'auto', false)).$evolution;
//         } else {
//             $tendency.="<img src=\"" .ADMIN_THEME_URL. "images/ico_stable.png\" />". sprintf(_t('dashboard','previous_value'), fnumber_format($previous_value, 'auto', false)).$evolution;
// //             $tendency.= ' 🡺 '.sprintf(_t('dashboard','previous_value'), fnumber_format($previous_value, 'auto', false));
//         }
        $tendency .= sprintf(_t('dashboard','previous_value'), fnumber_format($previous_value, 'auto', false)).$evolution;
        // finally, if any null value we don't display tendency
        if(!is_null($values[0]['sdiv_value']) && !is_null($values[1]['sdiv_value'])) $tendency = sprintf(_t('dashboard', 'previous_value'), fnumber_format($previous_value, 'auto', false));
        }

       return sprintf('<div class="dashboard-indicator-tendency">%s</div>', $tendency);
}

function getRawIndicatorRecord($scale_id, $indicator) {
    
    include_once('../dashboard/common.php');

    $extraclass ='';
    
    if($indicator['sdii_type'] != 'not-set') $typecontent = ' <span class="indic-type '.$indicator['sdii_type'].'">['.formatText(mb_ucfirst($GLOBALS['lang']['sdi']['select_type'][$indicator['sdii_type']]), '2HTML').']</span>'; else $typecontent='';
    
    $req_sdiav=SQL_getAllValue("SCA", $scale_id, $indicator['sdii_id']);
    $result_value = $GLOBALS['sql_object']-> DBSelect($req_sdiav);
    
    // if not values yet we return empty string
    if(!is_array($result_value)) return '';

        // we handle multivalues
    if ($indicator['sdii_value_type'] == 'multiple') {
        $data = unserialize($result_value[0]['sdiv_multivalue']);
        if($indicator['sdii_multiple_type'] == 'sum')  $cfield = '_total';
        if($indicator['sdii_multiple_type'] == 'mean')  $cfield = '_mean';
        if($indicator['sdii_multiple_type'] == 'none')  $cfield = '_none';
        if(is_null($data[0][$cfield])) {
            $current_value =  _t('dashboard', 'no_data');
            $extraclass = " nodata";
        }
        else $current_value = fnumber_format($data[0][$cfield], 'auto', false);
        if($indicator['sdii_multiple_type'] == 'none')  {
            $current_value = _t('sdi', 'multiple_type_none');
            $extraclass = " nonetype";
        }
        // we handle simple values
    } else {
        $a = getBooleanValues($indicator);

        if ($a && ($indicator['sdii_nature'] == 'boolean' || $indicator['sdii_nature'] == 'qualitative')) {
            $current_value = $a[$result_value[0]['sdiv_value']];
        } else {
            if(is_null($result_value[0]['sdiv_value'])) {
                $current_value =  _t('dashboard', 'no_data');
                $extraclass = " nodata";
            }
            else $current_value = fnumber_format($result_value[0]['sdiv_value'], 'auto', false);
        }
    }
    
    $str  = '<tr nobr="true">';
    $str .= '<td class="bb value">';
    $str .= '<span class="currentvalue'.$extraclass.'">'.$current_value.'</span> ';
    $str .= '<span class="unit">'.formatText($indicator['sdii_unit']).'</span>';
    $str .= '<span class="tendency">'. getRawTendency($result_value, $indicator) .'</span>';
    $str .= '</td>';
    
    $str .= '<td class="bb year currentyear">';
    if(isset($result_value[0])) {
        $arr = array_reverse($result_value);
        $lastval = end($arr);
        $lastyear = get_year($lastval['date_p']);
        $str .= '<div class="indicator-last-date">' . $lastyear . '</div>';
    }
    $str .= '</td>';
    $str .= '<td class="bb name currentname">'. formatText($indicator['sdii_name'], '2HTML') . $typecontent .'</td>';
    $str .= '</tr>';
    
    return $str;
}

function project_associated_indicators_values($record)
{
    global $pdf;
    
    $result_sdi = $GLOBALS['sql_object']->DBSelect(SQL_getProjectSdiValues($record['project_id']));
    
    $scale_id = 1; // scale id value
    
    // we exit if no associated indicators
    if(!is_array($result_sdi)) return false;
    
    $ordered_indics = array();
    // we prepare ordered data if given
    // 1 - first data stored in $orderedIndicators, then all data
    $tmp = unserialize($record['project_indic_order']);
    if(is_array($tmp)) {
        foreach($tmp as $k => $v) {
            if(is_integer($k)) array_push($ordered_indics, $k); // to be sure it is not empty
        }
    }
    // 2 - then, we iterate on all indicators thare are not already in $ordered_indics
    foreach($result_sdi as $sdi) {
        if($sdi['sdii_statut'] == 'P' && !in_array($sdi['sdii_id'], $ordered_indics)) array_push($ordered_indics, $sdi['sdii_id']); // to be sure it is not empty
    }
    
    $indicators = '';
    $indicators_array = [];
    foreach($ordered_indics as $k => $v) {
        
        // we search for the key of searched element : $j
        // then we display the full record
        $j = array_search($v, array_column($result_sdi, 'sdii_id')); 
        if(!in_array($j, $indicators_array)) $indicators .= getRawIndicatorRecord($scale_id, $result_sdi[$j]);
        array_push($indicators_array, $j);
    }
    
    // we exit again if no associated values 
    if(empty($indicators)) return false;
    
    ParagraphBreak();
    $out_indic_item = formatText(mb_ucfirst(strip_tags(_t('project','sdi'))));
    // $pdf->Bookmark($out_cal_item, ($bookmark_level), -1);
    project_format_item($out_indic_item);
    $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
    
    $tbl = '<style>
			table {
  			   border:1px solid #E2E2E2;
				color:#777777;
  		    }
            .tendency {color:#bcbcbc;}
            .unit {
                font-weight:bold;
                color:#738ace;
            }
            .indic-type {color:#bcbcbc;
				font-size:7pt;
                font-weight:normal;
            }
            .currentyear {font-weight:bold;color:#bcbcbc}
            .currentvalue {
                color:#738ace;
				font-size:16pt;
                font-weight:bold;
            }
            .nodata {
                color:#eab86a;
                font-size:11pt;
            }
            .nonetype {
                color:#b3b3b3;
                font-size:11pt;
            }
            .currentname {
                color:#738ace;
				font-size:10pt;
                font-weight:bold;
            }

			.header {
				color:#777777;
				background-color:#E2E2E2;
				font-size:7pt;
			}
            .value {
				width:28%;
			}
            .year {
				width:8%;
			}
            .name {
				width:64%;
                text-align:left;
			}
    		  td.br {
    		    	border-right:1px solid #E2E2E2;
    		  }
              td.bb {
    		    	border-bottom:1px solid #E2E2E2;
    		  }
			td {
				text-align:center;
			}
			</style>
      <table cellspacing="0" cellpadding="5" nobr="false">
          <tr nobr="true">
              <td class="header value">' .mb_ucfirst(_t('dashboard', 'numeric_value')).'</td>
              <td class="header year">'.mb_ucfirst(_t('dashboard', 'year')).'</td>
              <td class="header name">'.mb_ucfirst(_t('dashboard', 'label_value')).'</td>
          </tr>
          '. $indicators .'              
      </table>';
    
    
    $pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
    $pdf->writeHTML($tbl, true, false, false, false, '');
    $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
    
}

/**
 * project_associated_indicators()
 * Affiche la liste des indicateurs associés
 *
 * @param int $record
 * @return bool true
 * @todo remove ? 
 */
function project_associated_indicators($record, $bookmark_level)
{
	global $pdf;
	
	$query = SQL_getProjectSdi($record['project_id']);
	$data = $GLOBALS['sql_object']->DBSelect($query);
	
	$pdf->setListIndentWidth(20); //  margin-left not implemented into tcpdf yet
	
	if(isset($data[0]['sdii_id'])) {
	    
	    ParagraphBreak();
	    $out_indicators_item = formatText(mb_ucfirst(strip_tags(_t('project','sdi'))));
	    // $pdf->Bookmark($out_indicators_item, $bookmark_level, -1);
	    project_format_item($out_indicators_item);
	    $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
	    
// 	  $sdi_list='<ul style="margin-left:10%;">'; //  margin-left not implemented into tcpdf yet
// 	  foreach ($data as &$value) {
// 	    $sdi_list.= '<li>'.formatText($value['sdii_name'], '2HTML').'</li>'.PHP_EOL;
// 	  }
// 	  $sdi_list.='</ul>';
	  
// 	  $pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
// 	  $pdf->writeHTML(empty_nc($sdi_list), true, false, false, false, '');
// 	  $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
	  
	  ParagraphBreak();
	  
	}  // else $sdi_list = mb_ucfirst(_t('divers','none'));

	

	return true;
}

/**
 * project_associated_dashboard()
 * Affiche l'image des dernières valeurs des indicateurs
 *
 * @param int $record
 * @return bool true
 */
function project_associated_dashboard($record)
{
	global $pdf;
	
	if(file_exists(SITE_PATH. 'tmp/report/project-'.$record['project_id'].'-dashboard.png')) {
		$pdf->Image(SITE_PATH. 'tmp/report/project-'.$record['project_id'].'-dashboard.png',$pdf->GetX(), $pdf->GetY(), 160, 0, '', '', 'M', false, 0, 'C');
		$pdf->SetY($pdf->GetY() + DOC_INTERVAL);
	}

	return true;
}

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

	// ParagraphBreak();
	
	$complement = '<span class="label">' . mb_ucfirst(strip_tags(_t('project', 'statut'))). ' : </span>' . display_statut($record['project_statut']);
	
	
	$complement .= '<span class="separator"> / </span><span class="label">' . mb_ucfirst(strip_tags(_t('project', 'priority'))). ' : </span>' .$record['priority_name'] ;
	
	($record['scale_id'] != 0 ) ? $complement .=  '<span class="separator"> / </span><span class="label">' .mb_ucfirst(strip_tags(_t('project', 'scale'))). ' : </span>' .$record['scale_denomination'] : '';

	$tbl = '<style>
			.complement {
				color:#444444;
				font-size:8pt;
				text-align:right;
			}
			span.label, span.separator {
				color:#777777;
				font-weight:bold,
				}	
			</style>
			<div class="complement">'.$complement.'</div>
      ';

	$pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
	$pdf->writeHTML($tbl, true, false, false, false, '');
	$pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);

	return true;
}

/**
 * project_completion()
 * Affiche un indcateur de progression de l'action
 *
 * @param int $record
 * @return bool true
 * @todo complete - it dose not work yet ... not used
 */
function project_completion($record)
{
	global $pdf;

	ParagraphBreak();

	$totalwidth = 700;
	$currentwidth = $record['project_completed'] * $totalwidth / 100 ;


	$tbl = '<style>
			td.value {
		    	width:70%;
		  }
		  td.label {
		    	width:30%;
		  }
			td {
		    	text-align:left;
		  }
			</style>
      <table cellspacing="0" cellpadding="0" nobr="true">
          <tr>
              <td class="label">'.mb_ucfirst(strip_tags(_t('project','progression'))) .' : </td>
              <td class="value" style="background-color:#E5E5E5"><div style="width:'.$currentwidth.'px;background-color:#FCA874;display:block;color:white;text-align:right;">' . $record['project_completed'] . ' % </div></td>
          </tr>
      </table>';

	$pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
	$pdf->writeHTML($tbl, true, false, false, false, '');
	$pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);

	return true;
}


/**
 * project_display_steering_budget()
 * Affiche les tableaux contenant information 'animation / comité de pilotage'
 * et budget
 *
 * @param int $record
 * @return bool true
 */
function project_display_steering_budget($record, $bookmark_level, $columns = 2)
{
    global $pdf;
    
    ParagraphBreak();
    //$pdf->Bookmark(_t('project','steering_title'), $bookmark_level, -1);
    //$pdf->Bookmark(_t('project','budget_title'), $bookmark_level, -1);
    $pdf->SetX($pdf->GetX());
    
    $coordinator = getAssociatedActors($record['project_id'], 'coordinator');
    $partners = getAssociatedActors($record['project_id'], 'partner');
    $manager = getAssociatedManagers($record['project_id']);
    
    // do not display anything if fields are empty
    if(empty($current_record['project_elected']) &&  empty($coordinator) && empty($manager) && empty($partners) && empty($current_record['project_team']) && empty($current_record['project_budget']) && empty($current_record['project_budget_comment'])) return true;
    
    
    empty($manager) ? $tbl_manager = '' : $tbl_manager = '<p><span class="label">'. mb_ucfirst(strip_tags(_t('project','manager'))) . ' : </span>' . empty_nc($manager) . '</p>';
    empty($coordinator) ? $tbl_coordinator = '' : $tbl_coordinator = '<p><span class="label">'. mb_ucfirst(strip_tags(_t('project','coordinator'))) . ' : </span>' . empty_nc($coordinator) . '</p>';
    empty($partners) ? $tbl_partners = '' : $tbl_partners = '<p><span class="label">'. mb_ucfirst(strip_tags(_t('project','partners'))) . ' : </span>' . empty_nc($partners) . '</p>';
    empty($record['project_elected']) ? $tbl_elected = '' : $tbl_elected = '<p><span class="label">'. mb_ucfirst(strip_tags(_t('project','elected'))) . ' : </span>' . empty_nc($record['project_elected']) . '</p>';
    empty($record['project_team']) ? $tbl_team = '' : $tbl_team = '<p><span class="label">'. mb_ucfirst(strip_tags(_t('project','team'))) . ' : </span>' . empty_nc(fixImageWidth(rmUnwantedTags($record['project_team']))) . '</p>';
    
    empty($record['project_budget']) ? $tbl_budget = '' : $tbl_budget = '<p><span class="label">'.  mb_ucfirst(strip_tags(_t('project','budget'))) . ' : </span>'.  empty_nc(fnumber_format($record['project_budget'],0, false)) . '</p>';
    empty($record['project_budget_comment']) ? $tbl_budgetc = '' : $tbl_budgetc = '<p><span class="label">'.  mb_ucfirst(strip_tags(_t('project','budget_comment'))) . ' : </span></p><div>' . empty_nc(fixImageWidth(rmUnwantedTags($record['project_budget_comment']))) . '</div>';
    
    if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $tbl_team = removeDomElement('img', $tbl_team);
    if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $tbl_budgetc = removeDomElement('img', $tbl_budgetc);
    
    $style = '<style>
            table {
  			   border:1px solid #D1EDFF;
  		    }
			.light {
				border-top:1px solid #444444;
			}
            p {padding:0 1em;}
			td {
		    	text-align:left;
		    }
            .header {	
				color:#283486;
				background-color:#D1EDFF;
                border-top:1px solid #D1EDFF;
                border-bottom:1px solid #D1EDFF;
				font-size:10pt;
                text-align:center;
				font-weight:bold;
			}
    		  td.br {
    		    	border-right:1px solid #D1EDFF;
    		  }
			.title {
                text-align:center;
				font-weight:bold;
				color:#444444;
                background-color:#D1EDFF;
			}
			span.label {
				color:#777777;
				font-weight:bold,
				}

			</style>';
    
    // if 2 columns format, we generate one table only
      $table_2columns = '<table cellspacing="0" cellpadding="10">
          <tr>
              <td class="header br">'.strtoupper(mb_ucfirst(strip_tags(_t('project', 'steering_title')))).'</td>
              <td class="header">'.strtoupper(mb_ucfirst(strip_tags(_t('project', 'budget_title')))).'</td>
          </tr>
        <tr>
        	<td class="br">
              		<!-- Steering -->

              				' . $tbl_elected . '
              				' . $tbl_coordinator . '
              				' . $tbl_manager . '
              				' . $tbl_partners . '
              				' . $tbl_team . '
           </td>
           <td>
              			<!-- Budget -->
                            ' . $tbl_budget . '
                            ' . $tbl_budgetc . '
           </td>
              				    
      	</tr>
      </table>';
      
      // if 1 column only format, we generate 2 separate tables
      $table_1column = '<table cellspacing="0" cellpadding="10" nobr="false">
          <tr nobr="true">
              <td class="header">'.strtoupper(mb_ucfirst(strip_tags(_t('project', 'steering_title')))).'</td>
          </tr>
        <tr>
        	<td>
              		<!-- Steering -->
                  
              				' . $tbl_elected . '
              				' . $tbl_coordinator . '
              				' . $tbl_manager . '
              				' . $tbl_partners . '
              				' . $tbl_team . '			    
           </td>                              
      	</tr>
      </table><p>&nbsp;</p>
      <table cellspacing="0" cellpadding="10" nobr="false">>
          <tr nobr="true">
              <td class="header">'.strtoupper(mb_ucfirst(strip_tags(_t('project', 'budget_title')))).'</td>
          </tr>
        <tr>
           <td>
              			<!-- Budget -->
                            ' . $tbl_budget . '
                            ' . $tbl_budgetc . '                    
           </td>
                                
      	</tr>
      </table>';
    
    $pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
    if($columns == 2) $pdf->writeHTML($style . $table_2columns, true, false, false, false, '');
    else $pdf->writeHTML($style . $table_1column, true, false, false, false, '');
    $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
    
    return true;
}


function project_display_parent($name)
{
	global $pdf;
	
	$converted =  \Soundasleep\Html2Text::convert($name);
	$out_parent = formatText($converted) . PHP_EOL;
	$out_parent_item = formatText(mb_ucfirst(strip_tags(_t('project', 'parent'))));
	// $pdf->Ln();
	$pdf->ImageSVG($file=THEME_ADMIN_PATH.'images/upper-left-arrow.svg', $x=$pdf->GetX()+1, $y=$x=$pdf->GetY(), $w='', $h=3, $link='', $align='', $palign='', $border=0, $fitonpage=false);
	// workaround to handle positionning
	$pdf->writeHTML('<div style="font-size: 8pt;color:#888888"><span style="font-size: 8pt;color:#ffffff">___</span><strong>'. $out_parent_item . '</strong> : '  . $out_parent . '</div>', true, 0, true, true);
	$pdf->Ln();
	

}

function project_display_finalities($finalities)
{
    global $pdf;
    
    
    $style='<style>;
            li, ul {
                list-style-type: none;
            }
            ul {margin:0px;padding:0px;}
            </style>';
    
    $pdf->SetY($pdf->GetY()-(DOC_INTERVAL*2)-2); // workaround to prevent extra space - not able to remove margin with css
    $pdf->writeHTML($style.'<div>'. $finalities . '</div>', true, 0, true, true);
    $pdf->SetY($pdf->GetY()-(DOC_INTERVAL*2)); // workaround to prevent extra space - not able to remove margin with css
    
    
}

/**
 * project_display_level()
 * display root level as chapter
 * @param string $level
 */
function project_display_level($level, $bookmark_level)
{
    
    global $report_settings;
    global $extraCSS;
    global $pdf;
    
    if(!defined('EXPORT_NOLEVELLABEL') || EXPORT_NOLEVELLABEL == 0) $level_label = $level['level_label'].' : ';
    else $level_label = '';
    
    if($level['level_parent'] == 0) {
        $pdf->writeHTML('<br pagebreak="true" />');
        ParagraphBreak();
        $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+8);
        $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
    } else {
        $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+4);
        $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
    }
    
    $pdf->Bookmark(mb_ucfirst($level_label . $level['level_name']), $bookmark_level, -1);
    $pdf->MultiCell(0,DOC_HEIGHT,mb_ucfirst($level_label . $level['level_name']),0,'L',0);
    $pdf->SetTextColorArray(getColor('DOC_COLOR'));
    $pdf->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);

    if ($report_settings['firstlevel_description'] === true && $level['level_parent'] == 0) {
        
        ParagraphBreak();
        $converted =  \Soundasleep\Html2Text::convert($level['level_desc_project']);
        $out = formatText($converted) . PHP_EOL;
        if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . '<div style="font-size: 10pt;color:#444444;text-align:justify">'. formatText(rmUnwantedTags(fixImageWidth($level['level_desc_project']))). '</div>', true, false, false, false, 'J');
        else $pdf->MultiCell(0, DOC_HEIGHT, $out, 0, 'J');
        $pdf->writeHTML('<br pagebreak="true" />');
        
    } else {
        ParagraphBreak();
        ParagraphBreak();
    }

    return true;    
}



function project_format_item($libelle)
{
	global $pdf;

	$libelle="        ".$libelle;
	$pdf->SetFont(DOC_POLICE, SDI_ITEM_STYLE, SDI_ITEM_SIZE);
	$pdf->SetTextColorArray(getColor('SDI_ITEM_COLOR'));
	$pdf->MultiCell(0,DOC_HEIGHT,$libelle,0,'L',0);
	$pdf->SetTextColorArray(getColor('DOC_COLOR'));
	$pdf->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
}




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


if(!function_exists('indicator_recursive')) {
    function indicator_recursive($levels, $bookmark_level) {
        
        global $ordered_items;
        global $sdi;
        global $pdf;
        global $report_settings;
        
        $debug = false;
        
        // we retrieve all root levels if not given - when first run
        if($levels === null) {
            $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList(true));
            // we add PDF page, only on individual export
            // to prevent "TCPDF ERROR: Wrong page number on setPage() function: 0" error
            $pdf->addPage();
        }
        
        // if($debug) print_r($levels);
        
        // for each root level ...
        foreach($levels as $l) {
            
            // on affiche ici le nom du thèmes
            // et la description si demandée
            if($debug) echo "<h1>". $l['level_name'] . "</h1><p>". $l['level_desc_dashboard'] . "</p><br /><br />";
            
    //         if ($report_settings['levels'] ==  true) indicator_display_level($l, $bookmark_level, $pdf);
    //         elseif($report_settings['quick_export'] ==  false) $pdf->addPage();
            
            // if there is action related to current level we display them
            // first we prepare them
            $associated_indicators = array();
            foreach($sdi as $indicator) {
                if($indicator['sdii_level'] == $l['level_id']) {
                    if($debug) echo "on affiche l'indicateur ". $indicator['sdii_id'] ." (indic-level-id".$indicator['sdii_level']. ") associé directement à ". $l['level_id']."<br />\n<br />\n";
                    array_push($associated_indicators, $indicator);
                    array_push($ordered_items, $indicator);
                }
            }
            
            // we get children
            $levelschildren = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $l['level_id']);
            if($debug) echo "<h1>----- Here are children -----</h1>";
            if($debug) print_r($levelschildren);
            
            // we display level if they have associated projects or children levels and or we we display empty levels
            if($report_settings['levels'] ==  true && (count($associated_indicators) > 0 || count($levelschildren) > 0 || $report_settings['display_empty_levels'] ===  true)) {
                indicator_display_level($l, $bookmark_level, $pdf);
            } // elseif($report_settings['quick_export'] ==  false) $pdf->addPage();
            
            
            // we display indicator if any
            if(count($associated_indicators) > 0) {
                
                $associated_indicators = sort_indicators($associated_indicators);
                
                foreach($associated_indicators as $ind) indicator_display_by_levels($ind, $bookmark_level);
            }
            
            if(count($levelschildren) > 0 ) indicator_recursive($levelschildren, $bookmark_level+1);
            
        }
        
    }
}


function sort_indicators($indicators) {
    
    // we init values each time we iterate
    $indicator_range = array();
    $indicator_name = array();
    
    // First we prepare multi-sort
    // @see http://php.net/manual/fr/function.array-multisort.php
    foreach ($indicators as $key => $row) {
        $indicator_range[$key] = $row['sdii_range'];
        $indicator_name[$key] = $row['sdii_name'];
    }
    
    array_multisort($indicator_range, SORT_DESC, $indicator_name, SORT_ASC, $indicators);
    
    return $indicators;
    
}

/**
 * indicator_display_level()
 * display root level as chapter
 * @param string $level
 */
if(!function_exists('indicator_display_level')) {
    function indicator_display_level($level, $bookmark_level, $pdf)
    {
        
        global $report_settings;
        global $extraCSS;
    
        if(!defined('EXPORT_NOLEVELLABEL') || EXPORT_NOLEVELLABEL == 0) $level_label = $level['level_label'].' : ';
        else $level_label = '';
        
        if($level['level_parent'] == 0) {
            $pdf->writeHTML('<br pagebreak="true" />');
            ParagraphBreak();
            $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+8);
            $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
        } else {
            $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+4);
            $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
        }
        
        $pdf->Bookmark(mb_ucfirst($level_label . $level['level_name']), $bookmark_level);
        $pdf->MultiCell(0,DOC_HEIGHT,mb_ucfirst($level_label . $level['level_name']),0,'L',0);
        $pdf->SetTextColorArray(getColor('DOC_COLOR'));
        $pdf->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
        
        if ($report_settings['firstlevel_description'] === true && $level['level_parent'] == 0) {
            ParagraphBreak();
            $converted =  \Soundasleep\Html2Text::convert($level['level_desc_dashboard']);
            $out = formatText($converted) . PHP_EOL;
            if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . '<div style="font-size: 10pt;color:#444444;text-align:justify">'. formatText(rmUnwantedTags(fixImageWidth($level['level_desc_dashboard']))). '</div>', true, false, false, false, 'J');
            else $pdf->MultiCell(0, DOC_HEIGHT, $out, 0, 'J');
            $pdf->writeHTML('<br pagebreak="true" />');
            
        } else {
            ParagraphBreak();
            ParagraphBreak();
        }
        
        return true;
    }
}


/**
 * indicator_display_by_levels()
 * Affiche les infos générales d'un indicateur
 *
 * @param int $pointer
 * @return bool true
 */
if(!function_exists('indicator_display_by_levels')) {
    function indicator_display_by_levels($indicator, $bookmark_level)
    {
        
        
        global $report_settings;
        global $extraCSS;
        global $pdf;
        
        $current_record = $indicator;
        if(defined('EXPORT_LOG') && EXPORT_LOG == 1) file_put_contents('../tmp/export-logs/pdf-indicators.txt', $current_record['sdii_id']."\n", FILE_APPEND);
        
        // we override dynamic $bookmark_level
        if($report_settings['levels'] ==  false) $bookmark_level = -1;
    
        
        indicator_display_main($current_record, $bookmark_level);
        indicator_display_values($current_record['sdii_id'], $bookmark_level);
        if ($report_settings['display_provider'] === true) indicator_display_provider($current_record, $bookmark_level);
        if ($report_settings['display_reglementation'] === true) indicator_display_rules($current_record, $bookmark_level);
        if ($report_settings['display_evaluation'] === true) indicator_display_assessment($current_record, $bookmark_level);
            
        
        // we add page only if this is not a quick export
        if($report_settings['quick_export'] === false) $pdf->addPage();
        
        return true;
    }
}

function display_orphan_indicators ($bookmark_level) {
    
    global $ordered_items;
    global $sdi;
    global $pdf;
    global $report_settings;
    
    $associated_indicators = array();
    foreach($sdi as $i) {
        if($i['sdii_level'] == 0) {
            array_push($associated_indicators, $i);
            array_push($ordered_items, $i);
        }
    }
    
    if(count($associated_indicators) < 1) return false;
    
    if($report_settings['levels'] ==  true) {
        $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+8);
        $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
    } else {
        $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE+4);
        $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
    }
    
    
    if ($report_settings['levels'] ==  true) {
        // chapter title
        $out_title = formatText(mb_ucfirst(_t('report', 'no-first-level')));
//         $pdf->SetTextColorArray(getColor('SDI_TITLE_COLOR'));
//         $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
        $pdf->Bookmark(mb_ucfirst($out_title), $bookmark_level);
        $pdf->Write(DOC_HEIGHT, $out_title);
        ParagraphBreak();
        ParagraphBreak();
    }
    
    $associated_indicators = sort_indicators($associated_indicators);
    foreach($associated_indicators as $ind) indicator_display_by_levels($ind, $bookmark_level, $pdf);
    
    return true;
}


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

//   $pdf->AddPage();
//   // lien interne si actif
//   if ($report_settings['summary'] === true) $pdf->SetLink($pointer+1);
//   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]);

//   return true;
// }


function indicator_format_item($libelle)
{
  global $pdf;

  $libelle="        ".$libelle;
  $pdf->SetY($pdf->GetY() + 6);
  $pdf->SetFont(DOC_POLICE, SDI_ITEM_STYLE, SDI_ITEM_SIZE);
  $pdf->SetTextColorArray(getColor('SDI_ITEM_COLOR'));
  $pdf->MultiCell(0,DOC_HEIGHT,$libelle,0,'L',0);
  $pdf->SetTextColorArray(getColor('DOC_COLOR'));
  $pdf->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
}

function indicator_format_indic($libelle)
{
  global $pdf;

  $pdf->SetFillColorArray(getColor('BCKG_INFO'));
  $pdf->SetFont(DOC_POLICE, SDI_INFO_STYLE, SDI_INFO_SIZE+1);
  $pdf->SetTextColorArray(getColor('SDI_INFO_COLOR'));
  $pdf->MultiCell(0,DOC_HEIGHT+3,'   '.$libelle,0,'L',1, 1, '', '', true, 0, false, true, DOC_HEIGHT+3, 'M');
//   $pdf->SetLineStyle(array('color'=> array(100,100,100)));
//   $pdf->Line($pdf->GetX(), $pdf->GetY(), $pdf->GetX()+180, $pdf->GetY());
  $pdf->SetTextColorArray(getColor('DOC_COLOR'));
  $pdf->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
  $pdf->Ln(DOC_INTERVAL);
}

// Saut de paragraphe
function ParagraphBreak()
{
  global $pdf;

  $pdf->SetTextColorArray(getColor('DOC_COLOR'));
  $pdf->SetFont(DOC_POLICE,DOC_STYLE,DOC_SIZE);
  $pdf->Ln(PARAGRAPH_BREAK);
}

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

  // titre d'un indicateur
  $out_title = formatText($record['sdii_name']);
  $pdf->SetTextColorArray(getColor('SDI_TITLE_COLOR'));
  $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
  $pdf->Bookmark(mb_ucfirst(strtolower($out_title)), $bookmark_level+1);
  $pdf->Write(DOC_HEIGHT, $out_title);
  
  // affichage du type si existant
  if($record['sdii_type'] != 'not-set') {

     $pdf->SetXY($pdf->GetX()+3, $pdf->GetY()+1);
     if($record['sdii_type'] == 'state') $out_type = ' <span style="background-color:pink; color: rgb(255, 255, 255);font-size:11px;">&nbsp;'.mb_ucfirst($GLOBALS['lang']['sdi']['select_type'][$record['sdii_type']]).'&nbsp;</span>';
     if($record['sdii_type'] == 'follow-up' || $record['sdii_type'] == 'pressure') $out_type = ' <span style="background-color: #87d9ba; color:#4f8872;font-size:11px;">&nbsp;'.mb_ucfirst($GLOBALS['lang']['sdi']['select_type'][$record['sdii_type']]).'&nbsp;</span>';
     if($record['sdii_type'] == 'achievement' || $record['sdii_type'] == 'response') $out_type = ' <span style="background-color:#bfa8d5; color:#595a9f;font-size:11px;">&nbsp;'.mb_ucfirst($GLOBALS['lang']['sdi']['select_type'][$record['sdii_type']]).'&nbsp;</span>';
     $pdf->WriteHTML($out_type, true, false, true, false, '');
    }
    
  // si non publié
  if ($record['sdii_statut'] == 'D') {
    $pdf->SetTextColorArray(getColor('DOC_ADVISE_COLOR'));
    $pdf->SetFont(DOC_POLICE, '', SDI_TITLE_SIZE);
    $out_status = ' / ' . strtolower(_t('statut', 'draftpdf'));
    $pdf->Write(DOC_HEIGHT, $out_status);
    $pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
    $pdf->SetTextColorArray(getColor('DOC_COLOR'));
  }
  // si non attaché au tableau de bord
  if ($record['sdii_to_dashboard'] == 'Y') {
  	$pdf->SetTextColorArray(getColor('DOC_ADVISE_COLOR'));
  	$pdf->SetFont(DOC_POLICE, '', SDI_TITLE_SIZE);
  	$out_attached_to_dashboard = ' (' . strtolower(_t('sdi','attached_to_dashboard').')');
  	$pdf->Write(DOC_HEIGHT, $out_attached_to_dashboard);
  	$pdf->SetFont(DOC_POLICE, SDI_TITLE_STYLE, SDI_TITLE_SIZE);
  	$pdf->SetTextColorArray(getColor('DOC_COLOR'));
  }

  $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
  $pdf->SetTextColorArray(getColor('SDI_LEVEL_COLOR'));
  
  $pdf->Ln(DOC_HEIGHT);
  
  // thème d'appartenance
  if ($report_settings['levels'] !==  true) {
      if($record['sdii_level'] == 0) $level_name = mb_ucfirst(_t('sdi', 'no_associated_level'));
      else $level_name = mb_ucfirst($record['level_name']);
      if($record['sdii_level'] != 0 && (!defined('EXPORT_NOLEVELLABEL') || EXPORT_NOLEVELLABEL == 0)) $out_level = formatText('» ' . mb_ucfirst($record['level_label']). ' : ' . $level_name);
      else $out_level = formatText('» ' . $level_name );
      
      // we retrieve root level
      $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
      $a = getLevelParent($levels, $record['level_id'], 0);
      if(is_array($a) && $a['id'] != $record['level_id']) {
          if(!defined('EXPORT_NOLEVELLABEL') || EXPORT_NOLEVELLABEL == 0) $out_level .=  ' / ' .formatText( mb_ucfirst($a['label']) . ' : ' . $a['name']) . PHP_EOL;
          else $out_level .=  ' / ' .formatText($a['name']) . PHP_EOL;
      }
      
      $pdf->SetY($pdf->GetY() + 2);
      $pdf->Write(DOC_HEIGHT, $out_level);
      $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
      $pdf->SetTextColorArray(getColor('DOC_COLOR'));
  }
  
  $pdf->Ln(DOC_HEIGHT);
  
  // description
  $out_desc = formatText(strip_tags($record['sdii_description'])) . PHP_EOL;
  $converted =  \Soundasleep\Html2Text::convert($record['sdii_description']);
  $out_desc = formatText($converted) . PHP_EOL;
  //$pdf->Bookmark(mb_ucfirst(_t('sdi','description')), $bookmark_level+2);
  
  if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $record['sdii_description'] = removeDomElement('img', $record['sdii_description']);
  
  if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($record['sdii_description']))), true, false, false, false, '');
  else $pdf->MultiCell(0, DOC_HEIGHT, $out_desc, 0, 'J');
  
  $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
  // objectif

  if(!empty($record['sdii_goal'])) {
      $converted =  \Soundasleep\Html2Text::convert($record['sdii_goal']);
      $out_goal = formatText(empty_nc($converted)) . PHP_EOL;
      $out_goal_item = formatText(mb_ucfirst(strip_tags(_t('sdi', 'goal'))));
      //$pdf->Bookmark($out_goal_item, $bookmark_level+2);
      indicator_format_item($out_goal_item);
      
      if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $record['sdii_goal'] = removeDomElement('img', $record['sdii_goal']);
      
      if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($record['sdii_goal']))), true, false, false, false, '');
      else $pdf->MultiCell(0, DOC_HEIGHT, $out_goal, 0, 'J');
  }
  
  $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
  // conseil d'amélioration

  if(!empty($record['sdii_consulting'])) {
      $converted =  \Soundasleep\Html2Text::convert($record['sdii_consulting']);
      $out_consulting = formatText(empty_nc($converted)) . PHP_EOL;
      $out_consulting_item = formatText(mb_ucfirst(strip_tags(_t('sdi', 'consulting'))));
      // $pdf->Bookmark($out_consulting_item, $bookmark_level+2);
      indicator_format_item($out_consulting_item);
      
      if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $record['sdii_consulting'] = removeDomElement('img', $record['sdii_consulting']);
      
      if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($record['sdii_consulting']))), true, false, false, false, '');
      else $pdf->MultiCell(0, DOC_HEIGHT, $out_consulting, 0, 'J');
  }
  
  // comment only if EXPLICITLY called
  if(defined('EXPORT_COMMENT') && (stripos(EXPORT_COMMENT, 'indicator') !== false) && !empty($record['sdii_comment'])) {
      // we remove default values entered between {}
      $record['sdii_comment'] = preg_replace('/{[\s\S]+?}/', '', $record['sdii_comment']);
      $converted =  \Soundasleep\Html2Text::convert($record['sdii_comment']);
      $out_comment = formatText(empty_nc($converted)) . PHP_EOL;
      $out_comment_item = formatText(mb_ucfirst(strip_tags(_t('sdi', 'comment'))));
      //$pdf->Bookmark($out_goal_item, $bookmark_level+2);

      if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $record['sdii_comment'] = removeDomElement('img', $record['sdii_comment']);

      if(strlen($out_comment) > 6) {
          indicator_format_item($out_comment_item);
          if (defined('HTML_EXPORT') && HTML_EXPORT == 1) $pdf->writeHTML($extraCSS . formatText(fixImageWidth(rmUnwantedTags($record['sdii_comment']))), true, false, false, false, '');
          else $pdf->MultiCell(0, DOC_HEIGHT, $out_comment, 0, 'J');
      }
      
  }


  // informations de mesure
  $out_mesures_item = formatText(ucfirst(strip_tags(_t('sdi', 'info_mesure'))));
  $out_mesures_behavior = ($record['sdii_threshold_relative'] == 'Y' ? _t('sdi', 'threshold_relative_Y') : _t('sdi', 'threshold_relative_N'));
  $out_mesures_unit = formatText(mb_ucfirst(_t('sdi', 'unit'))) . ' : ' . $record['sdii_unit'] . PHP_EOL;
  // $pdf->Bookmark($out_mesures_item, $bookmark_level+2);
  indicator_format_item($out_mesures_item);
  // unitée de mesure
  $pdf->SetFont(DOC_POLICE, EM_STYLE, MIN_SIZE);
  $pdf->Write(DOC_HEIGHT, $out_mesures_unit . PHP_EOL);
  // comportement
  $pdf->Write(DOC_HEIGHT, mb_ucfirst($out_mesures_behavior) . PHP_EOL);
  $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
  // tableau de valeurs
  indicator_display_mesures($record);
  $pdf->SetFont(DOC_POLICE, EM_STYLE, MIN_SIZE);
  $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
}

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

  global $pdf;
  
  $a = getBooleanValues($record);
  
  // if indicator is boolean or qualitative and mask is defined
  if(($record['sdii_nature'] == 'boolean' || $record['sdii_nature'] == '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)];
  		($record['sdii_threshold_value'] != '' && !is_null($record['sdii_threshold_value'])) ? $display_threshold = $a[$record['sdii_threshold_value']] : $display_threshold = empty_none('');
  	}

  } else {
  	$display_minvalue = empty_nc(fnumber_format($record['sdii_min_value'], 'auto', false));
  	$display_maxvalue = empty_nc(fnumber_format($record['sdii_max_value'], 'auto', false));
  	$display_threshold = empty_none(fnumber_format($record['sdii_threshold_value'], 'auto', false));
  }

  $tbl = '<style>
  	table {
  		border:1px solid #E2E2E2;
  		}
  	.header {
  		color:#777777;
			background-color:#E2E2E2;
  		font-weight:bold;
  		font-size:7pt;
  	}
    td {
    	text-align:center;
  		color:#777777;
    }
  	td.br {
  		border-right:1px solid #E2E2E2;
  		}
	</style>
  <table cellspacing="0" cellpadding="5" border="0" nobr="true">
  <thead>
      <tr>
          <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'min_value'))).'</td>
          <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'max_value'))).'</td>
          <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'initial_threshold_value'))).'</td>
          <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'frequency'))).'</td>
      </tr>
  </thead>
      <tr>
          <td class="br">'.$display_minvalue.'</td>
          <td class="br">'.$display_maxvalue.'</td>
          <td class="br">'.$display_threshold.'</td>
          <td>'.$record['sdii_frequency'].'</td>
      </tr>
  </table>';

  $pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
  $pdf->writeHTML($tbl, true, false, false, false, '');
  $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);

  return true;
}

/**
 * indicator_display_provider()
 * Affiche les informations Fournisseurs d'un IDD
 *
 * @param  $record
 * @return bool true
 */
function indicator_display_provider($record, $bookmark_level)
{
  global $pdf;
  global $extraCSS;
  
  // no information is given, we do not display the section
  if(empty($record['sdip_name']) && empty($record['sdip_service']) && empty($record['sdip_incharge']) && empty($record['sdip_email'])) return true;

  $out_name = formatText($record['sdip_name']);
  if (!empty($record['sdip_service'])) $out_name .= ' - ' . formatText($record['sdip_service']);
  if (!empty($record['sdip_incharge'])) $out_name .= ' - ' . formatText($record['sdip_incharge']) . ' (' . _t('sdi', 'p_incharge') . ')';
  $out_name .= PHP_EOL;
  

  $converted =  \Soundasleep\Html2Text::convert($record['sdip_address']);  
  if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $out_adress = formatText(fixImageWidth(rmUnwantedTags($record['sdip_address'])));
  else $out_adress = formatText(empty_nc($converted)) . PHP_EOL;
  
  if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $out_adress = removeDomElement('img', $out_adress);
  
  $out_phone_fax = mb_ucfirst(strip_tags(_t('sdi', 'p_phone'))) . ' : ' . formatText(empty_nc($record['sdip_phone']));
  $out_phone_fax .= ' - ' . mb_ucfirst(strip_tags(_t('sdi', 'p_fax'))) . ' : ' . formatText(empty_nc($record['sdip_fax'])) . PHP_EOL;
  $out_email_item = mb_ucfirst(strip_tags(_t('sdi', 'p_email'))) . ' : ';
  $out_email = formatText($record['sdip_email']);
  
  empty($out_email) ? $out_email = empty_nc($out_email) : $out_email = '<a href="mailto:'.$out_email.'">'.$out_email.'</a>';
  

  $converted =  \Soundasleep\Html2Text::convert($record['sdip_description']);
  $out_desc = formatText(empty_nc($converted)) . PHP_EOL;
  
  $out_provider_item = formatText(ucfirst(strip_tags(_t('sdi', 'p_title')))) ;

  ParagraphBreak();
  // $pdf->Bookmark($out_provider_item, $bookmark_level+2);
  indicator_format_indic($out_provider_item);

  $tbl = '<style>
  		table {
  			border:none;
            font-weight:normal;
  		}
	    td {
	    	text-align:left;
	    }
	  	.value {
            width:70%;
	  	}
        .label {
            text-align:right;
            width:30%;
            font-style: italic;
        }
      
      
			</style>
      <table cellspacing="0" cellpadding="5" border="0" nobr="true">
          <tr>
              <td class="label"></td>
              <td class="value">'.$out_name.'</td>
          </tr>
          <tr>
              <td class="label"></td>
              <td class="value">'.$out_adress.'</td>
          </tr>';
    
  if(!empty($record['sdip_email'])) $tbl .= '<tr><td class="label"></td><td class="value">'.$out_email.'</td></tr>';
  $tbl .= '</table>';
  

  
  $pdf->writeHTML($tbl, true, false, false, false, '');
  

  
  $pdf->SetY($pdf->GetY() + DOC_INTERVAL);

  return true;
}

/**
 * indicator_display_rules()
 * Affiche la réglementation d'un IDD
 *
 * @param  $record
 * @return bool true
 */
function indicator_display_rules($record, $bookmark_level)
{
  global $pdf;
  global $extraCSS;
  
  // no information is given, we do not display the section
  if(empty($record['sdir_title']) && empty($record['sdir_body']) && empty($record['sdir_mask_uri'])) return true;
  

  $out_name = formatText(empty_nc($record['sdir_title'])) . PHP_EOL;
//    $out_body = formatText(empty_nc(strip_tags($record['sdir_body']))) . PHP_EOL;
  $converted =  \Soundasleep\Html2Text::convert($record['sdir_body']);
  
  if(defined('HTML_EXPORT') && HTML_EXPORT == 1) $out_body = formatText(fixImageWidth(rmUnwantedTags($record['sdir_body'])));
  else $out_body = formatText(empty_nc($converted)) . PHP_EOL;
  
  if(defined('EXPORT_NOIMAGE') && EXPORT_NOIMAGE == 1)  $out_body = removeDomElement('img', $out_body);
  
  $out_uri = formatText($record['sdir_mask_uri']);
  $out_uri_href = $record['sdir_referer_uri'];

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

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

  ParagraphBreak();
  //$pdf->Bookmark($out_reglementation_item, $bookmark_level+2);
  indicator_format_indic($out_reglementation_item);
  
  
  // on prépare le lien
  $out_uri_text =!empty($out_uri_href) ? '<a href="'.$out_uri_href.'">{#}</a>' : empty_nc($out_uri_href);

  // $out_uri_text = !empty($out_uri) ? sprintf($out_uri_text, $out_uri) :sprintf($out_uri_text, $out_uri_href);
  $out_uri_text = !empty($out_uri) ? str_replace('{#}', $out_uri, $out_uri_text) : str_replace('{#}', $out_uri_href, $out_uri_text);
  
  $tbl = '<style>
  		table {
  			border:none;
            font-weight:normal;
  		}
	    td {
	    	text-align:left;
	    }
	  	.value {
            width:70%;
	  	}
        .label {
            text-align:right;
            width:30%;
            font-style: italic;
        }


			</style>
      <table cellspacing="0" cellpadding="5" border="0" nobr="true">
          <tr>
              <td class="label">'.mb_ucfirst($out_name_item).'</td>
              <td class="value">'.$out_name.'</td>
          </tr>
          <tr>
              <td class="label">'.mb_ucfirst($out_body_item).'</td>
              <td class="value">'.fixImageWidth($out_body).'</td>
          </tr>
          <tr>
              <td class="label">'.mb_ucfirst($out_uri_item).'</td>
              <td class="value">'.$out_uri_text .'</td>
          </tr>
     </table>';
  
  $pdf->writeHTML($tbl, true, false, false, false, '');

  $pdf->SetY($pdf->GetY() + DOC_INTERVAL);

  return true;
}

/**
 * indicator_display_assessment()
 * Affiche le tableau de critères d'évaluation
 *
 * @param int $record
 * @return bool true
 */
function indicator_display_assessment($record, $bookmark_level)
{
  global $pdf;
  
  // no information is given, we do not display the section
  if($record['sdie_scale_compare'] == 0 && $record['sdie_fiability'] == 0 && $record['sdie_accessibility'] == 0 && $record['sdie_lisibility'] == 0 && $record['sdie_relevance'] == 0 && $record['sdie_global_performance'] == 0) return true;

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

  ParagraphBreak();
  // $pdf->Bookmark($out_eval_item, $bookmark_level+2);
  indicator_format_indic($out_eval_item);
  $pdf->SetX($pdf->GetX());


  $tbl = '<style>
  		table {
  			border:1px solid #E2E2E2;
  		}
	  	.header {
	  		color:#777777;
				background-color:#E2E2E2;
	  		font-weight:bold;
	  		font-size:7pt;
	  	}
	    td {
	    	text-align:center;
	  		color:#777777;
	    }
	  	td.br {
	  		border-right:1px solid #E2E2E2;
	  		}
			</style>
      <table cellspacing="0" cellpadding="5" border="0" nobr="true">
          <tr>
              <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'e_scale_compare'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'e_fiability'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'e_accessibility'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'e_lisibility'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'e_relevance'))).'</td>
              <td class="header">'.mb_ucfirst(strip_tags(_t('sdi', 'e_global_performance'))).'</td>
          </tr>
        <tr>
        		<td class="br">'.zero_asNC($record['sdie_scale_compare']).'</td>
            <td class="br">'.zero_asNC($record['sdie_fiability']).'</td>
            <td class="br">'.zero_asNC($record['sdie_accessibility']).'</td>
            <td class="br">'.zero_asNC($record['sdie_lisibility']).'</td>
            <td class="br">'.zero_asNC($record['sdie_relevance']).'</td>
            <td class="br">'.zero_asNC($record['sdie_global_performance']).'</td>
      	</tr>
        </tbody>
      </table>';

  $pdf->SetFont(DOC_POLICE, DOC_STYLE, MIN_SIZE);
  $pdf->writeHTML($tbl, true, false, false, false, '');
  $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);

  return true;
}


/**
 * indicator_display_values()
 * Affiche les valeurs d'un IDD.
 *
 * @param int $sdi_id
 * @return bool true
 **/
if(!function_exists('indicator_display_values')) {

	function indicator_display_values($sdi_id, $bookmark_level)
	{
	  global $pdf;
	  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(strip_tags(_t('dashboard', 'all_value')));
	  ParagraphBreak();
	  // $pdf->Bookmark($out_values_item, $bookmark_level+2);
	  indicator_format_indic($out_values_item);

	  $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 $pdf;
  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;
  $margin = 0;
  $pdf->SetX($pdf->GetX() + $margin);
  $pdf->SetFont(DOC_POLICE, EM_STYLE, DOC_SIZE);
  $pdf->Cell(0, DOC_HEIGHT, $message, 0, 1, 'L');
  $pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
  $margin = 10;
  $pdf->SetTextColorArray(getColor('DOC_ADVISE_COLOR'));
  $pdf->SetX($pdf->GetX() + $margin);
  $pdf->MultiCell(0, DOC_HEIGHT, $content, 0, 'L');
  $pdf->SetY($pdf->GetY() + DOC_INTERVAL);
  $pdf->SetTextColorArray(getColor('DOC_COLOR'));

  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
 **/
 if(!function_exists('indicator_display_graphic_values')) {
	function indicator_display_graphic_values($sdi_id, $current_scale, $status, $mode)
	{
		global $pdf;
		global $sql_object;
		global $scale_denomination_array;
		

		include_once(override('../dashboard/graph.php'));
		
		// 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_nature'];
		
		
		$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(defined('CHART_MIN_VALUES') && is_numeric(CHART_MIN_VALUES)) $minChartValues = CHART_MIN_VALUES; else $minChartValues = 2; 

		if (!is_array($values) || count($values) < $minChartValues) 	return false;

		if($indicator_type == 'quantitative') {
		    
		    if(defined('EXPORT_CHART_SVG') && EXPORT_CHART_SVG == 1 && file_exists('../tmp/report/'.$sdi_id.'_'.$current_scale.'.svg')) {
		        $pdf->ImageSVG('../tmp/report/'.$sdi_id.'_'.$current_scale.'.svg', $pdf->GetX(), $pdf->GetY(), round($width), round($height), $link='', $align='', $palign='C', $border=0, $fitonpage='C');
		        
		        // on place le curseur en bas du graphique
		        $pdf->SetY($pdf->GetY() + ($height));
		        return true;
		    }
		        
			
			generateGraphic($sdi_id, $current_scale, $status, 'auto', false, $width, $width, '../tmp/report');
			
			// /////////////////////////////
			// Affichage
		
			// définition du positionnement
			$_y = $pdf->GetY() + 5;
			$_x = 60;
		
			// Affichage du titre de l'échelle s'il n'y en a plus d'un seulement
			if(count($scale_denomination_array) > 1) {
    			$out_scale_item = $scale_denomination_array[$current_scale];
    			//$pdf->Bookmark($out_scale_item, 2, -1);
    			indicator_format_item($out_scale_item);
    			$pdf->SetY($pdf->GetY() + DOC_INTERVAL);
			}
		
			// Affichage de l'image
			$pdf->Image('../tmp/report/'.$sdi_id.'_'.$current_scale.'.png', $_x, $pdf->GetY(), round($width * IMAGE_RATIO), round($height * IMAGE_RATIO));
		
			// on place le curseur en bas du graphique
			$pdf->SetY($pdf->GetY() + ($height * IMAGE_RATIO));
		
		}
		
		if($indicator_type == 'qualitative') {

			$pdf->writeHTML(getQualitativeViz($values, $result_sdii[0], 'short', true, true), true, false, true, false, '');
			$pdf->Ln(5);
		}

		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 $pdf;
	global $sql_object;
	global $scale_denomination_array;

	$values ='';

	// 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'];

    if($result_sdii[0]['sdii_multiple_type'] == 'sum') $cfield = '_total';
    if($result_sdii[0]['sdii_multiple_type'] == 'mean') $cfield = '_mean';

    $sdi_values = $sql_object->DBSelect(SQL_getAllValue($status, $current_scale, $sdi_id));
    $sdi_values = add_cumulative_value($sdi_values, $result_sdii[0]); // we add 'sdiv_cumulative_value' attribute if needed
	

	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($result_sdii[0]['sdii_value_type'] == 'multiple') {

			$data = unserialize($sdi_values[$i]['sdiv_multivalue']);
			$current_value = '<p style="text-align:left;">';

			foreach($data as &$val) {
				$current_value .= '';
				if(!empty($val['label'])) $current_value .= $val['label']. ' : ';
                if(!is_null($val['value'])) $current_value .= fnumber_format($val['value'], 2, false);
                else $current_value .= mb_ucfirst(_t('dashboard', 'no_data'));
                if($result_sdii[0]['sdii_multiple_type'] == 'sum' && !is_null($val['_percentage'])) $current_value .= '<span class="value-percent"> ('.fnumber_format($val['_percentage'], 2, false).' %)</span>';
				$current_value .= '<br />';
			}
			// we display the total if needed
            if($result_sdii[0]['sdii_multiple_type'] == 'sum') {
                if(!is_null($val['_total'])) {
                    $current_value .= '<strong>'. mb_ucfirst(_t('dashboard', 'multivalue_total')) . ' : ' . fnumber_format($data[0]['_total'], 2, false). '</strong>';
                } else {
                    $current_value .= '<strong>'. mb_ucfirst(_t('dashboard', 'multivalue_total')) . ' : ' . mb_ucfirst(_t('dashboard', 'no_data')). '</strong>';
                }
            }
            // we display the mean if needed
            if($result_sdii[0]['sdii_multiple_type'] == 'mean') {
                if (!is_null($val['_mean'])) {
                    $current_value .= '<strong>' . mb_ucfirst(_t('dashboard', 'multivalue_mean')) . ' : ' . fnumber_format($data[0]['_mean'], 2, false) . '</strong>';
                } else {
                    $current_value .= '<strong>' . mb_ucfirst(_t('dashboard', 'multivalue_mean')) . ' : ' . mb_ucfirst(_t('dashboard', 'no_data')) . '</strong>';
                }
            }
			$current_value .= '</p>';

            if($result_sdii[0]['sdii_multiple_type'] == 'none') {
                $firstValue = $lastValue = $year_end = $year_start = 0; // will return empty_nc()
            } else {
                if ($i == 0) {
                    $lastValue = $data[0][$cfield]; // 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][$cfield]; // 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_nature'] == 'boolean' || $result_sdii[0]['sdii_nature'] == 'qualitative') {
				$a = getBooleanValues($result_sdii[0]);
				if($a) {
					$current_value .= $a[$sdi_values[$i]['sdiv_value']];
				} else {
					$current_value .= fnumber_format($sdi_values[$i]['sdiv_value'], 'auto', false);
				}
				 
			} else {
				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(is_null($sdi_values[$i]['sdiv_value'])) {
                    $current_value .= mb_ucfirst(_t('dashboard', 'no_data'));
                } else {
                    $current_value .= fnumber_format($sdi_values[$i]['sdiv_value'], 'auto', false);
                }
			}
			
		}
		 
		// 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_nature'] == 'boolean' || $result_sdii[0]['sdii_nature'] == '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_nature'] == 'boolean' || $result_sdii[0]['sdii_nature'] == 'qualitative') {
				if(!is_null($default_threshold)) $threshold = $a[$default_threshold];
				else $threshold = empty_none('');
			} else {
			    $threshold = empty_none('');
			}
		}
		 
		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(strip_tags($sdi_values[$i]['sdiv_comment'])) .' ('.$comment_status.')<br />';
			$converted =  \Soundasleep\Html2Text::convert($sdi_values[$i]['sdiv_comment']);
			$comments = formatText($converted)  .' ('.$comment_status.')<br />';

		} else {
			$comments = '';
		}
		
		$current_date = formatText($sdi_values[$i]['date_p']);
		$values .= '
		<tr nobr="true">
		<td class="brb">'.$current_value.'</td>
		%s
		<td class="brb">'.$threshold.'</td>
		<td class="brb">'.$current_date.'</td>
		<td class="brb">'.$comments.'</td>
		</tr>';

        // we handle cumulative values
        if($result_sdii[0]['sdii_value_type'] == 'unique' && $result_sdii[0]['sdii_unique_mode'] == 'cumulative') $replace = '<td class="brb">'.formatText(fnumber_format($sdi_values[$i]['sdiv_cumulative_value'], 'auto', false), '2HTML').'</td>';
        else $replace ='';

        $values = str_replace('%s', $replace, $values); // do not use "sprintf($values, $replace);" because the presence of '%" in the string when multivalue will cause issue !
	}


	$tbl = '<style>
		table {
  			border:1px solid #E2E2E2;
  		}
	  .header {
	  		color:#777777;
				background-color:#E2E2E2;
	  		font-weight:bold;
	  		font-size:7pt;
	  	}
	  td {
	    	text-align:center;
	  		color:#777777;
	    }
	  td.brb {
	  		border-right:1px solid #E2E2E2;
				border-bottom:1px solid #E2E2E2;
	  }
    td.comment {
    }
	</style>
	<table cellspacing="0" cellpadding="5">
	<thead>
	<tr>
	<td class="header">'.mb_ucfirst(_t('dashboard', 'name_pluriel')).'</td>
	%s
	<td class="header">'.mb_ucfirst(_t('dashboard', 'threshold_value')).'</td>
	<td class="header">'.mb_ucfirst(_t('statut', 'published_on')).'</td>
	<td class="header">'.mb_ucfirst(_t('sdi', 'comment')).'</td>
	</tr>
	</thead>
	'.$values.'
	</table>';

    // we handle cumulative values
    if($result_sdii[0]['sdii_value_type'] == 'unique' && $result_sdii[0]['sdii_unique_mode'] == 'cumulative') $replace = '<td class="header">'.mb_ucfirst(_t('dashboard','cumulative_value')).'</td>';
    else $replace ='';
    // $tbl = sprintf($tbl, $replace);
    $tbl = str_replace('%s', $replace, $tbl); // do not use "sprintf($values, $replace);" because the presence of '%" in the string when multivalue will cause issue !

	// 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 2 valeurs
	if(defined('CHART_MIN_VALUES') && is_numeric(CHART_MIN_VALUES)) $minChartValues = CHART_MIN_VALUES; else $minChartValues = 2; 
	
	if ($mode != 'TWICE' || (count($sdi_values) >= 1 && count($sdi_values) < $minChartValues)) {
	    
	    // Affichage du titre de l'échelle s'il n'y en a plus d'une seulement
	    if(count($scale_denomination_array) > 1) {
    		$out_scale_item = $scale_denomination_array[$current_scale];
    		//$pdf->Bookmark($out_scale_item, 2, -1);
    		indicator_format_item($out_scale_item);
    		$pdf->SetY($pdf->GetY() + DOC_INTERVAL * 2);
	    }
	}
	
	$pdf->SetFont(DOC_POLICE, DOC_STYLE, ARRAY_DATA_SIZE );
	// Affichage du tableau
	// Affichage de l'astérisque - avertissement
	$pdf->MultiCell(0, DOC_HEIGHT, '* ' . strtolower(_t('statut', 'draftpdf')), 0, 'R', 0);
	$pdf->writeHTML($tbl, true, false, false, false, '');
	// affichage des taux
	if($result_sdii[0]['sdii_nature'] == 'quantitative') {
		$rates = getRates($firstValue, $lastValue, $year_start, $year_end, 'txt');
		$pdf->MultiCell(0, DOC_HEIGHT, $rates, 0, 'L', 0);
	}	
	
	$pdf->SetFont(DOC_POLICE, DOC_STYLE, DOC_SIZE);
	$pdf->Ln(DOC_INTERVAL);
		
	return true;
}

?>
