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

// https://github.com/PHPOffice/PHPWord

// http://endmemo.com/convert/topography.php
define('PAGE_WIDTH', 9070); // in twips
define('FONT_SIZE_MIN', 9);
// define('WORD_DEFAULT_FONT', 'Times New Roman');
define('DOC_DEFAULT_FONT', 'Tahoma');
define('DOC_HEADER_FONT', 'Arial');
define('DOC_DEFAULT_SIZE', 10);
define('ARRAY_HEADER_BG', 'D8D7D7');


# bench start tag
$start_time=getmicrotime();


// Code for phpWord 0.18.3 version
// https://github.com/PHPOffice/PHPWord/releases/tag/0.18.3

if(defined('WORDEXPORT_ESCAPE') && WORDEXPORT_ESCAPE == 1) PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
else PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(false);

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->setDefaultFontName(DOC_DEFAULT_FONT);
$phpWord->setDefaultFontSize(DOC_DEFAULT_SIZE);

// @todo fix : get page numbers in TOC
$phpWord->getSettings()->setUpdateFields(true);

// Adding document properties
$properties = $phpWord->getDocInfo();
$properties->setCreator('Linea21 '. LINEA_VERSION);
$properties->setCompany(SITE_NAME);
$properties->setTitle($report_settings['title']);
$properties->setLastModifiedBy($report_settings['author'] . ' - ' .$report_settings['mail_author']);
$properties->setCreated(time());
$properties->setModified(time());
$properties->setSubject($report_settings['title']);


$phpWord->addFontStyle('defaultF', array());
$phpWord->addFontStyle('noValueFor', array('bold' => true, 'color'=>'1B2232'));
$phpWord->addFontStyle('arrayValue', array('size' => FONT_SIZE_MIN));
$phpWord->addFontStyle('arrayheader', array('size' => FONT_SIZE_MIN, 'bold' => true, 'color'=>'666666'));
$phpWord->addFontStyle('percentageValue', array('size' => FONT_SIZE_MIN, 'color'=>'666666'));
$phpWord->addFontStyle('attachedTheme', array('size' => DOC_DEFAULT_SIZE - 1, 'color'=>'355C6B', 'bold' => true));
$phpWord->addFontStyle('softLabel', array('color'=>'848484'));
$phpWord->addFontStyle('softLabelMin', array('size' => FONT_SIZE_MIN, 'color'=>'848484'));
$phpWord->addFontStyle('softMinBold', array('size' => FONT_SIZE_MIN, 'color'=>'848484', 'bold' => true));
$phpWord->addFontStyle('strongLabel', array('color'=>'848484', 'bold' => true));
$phpWord->addFontStyle('list', array('marginLeft'=>'2'));
$phpWord->addParagraphStyle('align-right', array('align' => 'right', 'keepLines' => true));
$phpWord->addParagraphStyle('align-justify', array('align' => 'both', 'keepLines' => true));
$phpWord->addParagraphStyle('defaultP', array('align' => 'left', 'keepLines' => true));

$pageBreak = array('pageBreakBefore' => true);

$cellalign = array('borderRightSize' => 1, 'borderRightColor' => ARRAY_HEADER_BG, 'valign' => 'center');
$cellHeaderStyle = array('align' => 'center', 'bgColor' => ARRAY_HEADER_BG);
$styleTable = array('borderSize' => 1, 'borderColor' => ARRAY_HEADER_BG,  'cellMargin' => 25, 'cellMarginTop' => 50, 'cellMarginBottom' => 50, 'width' => 100);
$firstRowStyle = array('bgColor' => ARRAY_HEADER_BG);

// https://phpword.readthedocs.io/en/latest/styles.html#font-style
// https://phpword.readthedocs.io/en/latest/styles.html#paragraph-style
// https://phpword.readthedocs.io/en/latest/recipes.html

if(defined('WORDEXPORT_NUMTITLES') && WORDEXPORT_NUMTITLES == 1) {
    
    // For numbered titles
    $phpWord->addNumberingStyle(
    		'hNum',
    		array('type' => 'multilevel', 'levels' => array(
    				array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1 '),
    				array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'),
    		        array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3')
    		)
    		)
    );
    $phpWord->addTitleStyle(1, array('size' => 18, 'bold' => true, 'color' => '237e84'), array('numStyle' => 'hNum', 'numLevel' => 0));
    $phpWord->addTitleStyle(2, array('size' => 16, 'bold' => true, 'color' => '31415a'), array('numStyle' => 'hNum', 'numLevel' => 1));
    $phpWord->addTitleStyle(3, array('size' => 12, 'bold' => true, 'color' => '444444'), array('numStyle' => 'hNum', 'numLevel' => 2));
    $phpWord->addTitleStyle(4, array('size' => 10, 'bold' => true, 'color' => 'e98e4e', 'allCaps' => true));
    
    // default styles
} else {

    $phpWord->addTitleStyle(1, array('size' => 18, 'bold' => true, 'color' => '237e84'));
    $phpWord->addTitleStyle(2, array('size' => 14, 'bold' => true, 'color' => '31415a'), array('spaceAfter' => 2));
    $phpWord->addTitleStyle(3, array('size' => 12, 'bold' => true, 'color' => '444444'), array('spaceAfter' => 2));
    $phpWord->addTitleStyle(4, array('size' => 10, 'bold' => true, 'color' => 'e98e4e', 'allCaps' => true), array('spaceAfter' => 2));

}

// we prepare var to get sorted objects (projetcs or indicators)
$ordered_items = array();

include_once(override('../export/word/word.report.inc.php', THEME_PUBLIC_PATH));

// Every element you want to append to the word document is placed in a section.
// To create a basic section:
$section = $phpWord->addSection();

require_once(override('../export/word/header_footer.php', THEME_PUBLIC_PATH));


if(!$report_settings['quick_export']) {
    include_once(override('../export/word/word.firstpage.php', THEME_PUBLIC_PATH));
	// because $section->addPageBreak() does not work in current version
	$section->addTextBreak(null, null, $pageBreak);
}

if(defined('WORDEXPORT_TOC_DEPTH')) $maxTOCdepth = WORDEXPORT_TOC_DEPTH;
else $maxTOCdepth = 7;

if($report_settings['summary']) {
	$section->addTextBreak(5);
	$section->addText(formatText(esc($lang['report']['summary'])), array('bold' => 'true') ,array('align' => 'center'));
	$section->addTextBreak(1);
	$section->addTOC(array('spaceAfter' => 60, 'size' => FONT_SIZE_MIN - 1), array(), 1, $maxTOCdepth);
	// because $section->addPageBreak() does not work in current version
	$section->addTextBreak(null, null, $pageBreak);
}


// SDI / dashboard report
if($report_settings['export_module'] == 'dashboard') {
    indicator_recursive(null, $bookmark_level);
    display_orphan_indicators ($bookmark_level);
// 	for($i=0; $i<count($sdi); $i++) {
// 		indicator_display_info($i);
// 	}
// project report
} else {
    project_recursive(null, $bookmark_level);
    display_orphan_projects ($bookmark_level);
}


# bench stop tag
$stop_time=getmicrotime();

$total_time=(float) $stop_time-$start_time;

#inclusion page d'infos de génération
if($report_settings['publi_infos']===true) include_once(override('../export/word/word.lastpage.php', THEME_PUBLIC_PATH));



if($report_settings['export_format'] == 'word') {
	$writer = 'Word2007';
	$extension = '.docx';
}

if($report_settings['export_format'] == 'html') {
	$writer = 'HTML';
	$extension = '.html';
}

// Not implemented yet
// if($report_settings['export_format'] == 'odt') {
// 	$writer = 'ODText';
// 	$extension = '.odt';
// }

// Not implemented yet
// $report_settings['export_format'] = 'pdf_word';
// if($report_settings['export_format'] == 'pdf_word') {
// 	\PhpOffice\PhpWord\Settings::setPdfRendererPath('../lib/vendor/tcpdf/');
// 	\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');
// 	$writer = 'PDF';
// 	$extension = '.pdf';
// }

if($report_settings['export_module'] == 'dashboard') {
    $file = _t('name', 'sdi_module'). '-'.date("d-m-Y_His").$extension;
} else {
    $file = _t('name', 'project_module'). '-'.date("d-m-Y_His").$extension;
}

header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
//header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header("Content-Type: application/octet-stream");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
ob_end_clean(); // uncomment to prevent unwanted content to be printed
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer);
$xmlWriter->save("php://output");
ob_end_flush();
exit();
?>