<?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'));
$paramYear = RequestHandler::getYear('yearSpinner');
$monthStart= 1;
$paramPeriod = RequestHandler::getValue('nbYearsPeriod');


$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/>';
}

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

if ($paramPeriod!='') {
  $headerParameters.= i18n("period") . ' : ' . $paramPeriod .'&nbsp;'.i18n('year').'<br/>';
}

$drew=false;
$monthTable=array('January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
'December');
$tab= array();
$result=array();
$forecast= new PlgForecast();
$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/>';
}
$display='';
include "header.php";

if($drew and $paramPeriod >=1){
  $clause="idResource in ($lstRes)  and refType='Activity'";
  $starYear=$paramYear;

  $endYear=$paramYear+$paramPeriod;
  $clause.=" and year >= '$paramYear'  and year <'$endYear'";

  $lstFor=$forecast->getSqlElementsFromCriteria(null,null,$clause,'idResource asc,idProject asc, refId asc');
  if(!empty($lstFor))$sortForcast=PlgForecast::sortForecast($lstFor);
  $lastReseource="";
  $tabCostRes=array();
  
  
  if(isset($outMode) and $outMode=='excel'){ // display in excel
      
      $display.= '<table  align="center" class="crossTable" style="width:95%;" '.excelName().'>';
      $display.=    '<tr class="reportHeader" style="height:32px;">';
      for ($y=$starYear;$y < $endYear;$y++){
        $i=1;
        if($y>$starYear)$display .=     '<td style="width:10%"  '.excelFormatCell('data',20).'></td>';
        $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'></td>';
        $display .=     '<td style="width:12%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('Activity').'</td>';
        $monthStartHead=$monthStart;
        while($i<=12){
          $display .=     '<td style="width:4%" class="reportTableHeader"  '.excelFormatCell('header',10).'>'.i18n($monthTable[$monthStartHead-1]).'</td>';
          $monthStartHead++;
          if($monthStartHead==13)$monthStartHead=1;
          $i++;
        }
        $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('colTotal').'&nbsp;'.$y.'</td>';
        $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('colCostFunct').'</td>';
        $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('sectionRevenue').'</td>';
      }
      $display .=     '</tr>';
      
      $nbElement=count($tab);
      $count=0;
      $cpAct=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){
//           if($cpAct!=0)$display=str_replace("rowspanBase",$cpAct,$display);
          $lastReseource=$res;
          $resAlreadyWriten= array();
          $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];
          }
        }
        
        $lastIdAct=$idAct;
        
        for ($year=$starYear;$year < $endYear;$year++){
          if($year>$starYear)$display .= '<td '.excelFormatCell('data',10).'></td>';
          
          if(!isset($resAlreadyWriten[$year])){
            $display .=     '<td rowspan="'.$tabNbLineRes[$resource->id].'" '.excelFormatCell('data',null,null,null,null,'left',null,null,null).'>';
            $display .=$resource->name;
            $display .=     '</td>';
            $resAlreadyWriten[$year]=true;
          }

          if($lastIdProj!=$idProj  ){
            $project= new Project($idProj);
            $natureProj= new NatureProjectPlg($project->idNatureProjectPlg);
            $projeColorExcel=($natureProj->color)? $natureProj->color :null;
            $projeBackgroundExcel=($projeColorExcel)? PlgForecast::adjustBrightness($projeColorExcel,0.5):null;
            $lastIdProj=$idProj;
          }

          $display .=     '<td '.excelFormatCell('data',null,$projeColorExcel,$projeBackgroundExcel,null,'left',null,null,null).'>';
          $display .=$actName;
          $display .=     '</td>';
          
          $m=1;
          $sumActYearly=0;
          $monthStartLine=$monthStart;
          while($m<=12){
            $work=0;
            $key=$res.'_'.$idProj.'_'.$idAct.'_'.$year.'_'.$monthStartLine;
            if(isset($sortForcast) and array_key_exists($key, $sortForcast)){  //======== forecast existe for this month ==========//
              $work=$sortForcast[$key]['work'];
              $sumActYearly +=$work;
            }
            $display .=   '<td '.excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,'work').'>';
            $display .= (($work!=0)?Work::displayWork($work):'');
            $display .=   '</td>';
            $monthStartLine++;
            $m++;
            if($monthStartLine==13)$monthStartLine=1;
          }
          $display .=   '<td '.excelFormatCell('data',null,null,$projeBackgroundExcel,null,'center',null,null,null).'>';
          $display .=(($sumActYearly!=0)?Work::displayWork($sumActYearly):'');
          $display .=   '</td>';
          $display .=  '<td '.excelFormatCell('data',null,null,$projeBackgroundExcel,null,'right',null,null,null).'>';
          $display .=(($cost!=0)?$cost:0);
          $display .=   '</td>';
          $display .=   '<td '.excelFormatCell('data',null,null,$projeBackgroundExcel,null,'right',null,null,null).'>';
          $display .=(($sumActYearly!=0 and $cost!=0)?$cost*$sumActYearly:0);
          $display .=   '</td>';
          
        }
        
        $display .= '</tr>';
        $cpAct++;
        $count++;
    
      }
      $display.= '</table>';
  }else{  // display in the application 
    for ($y=$starYear;$y < $endYear;$y++){
      $cpAct=0;
      $i=1;
      $display.= '<table  align="center" class="crossTable" style="width:95%;" '.excelName().'>';
      $display.=    '<tr class="reportHeader" style="height:32px;">';
      $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'></td>';
      $display .=     '<td style="width:12%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('Activity').'</td>';
      $monthStartHead=$monthStart;
      while($i<=12){
        $display .=     '<td style="width:4%" class="reportTableHeader"  '.excelFormatCell('header',10).'>'.i18n($monthTable[$monthStartHead-1]).'</td>';
        $monthStartHead++;
        if($monthStartHead==13)$monthStartHead=1;
        $i++;
      }
      $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('colTotal').'&nbsp;'.$y.'</td>';
      $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('colCostFunct').'</td>';
      $display .=     '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>'.i18n('sectionRevenue').'</td>';
      $display .=     '</tr>';
      $nbElement=count($tab);
      $count=0;
      foreach ( $tab as $id=>$obj ){
        $res=$obj['idResource'];
        $idAct=$obj['refId'];
        $idProj=$obj['idProject'];
        $actName=$obj['refName'];
        $display .= '   <tr >';
        if($lastReseource!=$res){
          $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.";":"";
          $projectC= ($natureProj->color)? PlgForecast::adjustBrightness($natureProj->color,0.5) :"";
          $projColor=($projectC!="")?"background-color:".$projectC.";":"";
          $lastIdProj=$idProj;
        }
        $cpAct++;
        $lastIdAct=$idAct;
        $display .=     '<td class="reportTableData" style="'.$projColor.$actNameColor.';text-align:left;padding:5px;" >';
                  $display .=$actName;
        $display .=     '</td>';
        $m=1;
        $sumActYearly=0;
        $monthStartLine=$monthStart;
        while($m<=12){
          $work=0;
          $key=$res.'_'.$idProj.'_'.$idAct.'_'.$y.'_'.$monthStartLine;
          if(isset($sortForcast) and array_key_exists($key, $sortForcast)){  //======== forecast existe for this month ==========//
            $work=$sortForcast[$key]['work'];
            $sumActYearly +=$work;
          }
          $display .=   '<td class="reportTableData" style="'.$projColor.';padding:5px;">';
          $display .=(($work!=0)?htmlDisplayNumericWithoutTrailingZeros($work):'');
          $display .=     '</td>';
          $monthStartLine++;
          $m++;
          if($monthStartLine==13)$monthStartLine=1;
        }
        $display .=   '<td class="reportTableData" style="'.$projColor.';padding:5px;" >';
        $display .=(($sumActYearly!=0)?htmlDisplayNumericWithoutTrailingZeros($sumActYearly):'');
        $display .=   '</td>';
        
        $display .=  '<td    class="reportTableData"  style="'.$projColor.';text-align:right;padding:5px;" >';
        $display .=htmlDisplayCurrency((($cost!=0)?$cost:0));
        $display .=   '</td>';
  //        $drawCost=false;
  //       }
        $display .=   '<td  class="reportTableData" style="'.$projColor.';text-align:right;" >';
        $display .=htmlDisplayCurrency((($sumActYearly!=0 and $cost!=0)?$cost*$sumActYearly:0)); 
        $display .=   '</td>';
        $display .= '</tr>';
        $count++;
        
      }
      if($count==$limit){
        $display .=  '<tr>';
        $display .=    '<td colspan="17">';
        $display .=      '<div style="background:#FFDDDD;font-size:150%;color:#808080;text-align:center;padding:15px 0px;width:100%;">'.i18n('limitedDisplay',array($cp)).'</div>';
        $display .=    '</td>';
        $display .=  '</tr>';
      }
      $display.= '</table>';
    }
  }
  
}else{ 
  if($paramPeriod<1)$message=i18n('chooseValidPerdiod');
  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: