<?php
/*** COPYRIGHT NOTICE *********************************************************
 *
 * Copyright 2018 ProjeQtOr - Pascal BERNARD - support@projeqtor.org
 *
 ******************************************************************************
 *** WARNING *** T H I S    F I L E    I S    N O T    O P E N    S O U R C E *
 ******************************************************************************
 *
 * This file is an add-on to ProjeQtOr, packaged as a plug-in module.
 * It is NOT distributed under an open source license. 
 * It is distributed in a proprietary mode, only to the customer who bought
 * corresponding licence. 
 * The company ProjeQtOr remains owner of all add-ons it delivers.
 * Any change to an add-ons without the explicit agreement of the company 
 * ProjeQtOr is prohibited.
 * The diffusion (or any kind if distribution) of an add-on is prohibited.
 * Violators will be prosecuted.
 *    
 *** DO NOT REMOVE THIS NOTICE ************************************************/

include_once '../tool/projeqtor.php';
include_once '../tool/formatter.php';
include_once '../report/headerFunctions.php';
include("../external/pChart2/class/pData.class.php");
include("../external/pChart2/class/pDraw.class.php");
include("../external/pChart2/class/pImage.class.php");
include("../external/pChart2/class/pPie.class.php");

//Parameters
$idProject=RequestHandler::getId('idProject');

// Styles
$cssDarkColor='#507050';
$cssTableMain="width:".setWidth(99)."; vertical-align: middle; text-align:center;font-size:9pt;margin:auto";
$cssTableCell="padding:5px;";
$cssTableLine="height:20px;";
$cssTableLineDetail="height:25px;text-align:left";
$cssTableCellLabel="width:125px; text-align:right;color:$cssDarkColor;white-space:nowrap;";
$cssTableCellHeaderLabel="padding:5px;text-align:center;color:#707070";
$cssTableCellDataRight="min-width:80px;text-align:right;";

//$cssSection="padding-left:20px;height:25px;text-transform:uppercase;text-align:left";
//$cssBoxTitleLine="height:30px;vertical-align:middle;";
//$cssBoxTitle="padding-left:20px; text-align: left;border-bottom:1px solid #000000;";
//$cssBoxTitleCentered="text-align: center;border-bottom:1px solid #000000;";
//$cssBoxField="padding:5px;text-align: left; vertical-align: top; border:1px solid #000000;font-size:80%;";
//$cssDataBoxField="padding:5px;text-align: left; vertical-align: top; border:1px solid #000000;font-size:80%;text-align:center;";
//$cssBoxCentral="border-right:1px solid #000000;";
//$cssBoxLeftTitle="font-size:80%;text-align:right;white-space:nowrap;padding-right:5px;border-right:1px solid #000000;";
//$cssTableHeader="text-align:center;background-color:#D9D9D9;height:25px;border:1px solid #000000;";
// 
$showLabel=false;
if (RequestHandler::isCodeSet('showLabel')) $showLabel=RequestHandler::getBoolean('showLabel');
if (! isset($outMode)) {
  $outMode='screen';
}
$repeatHeader=true;

if($idProject == ' ' ){
  echo '<br/><div style="background: #FFDDDD;font-size:150%;color:#808080;text-align:center;padding:20px">';
   echo i18n('messageNoData',array(i18n('Project')));
  echo '</div>';
  exit;
}

$proj=new Project($idProject);

displayHeader();

// ===================
// Description et état
// ===================
echo '<table style="'.$cssTableMain.'">';
echo '  <tr style="'.$cssTableLine.'">';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
  // Responsables
  echo '    <table>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colIdOrganization').'&nbsp;:&nbsp;</td><td>'.SqlList::getNameFromId('Organization', $proj->idOrganization).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colIdClient').'&nbsp;:&nbsp;</td><td>'.SqlList::getNameFromId('Client', $proj->idClient).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colManager').formatUserThumbLocal('idResource', $proj->idResource,16,'right').'</td><td>'.SqlList::getNameFromId('Affectable', $proj->idResource).'</td></tr>';
  echo '    </table>';
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
  // Dates
  echo '    <table>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td >&nbsp;</td><td style="'.$cssTableCellHeaderLabel.'">'.i18n("colRequested").'</td><td style="'.$cssTableCellHeaderLabel.'">'.i18n("colPlanned").'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colStartDate').'&nbsp;:&nbsp;</td><td style="'.$cssTableCell.'">'.htmlFormatDate($proj->ProjectPlanningElement->initialStartDate).'</td><td style="'.$cssTableCell.'">'.htmlFormatDate($proj->ProjectPlanningElement->plannedStartDate).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colEndDate').'&nbsp;:&nbsp;</td><td style="'.$cssTableCell.'">'.htmlFormatDate($proj->ProjectPlanningElement->initialEndDate).'</td><td style="'.$cssTableCell.'">'.htmlFormatDate($proj->ProjectPlanningElement->plannedEndDate).'</td></tr>';
  echo '    </table>';
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
  // Situation
  echo '    <table>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colIdStatus').formatColorThumbLocal('idStatus', $proj->idStatus,16,'right').'</td><td>'.SqlList::getNameFromId('Status', $proj->idStatus).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colIdHealth').'&nbsp;:&nbsp;</td><td>'.getIconLocal('Health', $proj->idHealth).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('colIdTrend').'&nbsp;:&nbsp;</td><td>'.getIconLocal('Trend', $proj->idTrend).'</td></tr>';
  echo '    </table>';
echo '    </td>';
echo '    <td rowspan="2" style="width:'.setWidth(25).';'.$cssTableCell.';padding-left:0;padding-right;0;vertical-align:top;text-align:left;position:relative;">';
  // Sous-projets
  if ($outMode=='pdf') echo '<div style="width:100px;text-align:left">';
  else echo '<div style="width:95%;position:absolute;overflow:hidden;">';
  echo '<div style="margin:2px 0px 10px 20px;padding:5px;text-align:center;background-color:'.$cssDarkColor.';color:white;">'.i18n('subProjects').'</div>';
  echo '<div style="margin:2px 0px 10px 20px;padding:5px;">'.$proj->drawSubProjects().'</div>';
  if ($outMode!='pdf') echo '<div style="width:100%;height:100%;background-color:transparent;opacity:0;position:absolute;top:0px;left:0px;"></div>';
  echo '</div>';
echo '    </td>';
echo '  </tr>';
echo '  <tr '.$cssTableLine.'>';
echo '    <td colspan="3" style="width:'.setWidth(75).';'.$cssTableCell.'">';
  // Description
  echo '    <div style="padding:5px; text-align:left;width:99%;height:99%;border:1px solid '.$cssDarkColor.';max-height:50mm;overflow:hidden;'.(($outMode=='pdf')?'height:50mm':'').'">'.$proj->description.'</div>';
echo '    </td>';
echo '  </tr>';
echo '</table>';

displayLine();

// ====================
// synthèse des charges
// ====================
echo '<table style="'.$cssTableMain.'">';
echo '  <tr style="'.$cssTableLine.'">';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.';vertical-align:top;position:relative;text-align:left">';
  // Titre
  if ($outMode=='pdf') echo '<div style="padding:5px;background-color:'.$cssDarkColor.';color:white;width:220px;text-align:center">'.i18n('leanatureSyntheseCharges').'</div>';
  else echo '<div style="padding:5px;background-color:'.$cssDarkColor.';color:white;text-align:center;">'.i18n('leanatureSyntheseCharges').'</div>';
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
  // Données
  echo '    <table>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.';">'.i18n('leanatureChargeReelle').'&nbsp;:&nbsp;</td><td style="'.$cssTableCellDataRight.'">'.Work::displayWorkWithUnit($proj->ProjectPlanningElement->realWork).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('leanatureChargeReste').'&nbsp;:&nbsp;</td><td style="'.$cssTableCellDataRight.'">'.Work::displayWorkWithUnit($proj->ProjectPlanningElement->leftWork).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('leanatureAvtGlobal').'&nbsp;:&nbsp;</td><td style="'.$cssTableCellDataRight.'">'.SqlList::getNameFromId('OverallProgress', $proj->idOverallProgress).'</td></tr>';
  echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('leanatureAvt').'&nbsp;:&nbsp;</td><td style="'.$cssTableCellDataRight.'">'.htmlDisplayPct($proj->ProjectPlanningElement->progress).'</td></tr>';
  echo '    </table>';
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
  // Graphe
  $data = new pData();
  $data->addPoints(array($proj->ProjectPlanningElement->progress,100-$proj->ProjectPlanningElement->progress),"progress");
  //$data->setSerieDescription("progress","Avancement");
  $data->addPoints(array(i18n("colRealWork"),i18n("colLeftWork")),"legende");
  $data->setAbscissa("legende");
  $width=200;
  $height=125;
  $graph = new pImage($width,$height,$data);
  $graph->setFontProperties(array("FontName"=>plgLeanatureGetFontLocation("verdana"),"FontSize"=>7,"R"=>100,"G"=>100,"B"=>100));
  $chart = new pPie($graph,$data);
  $chart->setSliceColor(0,array("R"=>100,"G"=>100,"B"=>200));
  $chart->setSliceColor(1,array("R"=>230,"G"=>120,"B"=>0));
  $chart->draw2DPie($height/2,$height/2,array("Radius"=>($height/2)-10,"WriteValues"=>PIE_VALUE_PERCENTAGE,"ValuePosition"=>PIE_VALUE_INSIDE,"LabelStacked"=>true,"SecondPass"=>true,"Border"=>FALSE));
  $chart->drawPieLegend($height,10,array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_VERTICAL));
  $imgName=getGraphImgName("leanatureRapportFlashCharge");
  $graph->Render($imgName);
  echo '<img style="width:'.($width).'px;height:'.($height).'px" src="' . $imgName . '" />'; 
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
echo '    </td>';
echo '  </tr>';
echo '</table>';

displayLine();

// ===================
// synthèse budgétaire
// ===================
echo '<table style="'.$cssTableMain.'">';
echo '  <tr style="'.$cssTableLine.'">';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.';vertical-align:top;position:relative;text-align:left">';
// Titre
if ($outMode=='pdf') echo '<div style="padding:5px;background-color:'.$cssDarkColor.';color:white;width:220px;text-align:center">'.i18n('leanatureSyntheseBudget').'</div>';
else echo '<div style="padding:5px;background-color:'.$cssDarkColor.';color:white;text-align:center;">'.i18n('leanatureSyntheseBudget').'</div>';
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
// Données
$budgetInit=$proj->ProjectPlanningElement->expenseValidatedAmount;
if (!$budgetInit) $budgetInit=0;
$expenseReal=$proj->ProjectPlanningElement->expenseRealAmount;
//$expenseLeft=$proj->ProjectPlanningElement->expenseLeftAmount;
//$expenseLeft=$proj->ProjectPlanningElement->expenseAssignedAmount-$proj->ProjectPlanningElement->expenseRealAmount;
$expenseLeft=$budgetInit-$expenseReal;
if ($expenseLeft<0) $expenseLeft=0;
echo '    <table>';
echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.';">'.i18n('leanatureBudgetInit').'&nbsp;:&nbsp;</td><td style="'.$cssTableCellDataRight.'">'.htmlDisplayCurrency($budgetInit,true).'</td></tr>';
echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('leanatureBudgetReel').'&nbsp;:&nbsp;</td><td style="'.$cssTableCellDataRight.'">'.htmlDisplayCurrency($expenseReal,true).'</td></tr>';
echo '      <tr style="'.$cssTableLineDetail.'"><td style="'.$cssTableCellLabel.'">'.i18n('leanatureBudgetReste').'&nbsp;:&nbsp;</td><td style="'.$cssTableCellDataRight.'">'.htmlDisplayCurrency($expenseLeft,true).'</td></tr>';
echo '    </table>';
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
  // Graphe
  $width=200;
  $height=125;
  $dataSet = new pData();
  if ($showLabel) {
    $arrayValidated=array(VOID,$budgetInit,VOID,VOID);
    $arrayReal=array(VOID,VOID,VOID,$expenseReal);
    $arrayLeft=array(VOID,VOID,VOID,$expenseLeft);
  } else {
    $arrayValidated=array($budgetInit,VOID);
    $arrayReal=array(VOID,$expenseReal);
    $arrayLeft=array(VOID,$expenseLeft);
  }
  $max=max($budgetInit,($expenseReal+$expenseLeft));
  $scaleMax=intval("1".substr('00000000000000',0,strlen(round($max,0))-1));
  //if ($scaleMax>0) $maxCeil=ceil($max/$scaleMax)*$scaleMax;
  $firstScaleVal=intval(substr($max,0,1));
  if ($firstScaleVal==1) $factor=5;
  else if ($firstScaleVal<5) $factor=1; 
  else $factor=2;
  //$arrayLabel=array('1','2');
  $dataSet->addPoints($arrayValidated,"validated");
  $dataSet->addPoints($arrayReal,"real");
  $dataSet->addPoints($arrayLeft,"left");
  //$dataSet->addPoints($arrayLabel,"label");
  $dataSet->setSerieOnAxis("real",0);
  $dataSet->setSerieOnAxis("validated",0);
  $dataSet->setSerieOnAxis("left",0);
  //$dataSet->setAbscissa("label");
  $dataSet->setSerieDescription("real","engagé");
  $dataSet->setSerieDescription("validated","budget initial");
  $dataSet->setSerieDescription("left","reste à faire");
  $dataSet->setAxisDisplay(0,AXIS_FORMAT_CUSTOM,"YAxisFormat");
  $graph = new pImage($width,$height,$dataSet);
  /* Draw the background */
  $graph->Antialias = FALSE;
  $Settings = array("R"=>255, "G"=>255, "B"=>255, "Dash"=>0, "DashR"=>0, "DashG"=>0, "DashB"=>0);
  //$graph->drawFilledRectangle(0,0,$graphWidth,$graphHeight,$Settings);
  /* Add a border to the picture */
  //$graph->drawRectangle(0,0,$graphWidth-1,$graphHeight-1,array("R"=>150,"G"=>150,"B"=>150));
  /* Set the default font */
  $graph->setFontProperties(array("FontName"=>plgLeanatureGetFontLocation("verdana"),"FontSize"=>7,"R"=>50,"G"=>50,"B"=>50));
  /* Draw the scale */
  $dataSet->setAxisUnit(0,' '.$currency.' ');
  $graph->setGraphArea(10,20,$width-20,$height-25);
  //$graph->drawFilledRectangle(70,50,$graphWidth-200,$graphHeight-30,array("R"=>230,"G"=>230,"B"=>230));
  $formatGrid=array( "GridTicks"=>0,"Mode"=>SCALE_MODE_MANUAL,"ManualScale"=>array(0=>array("Min"=>0,"Max"=>$max)),"LabelSkip"=>3,"RemoveXAxis"=>true,
    "DrawYLines"=>false, "DrawXLines"=>false,"Pos"=>SCALE_POS_TOPBOTTOM,
    "LabelRotation"=>90, "GridR"=>150,"GridG"=>150,"GridB"=>150,"Factors"=>array($factor));
  $graph->drawScale($formatGrid);
  $dataSet->setSerieDrawable("real",true);
  $dataSet->setSerieDrawable("validated",true);
  $dataSet->setSerieDrawable("left",true);
  $dataSet->setPalette("real",array("R"=>100,"G"=>100,"B"=>200,"Alpha"=>255));
  $dataSet->setPalette("validated",array("R"=>100,"G"=>150,"B"=>100,"Alpha"=>255));
  $dataSet->setPalette("left",array("R"=>230,"G"=>120,"B"=>0,"Alpha"=>255));
  $format=array( 'DisplayValues'=>true,'DisplayR'=>255,'DisplayG'=>255,'DisplayB'=>255);
  $graph->drawStackedBarChart($format);
  $graph->drawLegend(5,$height-10,array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_HORIZONTAL));
  if ($showLabel) {
    $LabelSettings = array("OverrideTitle"=>"Multiple series","DrawVerticalLine"=>false,"NoTitle"=>true,"DrawSerieColor"=>true,"VerticalMargin"=>5,"HorizontalMargin"=>3,"FontSize"=>6);
    $graph->writeLabel(array("validated"),1,$LabelSettings);
    $graph->writeLabel(array("real"),3,$LabelSettings);
    $graph->writeLabel(array("left"),3,$LabelSettings);
  }
  //$graph->drawText($width-12,16,"K€");
  $imgName=getGraphImgName("leanatureRapportFlashCharge");
  $graph->Render($imgName);  
  echo '<img style="width:'.($width).'px;height:'.($height).'px" src="' . $imgName . '" />';
echo '    </td>';
echo '    <td style="width:'.setWidth(25).';'.$cssTableCell.'">';
echo '    </td>';
echo '  </tr>';
echo '</table>';
// ====================================================================
// Functions
// ====================================================================

//Function pdf % to px
function setWidth ($width){
  global $outMode;
  if($outMode == 'pdfno'){
    return (1000*$width/100).'px';
  }else{
    return $width.'%';
  }
}
function formatColorThumbLocal($field, $value,$size,$float='right') {
	global $outMode;
  if ($outMode == 'pdf'){
	  return '&nbsp;:&nbsp;';//<div style="position:relative;width:16px;height:16px;"><div style="position:absolute;width:16px;height:16px;left:-16px;top:-16px;">'.formatColorThumb($field, $value,$size,$float).'</div></div>';
  } else {
	  return '<div style="float:'.$float.';padding:0px 5px;">'.formatColorThumb($field, $value,$size,$float).'</div>';
  }
}
function formatUserThumbLocal($field, $value,$size,$float) {
  global $outMode;
  if ($outMode == 'pdf'){
    return '&nbsp;:&nbsp;';//<div style="position:relative;width:16px;height:16px;"><div style="position:absolute;width:16px;height:16px;left:-16px;top:-16px;">'.formatColorThumb($field, $value,$size,$float).'</div></div>';
  } else {
    return '<div style="float:right;padding:0px 5px;">'.formatUserThumb($value,'','',$size,$float,false).'</div>';
  }
}
function getIconLocal($class, $value) {
  global $outMode;
  $obj=new $class($value);
  if (! $obj->icon) {
    return formatColorThumbLocal('id'.$class, $value,16,'left'); 
  }
  if ($outMode == 'pdf'){
    return '&nbsp;:&nbsp;';//<div style="position:relative;width:16px;height:16px;"><div style="position:absolute;width:16px;height:16px;left:-16px;top:-16px;">'.formatColorThumb($field, $value,$size,$float).'</div></div>';
  } else {
    return '<div style="float:left;padding:0px 5px;"><img src="../view/icons/'.$obj->icon.'" style="height:20px" /></div>';
  }
}

function displayHeader() {
	global $cssTableMain,$cssTableCell,$cssDarkColor,$proj;
	// En-tête
	$uri="../view/img/titleSmall.png";
	if (file_exists("../plugin/leanatureRapportFlash/logo.png")) $uri='../plugin/leanatureRapportFlash/logo.png';
	else if (file_exists("../plugin/leanatureRapportFlash/logo.gif")) $uri='../plugin/leanatureRapportFlash/logo.gif';
	else if (file_exists("../plugin/leanatureRapportFlash/logo.jpg")) $uri='../plugin/leanatureRapportFlash/logo.jpg';
	else if (file_exists("../logo.png")) $uri='../logo.png';
	else if (file_exists("../logo.gif")) $uri='../logo.gif';
	else if (file_exists("../logo.jpg")) $uri='../logo.jpg';
	$user=getSessionUser();
	$userName=($user->resourceName)?$user->resourceName:$user->name;
	echo '<table style="'.$cssTableMain.'">';
	echo '  <tr>';
	echo '    <td style="'.$cssTableCell.'width:'.setWidth(15).'; text-align: left;border-right:1px solid '.$cssDarkColor.'" rowspan="4">';
	echo '      <img style="max-width:200px;max-height:70px" src="' . $uri . '" />';
	echo '    </td>';
	echo '    <td style="line-height:25px;padding:10px;font-size:120%;text-align:center;border:1px solid '.$cssDarkColor.';width:'.setWidth(70).';">'.strtoupper(i18n('leanatureRapportFlash')).'<br/>'.$proj->projectCode.'&nbsp;-&nbsp;'.$proj->name.'</td>';
	echo '    <td style="'.$cssTableCell.'font-size:80%;white-space:nowrap;width:'.setWidth(15).';">'.i18n('leanatureEditionDate').'&nbsp;'.date('d/m/Y H\hi').'<br/>'.i18n('leanatureEditionUser').'&nbsp'.$userName.'</td>';
	echo '  </tr>';
	echo '</table>';
}

function displayLine() {
  global $cssTableMain,$cssTableCell,$cssDarkColor,$proj,$outMode;
  if ($outMode=='pdf') {
    echo '<table style="'.$cssTableMain.'">';
    echo '<tr><td style="width:100%;border-bottom: 1px solid '.$cssDarkColor.'">&nbsp;</td></tr>';
    echo '<tr><td style="width:100%;">&nbsp;</td></tr>';
    echo '</table>';
  } else {
    echo '<table style="'.$cssTableMain.'"><tr><td>';
    echo '<div style="width:100%;border-bottom:1px solid '.$cssDarkColor.';heigth:1px;margin:5px 0px;"></div>';
    echo '</td></tr></table>';
  }
}

function YAxisFormat($value) { 
  global $max;
  if ($max>500000) return(round($value/1000000,1).'M€');
  else return(round($value/1000,1).'K€'); 
}

function plgLeanatureGetFontLocation($font) {
	$current=plgLeanature_dirname_recursive(__FILE__,2);
	return "$current/external/pChart2/fonts/$font.ttf";
}
function plgLeanature_dirname_recursive($path, $count=1){
	if ($count > 1){
		return dirname(plgLeanature_dirname_recursive($path, --$count));
	}else{
		return dirname($path);
	}
}
