<?php
/**
 * Dashboard module
 * 
 * Back-office UI to generate PDF and Word reports 
 * 
 * @package linea21\modules\dashboard
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

// ////////// Check Inclusion de pages ////////////
if (!class_exists('auth')) {
  include_once("../lib/lib_common.php");
  ReloadIndex('admin');
}
// //////////

// @todo renforcer le check des droits
//////////// Check Droits utilisateur ////////////
if (!$l21auth->hasRight('project')) ReloadIndex('admin');
////////////

include_once("../lib/input_helpers.php");
include_once(override('../level/display.php', THEME_ADMIN_PATH));
include_once(override('../project/display.php', THEME_ADMIN_PATH));
include_once('../class/class.tag.php');

// including sparkline code
footerAddJS('../lib/js/jquery.sparkline.min.js');
footerAddInlineJS("$('.inlinebar').sparkline('html', {type: 'bar', barColor: '#8DA8CB'} );");

// including html2canvas to render and save as image
footerAddJS('../lib/js/html2canvas/dist/html2canvas.js');

$str = '
		var array_images = [];
		var array_names = [];
		
		$(".project-dashboard").each(function(index, value) {
			var name = $(this).attr("id");
    	
		// we create canvas and populate arrays
			html2canvas($(this), {
        	onrendered: function(canvas) {
            var canvasImg = canvas.toDataURL("image/png");
						$("#" + name).addClass("visually-hidden");
						array_images.push(canvasImg);
						console.log(name + " has been created");
						array_names.push(name);
        	}
			})
    });
		console.log(array_images.length);
		
		// we send arrays to php script to create image dynamically
		setTimeout(function(){
			// #display_projects is first opened because html2canvas cannot work when items / containers are not displayed
			if($("input#projects_all").is(":checked")) $("#display_projects").hide();
			if(array_images.length > 0) {
				$.post("../library/save-image.php", 
								{ images: array_images, names:array_names },
								function(msg) { // success
									console.log("Images has been saved.");
								}
				);
		};
		}, 3000);';
footerAddInlineJS($str);


function displayListProjectByLevels($statut, $filter, $id_filter)
{

	$data = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());

	// we retrieve main levels
	if($filter != 'LEVEL') {
		$data = getLevelChildren($data, 0); // 0 is parentid
		$depth = 0;
	} else {
		$current = $GLOBALS['sql_object']->DBSelect(SQL_getoneLevel($id_filter));
		$data = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $id_filter);
		$id_filter =  array_extract($data, 'level_id', true, 'children');
			
		$content  = '<h2>' . $current[0]['level_name'] . '</h2>' . PHP_EOL;
		$content .= '<p class="description">' . $current[0]['level_desc_project'] . '</p>' . PHP_EOL;
		$depth = 1;
	}

	echo '<div class="bylevels">';
	if(isset($content)) echo $content;
	echo generate_html_list_recursive($data, $statut, $filter, $id_filter, $depth, '');
	echo '</div>';
}




function generate_html_list_recursive($data, $statut, $filter, $id_filter, $depth, $class)
{
	// begin with an empty html string
	$html = '';

	// loop through all items in this level
	foreach($data as $key => &$item)
	{
		// echo "$key <br ><br>";
		// where only interested in numeric items
		// as those are the actual children
		if( !is_numeric( $key ) )
		{
			// otherwise continue
			continue;
		}

		// we get all parents
		
		
// 		print_r($item);
// 		echo '<br><br>';

		// we display link only on main levels
		if($item['level_parent'] == 0) {
			$class = ' level-' . $item['level_id']; // if root level we init $class to superior level
			$html .= '<h2><input type="checkbox" name="levels[]" id="level-' . $item['level_id'] . '" value="' .$item['level_id'] . '" class="' . $class . ' filter-select" /><label for="level-' . $item['level_id'] . '" class="autowidth">' . $item['level_name'] . '</label></h2>' . PHP_EOL;
		} else {
			// @todo - enhance $class / selection system. Today only handle 2 levels
			$class = 'level-'.$item['level_parent'].' level-' . $item['level_id']; // if not root level we concatenate classes
			$html .= '<h'.($depth+2).'><input type="checkbox" name="levels[]" id="level-' . $item['level_id'].'" value="' .$item['level_id'] . '" class="' . $class . ' filter-select" /><label for="level-' . $item['level_id'] . '" class="autowidth">' . $item['level_name'] . '</label></h'.($depth+2).'>' . PHP_EOL;

		}

		// we pass the level ID to the SQL query
		if($filter == 'TAG') {
			$projects = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList(0, 999, $statut, 'LEVEL_TAG', $item['level_id'], $id_filter));
		} else {
			$projects = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList(0, 999, $statut, 'LEVEL', $item['level_id']));
		}

		// 			// we sort values on level names
		// 			// Obtain a list of columns
		// 			foreach ($projects as $key => $row) {
		// 				$level[$key]  = $row['level_name'];
		// 			}
			
		// 			// Sort the data with level descending
		// 			// Add $projects as the last parameter, to sort by the common key
		// 			array_multisort($level, SORT_DESC, $projects);

		if ($projects != 0) {
				
			$html .= '<div class="projects-set">' . PHP_EOL;
				
			for($i = 0; $i < count($projects); $i++) {
				
				// getting tags
				$otag = new tag();
				$display_tags =$otag->getTags('project',  $projects[$i]['project_id'], true);

				$project_name = formatText($projects[$i]['complete_project_name'], '2HTML');
				$project_description = formatText($projects[$i]['project_description'], '2HTML');
				$html .= getAssociatedIndicatorsValues($projects[$i]['project_id']). PHP_EOL;
				$html .= '<p>' . PHP_EOL;
				$html .= '<input type="checkbox" name="projects_id[]" id="project-' . $projects[$i]['project_id'] . '" value="' . $projects[$i]['project_id'] . '"  class="' . $class . '" /><label for="project-' . $projects[$i]['project_id'] . '" class="autowidth">' . $project_name . '</label><i class="icon-tag-1" style="opacity:0.3;margin-left:-1em" title="'.formatText($display_tags, '2ALT').'"></i> ' . PHP_EOL;
				$html .= '</p>' . PHP_EOL;
					
			}
			$html .= '</div>' . PHP_EOL;

		}

		// call this funcion recursively
		// with the next level ($item)
		// it will figure out again whether that level has numeric children as well
		// returns a new complete set, if applicable, otherwise an empty string
		if(isset($item['children'])) $html .= generate_html_list_recursive($item['children'], $statut, $filter, $id_filter, $depth+1, $class);

	}

	// return the resulting html
	return $html;
}

$excludes = array('excel', 'csv', 'json', 'png');
$select_format = selectBox($lang['export']['format'], "format_report", strtolower($lang['export']['format']['pdf']), null, $excludes);


$js = "$('input.filter-select').change(function() {
					// console.log($(this).prop('checked'));
					var matchedClass = $(this).attr('id');
					if($(this).prop('checked') === true) {
						$('input.' + matchedClass).prop('checked', true);
					} else {
						$('input.' + matchedClass).prop('checked', false);
					}
			
					return false;
				});";

footerAddInlineJS($js);


$js = "$('#projects_all').click(function() {
					$('#display_projects').slideUp();
				});
				$('#projects_det').click(function() {
					$('#display_projects').slideDown();
				});";

footerAddInlineJS($js);

// if there is as selection stoed in session
if(isset($_SESSION['project_export_ids'])) {

	$js = ' var actives = '. json_encode($_SESSION["project_export_ids"]) . ';
			$("#projects_det").click();
			$("input:checkbox[name=\'projects_id[]\']").each(function() {

				// if in array we check input
				if($.inArray( $(this).val().toString(), actives) != -1) $(this).prop("checked", true);
		
			})';

	footerAddInlineJS($js);
}




// affichage liste infos
$listing = '';
$listing .= "<div class=\"mtm\"><h2>" . _t('report','comp_choice') . "</h2></div>";
$listing .= "<div class=\"contboxgray\">\n";
$listing .= "\t<ul><li>\n";

$listing .= "<input type=\"checkbox\" name=\"finalities\" id=\"finalities\" checked=\"checked\" />
			<label for=\"finalities\" class=\"autowidth\">" . _t('report','finalities') . "</label>\n";
$listing .= "\t</li>\n";

$listing .= "<input type=\"checkbox\" name=\"finalities_description\" id=\"finalities_description\" checked=\"checked\" />
			<label for=\"finalities_description\" class=\"autowidth\">" . _t('report','finalities_description') . "</label>\n";
$listing .= "\t</li>\n";

$listing .= "\t<li>\n";
$listing .= "<input type=\"checkbox\" name=\"dashboard_values\" id=\"dashboard_values\" checked=\"checked\" />
			<label for=\"dashboard_values\" class=\"autowidth\">" . _t('report','dashboard_values') . "</label>\n";
$listing .= "\t</li>\n";

$listing .= "\t<li>\n";
$listing .= "<input type=\"checkbox\" name=\"notpublished\" id=\"notpublished\" checked=\"checked\" />
			<label for=\"notpublished\" class=\"autowidth\">" . _t('report','also_draft_archives') . "</label>\n";
$listing .= "\t</li>\n";

$listing .= "\t<li>\n";
$listing .= "<input type=\"checkbox\" name=\"summary\" id=\"summary\" checked=\"checked\" />
			<label for=\"summary\" class=\"autowidth\">" . _t('report','summary_info') . "</label>\n";
$listing .= "\t</li>\n";
$listing .= "\t<li>\n";
$listing .= "<input type=\"checkbox\" name=\"publi_info\" id=\"publi_info\" checked=\"checked\" />
			<label for=\"publi_info\" class=\"autowidth\">" . _t('report','publi_info') . "</label>\n";
$listing .= "\t</li>\n";
$listing .= "\t</ul>\n";
$listing .= "</div>\n";

?>
<div id="chemin">
<ul>
	<li><a href="index.php" class="chemin_home"><?php echo _t('way','home'); ?></a></li>
	<li><a href="<?php echo $rub_link; ?>" id="chemin_<?php echo $rub; ?>" class="chemin_rub"><?php echo _t('menu','project'); ?></a></li>
	<li><span><?php echo _t('project','report'); ?></span></li>
</ul>
</div>
<!--end barre haute -->

<div class="contentcontainer"><?php include_once(override($dir.'/menurub.php', THEME_ADMIN_PATH));
?>
<div id="content">
  <h2><?php echo _t('project','report'); ?></h2>
  <form id="report" action="../export/report.php" method="post">
  <p>
    <label for="title_report"><?php echo mb_ucfirst(_t('report','title')); ?> : </label>
    <input name="title_report" type="text" class="textfield" id="title_report" maxlength="255" value="" />
   </p>
  <p>
    <label for="author"><?php echo mb_ucfirst(_t('report','author')); ?> : </label>
    <input name="author" type="text" class="textfield" id="author" maxlength="255" value="" />
  </p>
  <p>
    <label for="mail_author"><?php echo mb_ucfirst(_t('report','mail_author'));?> : </label>
    <input name="mail_author" type="text" class="textfield"	id="mail_author" maxlength="255" value="" />
  </p>
  <p>
    <label for="service_author"><?php echo mb_ucfirst(_t('report','service')); ?> : </label>
    <input name="service_author" type="text" class="textfield" id="service_author" maxlength="255" value="" />
  </p>
  <p>
    <label for="adress_author"><?php echo mb_ucfirst(_t('report','address')); ?> : </label>
    <textarea id="adress_author" name="adress_author" class="no-wysiwyg" <?php echo AREA_SETTINGS; ?>></textarea>
  </p>
  <p>
  	<label for="format_report"><?php echo mb_ucfirst(_t('export','output_format')) ?> : </label>
  	<?php echo $select_format; ?>
  </p>
  
  <div class="mtm"><h2><?php echo _t('report','projects_choice'); ?></h2></div>
	<div class="contboxgray">
		<ul>
			<li><input type="radio" name="projects" value="all" checked="checked" id="projects_all"/><label for="projects_all" class="autowidth"><?php echo _t('report','projects_all'); ?></label>
			<br /><input type="radio" name="projects" value="det" id="projects_det" /><label for="projects_det" class="autowidth"><?php echo _t('report','projects_det'); ?></label>
			<?php if(isset($_SESSION['project_export_ids'])) printf('<span class="session-stored-notice">('._t('project', 'session-stored').')</span>', count($_SESSION['project_export_ids'])); ?>
			</li></ul>
	</div>

	<div class="contboxwhite" id="display_projects">
		<ul>
		  <?php displayListProjectByLevels(false, false, false); ?>
		</ul>
	</div>
 	<?php  echo $listing;  ?>
  <div>
  	<input name="what" type="hidden" value="projects" />
    <input name="annuler" type="button" value="<?php echo _t('btn','annul'); ?>" onclick="window.location='javascript:history.go(-1);'" class="button" id="annuler" />
    <input name="sauver" type="submit" value="<?php echo _t('report','save') ; ?>" class="button" id="sauver" />
  </div>
</form>
</div> <!-- closing #content -->
</div> <!-- closing .contentcontainer -->