<?php 
/*** COPYRIGHT NOTICE *********************************************************
 *
 * Copyright 2009-2017 ProjeQtOr - Pascal BERNARD - support@projeqtor.org
 * Contributors : -
 * 
 * Most of properties are extracted from Dojo Framework.
 *
 * This file is part of ProjeQtOr.
 * 
 * ProjeQtOr is free software: you can redistribute it and/or modify it under 
 * the terms of the GNU Affero General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version.
 * 
 * ProjeQtOr is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for 
 * more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * ProjeQtOr. If not, see <http://www.gnu.org/licenses/>.
 *
 * You can get complete code of ProjeQtOr, other resource, help and information
 * about contributors at http://www.projeqtor.org 
 *     
 *** DO NOT REMOVE THIS NOTICE ************************************************/

include_once '../tool/projeqtor.php';

$paramTeam = trim(RequestHandler::getId('idTeam'));
$idOrganization = trim(RequestHandler::getId('idOrganization'));
$idDepartement=trim(RequestHandler::getId('idDepartementPlg'));
$idDirection=trim(RequestHandler::getId('idDirectionPlg'));
$idBaseLine1=trim(RequestHandler::getId('idPlgForecastBaseLineHeaderOne'));
$idBaseLine2=trim(RequestHandler::getId('idPlgForecastBaseLineHeaderTwo'));
$paramYear = RequestHandler::getYear('yearSpinner');


$user=getSessionUser();


// Header
$headerParameters="";

if ($idOrganization!="") {
  $headerParameters.= i18n("colIdOrganization") . ' : ' . htmlEncode(SqlList::getNameFromId('Organization',$idOrganization)) . '<br/>';
}
if ($idDepartement!="") {
  $headerParameters.= i18n("colIdDepartement") . ' : ' . htmlEncode(SqlList::getNameFromId('DepratementPlg',$idDepartement)) . '<br/>';
}
if ($idDirection!="") {
  $headerParameters.= i18n("colIdDirection") . ' : ' . htmlEncode(SqlList::getNameFromId('DirectionPlg',$idDirection)) . '<br/>';
}
if ($paramTeam!="") {
  $headerParameters.= i18n("colIdTeam") . ' : ' . htmlEncode(SqlList::getNameFromId('Team', $paramTeam)) . '<br/>';
}

if ($idBaseLine1!="") {
  $nameBaseLine1=SqlList::getNameFromId('PlgForecastBaseLineHeader',$idBaseLine1);
  $headerParameters.= i18n("colIdPlgForecastBaselineOne") . ' : ' . htmlEncode($nameBaseLine1) . '<br/>';
}
if ($idBaseLine2!="") {
  $nameBaseLine2=SqlList::getNameFromId('PlgForecastBaseLineHeader',$idBaseLine2);
  $headerParameters.= i18n("colIdPlgForecastBaselineTwo") . ' : ' . htmlEncode($nameBaseLine2) . '<br/>';
}

$headerParameters.= i18n("year") . ' : ' . $paramYear . '<br/>';



$drew=false;
$monthTable=array('January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
'December');
$tab= array();
$result=array();
$forecast= new PlgForecast();
$baseLine= new PlgForecastBaseLine();
$proj=new Project();
$aff=new Affectation();
$pe= new PlanningElement();
$pejTableName=$pe->getDatabaseTableName();
$projTableName=$proj->getDatabaseTableName();
$affTableName=$aff->getDatabaseTableName();
$user=getSessionUser();
$destinationWidth=RequestHandler::getNumeric('destinationWidth')-(RequestHandler::getNumeric('destinationWidth')*0.05)-15;
$widthInput=intval($destinationWidth/(25)-30);

$resTableName=$user->getDatabaseTableName();
$lstRes="SELECT $resTableName.id FROM $resTableName WHERE $resTableName.isResource=1";
if($paramTeam!="")$lstRes .=" and $resTableName.idTeam=$paramTeam";
if($idOrganization!="")$lstRes .=" and $resTableName.idOrganization=$idOrganization";
if($idDepartement!="")$lstRes .=" and $resTableName.idDepartementPlg=$idDepartement";
if($idDirection!="")$lstRes .=" and $resTableName.idDirectionPlg=$idDirection";


$query="SELECT pe.refType, pe.refId, pe.idProject, pe.refName, af.idResource FROM $pejTableName pe ";
$query .="LEFT JOIN $affTableName af on af.idProject=pe.idProject ";
$query .="WHERE pe.refType='Activity' and pe.topRefType='Project' and af.idResource is not null ";
$query .="and af.idResource in ($lstRes) and pe.cancelled <> 1 and pe.idle <> 1 ";
$query .="and pe.idProject in (SELECT proj.id FROM $projTableName proj WHERE proj.idle <> 1 and proj.cancelled <> 1 ) ";
$query .="ORDER BY af.idResource asc , pe.idProject asc , pe.refId asc ";
 
$result=Sql::query($query);
$tabNbLineRes=array();
$lastRes="";
$cpNbLineRes=1;
$cp=0;
$limit=2500;
while ($line = Sql::fetchLine($result)) {
  $tab[]=$line;
  $res=$line['idResource'];
  if($lastRes!=$res ){
    $tabNbLineRes[$lastRes]=$cpNbLineRes;
    $cpNbLineRes=1;
    $lastRes=$res;
  }else{
    $cpNbLineRes++;
  }
  $cp++;
  if($cp==$limit){
    break;
  }
}
$tabNbLineRes[$lastRes]=$cpNbLineRes;
if(!empty($tab))$drew=true;

if (isset($outMode) and $outMode=='excel') {
  $headerParameters.=str_replace('- ','<br/>',Work::displayWorkUnit()).'<br/>';
}
include "header.php";

if($drew){
  $clause="idResource in ($lstRes)  and refType='Activity'";
  $clause.=" and year = '$paramYear' ";
  $lstFor=$forecast->getSqlElementsFromCriteria(null,null,$clause,'idResource asc,idProject asc, refId asc');
  if($idBaseLine1!='' or $idBaseLine2!=''){
    if($idBaseLine1!='' and  $idBaseLine2!='')$clauseBasLine=$clause." and idPlgForecastBaselineHeader in  ($idBaseLine1, $idBaseLine2 )";
    else $clauseBasLine=$clause." and idPlgForecastBaselineHeader = ".((($idBaseLine1!='')?$idBaseLine1:$idBaseLine2));
    $lstBaseLine=$baseLine->getSqlElementsFromCriteria(null,null,$clauseBasLine,'idResource asc,idProject asc, refId asc');
  }
  
  if(!empty($lstFor))$sortForcast=PlgForecast::sortForecast($lstFor);
  if(!empty($lstBaseLine))$sortBasLine=PlgForecast::sortForecast($lstBaseLine,true);
  $lastReseource="";
  $tabCostRes=array();
  $display='';
  
    $cpAct=0;
    $i=1;
    $display.= '<table  align="center" class="crossTable" style="width:95%;" '.excelName().'>';
    $display.=  '<tr class="reportHeader" >';
    $display .=     '<td rowspan="2" style="width:6%" class="reportTableHeader"  '.excelFormatCell('header',20).'></td>';
    $display .=     '<td rowspan="2" style="width:6%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('Activity').'</td>';
    while($i<=12){
      $display .=     '<td colspan="3" style="width:6%" class="reportTableHeader"  '.excelFormatCell('header',10).'>'.i18n($monthTable[$i-1]).'</td>';
      $i++;
    }
    $i=1;
    $display .=     '<td colspan="3" style="width:6%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('colTotal').'&nbsp;'.$paramYear.'</td>';
    $display .=     '<td rowspan="2" style="width:4%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('colCostFunct').'</td>';
    $display .=     '<td colspan="3"style="width:6%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('sectionRevenue').'</td>';
    $display .=   '</tr>';
    
    $display.=    '<tr class="reportHeader" >';
    while ($i<=13){
      $display .=   '<td   class="reportTableHeader"  '.excelFormatCell('header',10).'></td>';
      $display .=   '<td   class="reportTableHeader" style="background-color:#FFC300 '.(( isset($outMode) and $outMode=='pdf')?'':'!important').';"  '.excelFormatCell('header',10).'>B1</td>';
      $display .=   '<td   class="reportTableHeader" style="background-color:#D35400 '.(( isset($outMode) and $outMode=='pdf')?'':'!important').';" '.excelFormatCell('header',10).'>B2</td>';
      $i++;
    }

    $display .=   '<td   class="reportTableHeader" style="width:2%" '.excelFormatCell('header',10).'></td>';
    $display .=   '<td class="reportTableHeader" style="width:2%;background-color:#FFC300 '.(( isset($outMode) and $outMode=='pdf')?'':'!important').';"  '.excelFormatCell('header',10).'>B1</td>';
    $display .=   '<td class="reportTableHeader" style="width:2%;background-color:#D35400 '.(( isset($outMode) and $outMode=='pdf')?'':'!important').';"  '.excelFormatCell('header',10).'>B2</td>';
    $display .= '</tr>';
    
    
    $nbElement=count($tab);
    $count=0;
//     $drawCost=false;
    foreach ( $tab as $id=>$obj ){
      $res=$obj['idResource'];
      $idAct=$obj['refId'];
      $idProj=$obj['idProject'];
      $actName=$obj['refName'];
      $display .= '   <tr>';
      if($lastReseource!=$res){
//         $display=str_replace("rawspanBase",$cpAct,$display);
        $lastReseource=$res;
        $cpAct=0;
        $lastIdAct="";
        $lastIdProj="";
        $resource= new ResourceAll($res);
        $resourceCost= new ResourceCost();
        if(!isset($tabCostRes[$res])){
          $role=$resource->idRole;
          $RC=SqlElement::getSingleSqlElementFromCriteria('ResourceCost', array('idResource'=>$res,'idRole'=>$role));
          $cost=$RC->cost;
          $tabCostRes[$res]=$cost;
        }else{
          $cost=$tabCostRes[$res];
        }
        
        
        $display .= '<td rowspan="'.$tabNbLineRes[$resource->id].'" class="reportTableData"  style="text-align:left;padding:5px;"';
        $display .= excelFormatCell('data',null,null,null,null,'left',null,null,null).'>';
        $display .=$resource->name;
        $display .= '</td>';
//         $drawCost=true;
      }
      if($lastIdProj!=$idProj  ){
        $project= new Project($idProj);
        $natureProj= new NatureProjectPlg($project->idNatureProjectPlg);
        $actNameColor=($natureProj->color)?"color:".$natureProj->color.";":"";
        $projeColorExcel=($natureProj->color)? $natureProj->color:null;
        $projectC= ($natureProj->color)? PlgForecast::adjustBrightness($natureProj->color,0.5) :"";
        $projeBackgroundExcel=($projeColorExcel)? PlgForecast::adjustBrightness($projeColorExcel,0.5):null;
        $projColor=($projectC!="")?"background-color:".$projectC.";":"";
        $lastIdProj=$idProj;
      }
      $cpAct++;
      $lastIdAct=$idAct;
      $display .= '<td class="reportTableData" style="'.$projColor.$actNameColor.';text-align:left;padding:5px;"';
      $display .= excelFormatCell('data',null,$projeColorExcel,$projeBackgroundExcel,null,'left',null,null,null).'>';
      $display .=$actName;
      $display .= '</td>';
      $m=1;
      $sumActYearly=0;
      $sumActYearlyBL1=0;
      $sumActYearlyBL2=0;
      while($m<=12){
        $work=0;
        $workBL1=0;
        $workBL2=0;
        $key=$res.'_'.$idProj.'_'.$idAct.'_'.$paramYear.'_'.$m;
        $keyBL1=$key.'_'.$idBaseLine1;
        $keyBL2=$key.'_'.$idBaseLine2;
        if(isset($sortForcast) and array_key_exists($key, $sortForcast)){  //======== forecast existe for this month ==========//
          $work=$sortForcast[$key]['work'];
          $sumActYearly +=$work;
        }
        if(isset($sortBasLine)){
          if(array_key_exists($keyBL1, $sortBasLine)){
            $workBL1=$sortBasLine[$keyBL1]['work'];
            $sumActYearlyBL1 +=$workBL1;
          }
          if(array_key_exists($keyBL2, $sortBasLine)){
            $workBL2=$sortBasLine[$keyBL2]['work'];
            $sumActYearlyBL2 +=$workBL2;
          }
        }
        $display .= '<td class="reportTableData" style="'.$projColor.';min-width: 2em;"';
        $display .= excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,'work').'>';
        if(isset($outMode) and $outMode=='excel')$display .= (($work!=0)?Work::displayWork($work):'');
        else $display .= (($work!=0)?htmlDisplayNumericWithoutTrailingZeros($work):'');
        $display .= '</td>';
        $display .= '<td class="reportTableData" style="'.$projColor.';min-width: 2em;"';
        $display .= excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,'work').'>';
        if(isset($outMode) and $outMode=='excel')$display .= (($workBL1!=0)?Work::displayWork($workBL1):'');
        else $display .= (($workBL1!=0)?htmlDisplayNumericWithoutTrailingZeros($workBL1):'');
        $display .= '</td>';
        
        $display .= '<td class="reportTableData" style="'.$projColor.';min-width: 2em;"';
        $display .=excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,'work').'>';
         if(isset($outMode) and $outMode=='excel')$display .= (($workBL2!=0)?Work::displayWork($workBL2):'');
         else $display .= (($workBL2!=0)?htmlDisplayNumericWithoutTrailingZeros($workBL2):'');
        $display .= '</td>';
        $m++;
      }
      $display .= '<td class="reportTableData" style="'.$projColor.'"';
      $display .=excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,null).'>';
      if(isset($outMode) and $outMode=='excel')$display .=(($sumActYearly!=0)?Work::displayWork($sumActYearly):'');
      else $display .= (($sumActYearly!=0)?htmlDisplayNumericWithoutTrailingZeros($sumActYearly):'');
      $display .= '</td>';
      
      $display .= '<td class="reportTableData" style="'.$projColor.'"';
      $display .=excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,null).'>';
      if(isset($outMode) and $outMode=='excel')$display .=(($sumActYearlyBL1!=0)?Work::displayWork($sumActYearlyBL1):'');
      else $display .= (($sumActYearlyBL1!=0)?htmlDisplayNumericWithoutTrailingZeros($sumActYearlyBL1):'');
      $display .= '</td>';
      $display .= '<td class="reportTableData" style="'.$projColor.'"'
                            .excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,null).'>';
      if(isset($outMode) and $outMode=='excel')$display .=(($sumActYearlyBL2!=0)?Work::displayWork($sumActYearlyBL2):'');
      else $display .= (($sumActYearlyBL2!=0)?htmlDisplayNumericWithoutTrailingZeros($sumActYearlyBL2):'');
      $display .= '</td>';
//       if($drawCost){
        $display .= '<td  class="reportTableData"  style="text-align:right;padding:5px;"';
        $display .=excelFormatCell('data',null,null,$projeBackgroundExcel,null,'right',null,null,null).'>';
        if(isset($outMode) and $outMode=='excel')$display .=(($cost!=0)?$cost:0);
        else $display .=htmlDisplayCurrency((($cost!=0)?$cost:0));
        $display .='</td>';
//         $drawCost=false;
//       }
      $display .= '<td  class="reportTableData" style="'.$projColor.';text-align:right;padding:5px;"';
      $display .=excelFormatCell('data',null,null,$projeBackgroundExcel,null,'right',null,null,null).'>';
      if((isset($outMode) and $outMode=='excel')) $display .=(($sumActYearly!=0 and $cost!=0)?$cost*$sumActYearly:0);
      else $display .=htmlDisplayCurrency((($sumActYearly!=0 and $cost!=0)?$cost*$sumActYearly:0));
      $display .= '</td>';
      
      $display .= '<td  class="reportTableData" style="'.$projColor.';text-align:right;padding:5px;"';
      $display .=excelFormatCell('data',null,null,$projeBackgroundExcel,null,'right',null,null,null).'>';
      if((isset($outMode) and $outMode=='excel')) $display .=(($sumActYearlyBL1!=0 and $cost!=0)?$cost*$sumActYearlyBL1:0);
      else $display .=htmlDisplayCurrency((($sumActYearlyBL1!=0 and $cost!=0)?$cost*$sumActYearlyBL1:0));
      $display .= '</td>';
      
      $display .= '<td  class="reportTableData" style="'.$projColor.';text-align:right;padding:5px;"';
      $display .=excelFormatCell('data',null,null,$projeBackgroundExcel,null,'right',null,null,null).'>';
      if((isset($outMode) and $outMode=='excel')) $display .=(($sumActYearlyBL2!=0 and $cost!=0)?$cost*$sumActYearlyBL2:0);
      else $display .=htmlDisplayCurrency((($sumActYearlyBL2!=0 and $cost!=0)?$cost*$sumActYearlyBL2:0));
      $display .= '</td>';
      $display .='</tr>';
      $count++;
    }
    
    if($count==$limit){
      $display .=  '<tr>';
      $display .=    '<td colspan="45">';
      $display .=      '<div style="background:#FFDDDD;font-size:150%;color:#808080;text-align:center;padding:15px 0px;width:100%;">'.i18n('limitedDisplay',array($count)).'</div>';
      $display .=    '</td>';
      $display .=  '</tr>';
    }

    $display.= '</table>';
}else{ 
  $message =i18n('noDataFound');
	    // =============  message "selectOnListToDisplayForecast"  ============= //
  $display = '<table style="width:90%; margin-bottom:10px;margin-top:45px;margin-left:5%;" '.excelName().'>';
  $display .=   '<tr>';
   $display .=     '<td  '.excelFormatCell('data',null,null,null,null,'right',null,null,null).'>';
  if(isset($outMode) and $outMode=='excel')$display.= $message;
  else$display .=       '<div style="background:#FFDDDD;font-size:150%;color:#808080;text-align:center;padding:15px 0px;width:100%;">'.$message.'</div>';
  $display .=     '</td>';
  $display .=   '</tr>';
  $display .= '</table>';
  //==================//
}
echo $display;

end: