<?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';
require_once "../tool/formatter.php";

$paramProject = trim(RequestHandler::getId('idProject'));
$paramTeam = trim(RequestHandler::getId('idTeam'));
$idOrganization = trim(RequestHandler::getId('idOrganization'));
$idDepartement = trim(RequestHandler::getId('idDepartementPlg'));
$idDirection = trim(RequestHandler::getId('idDirectionPlg'));
$paramYear = RequestHandler::getYear('yearSpinner');
$paramMonth = RequestHandler::getMonth('monthSpinner');
$paramWeek = RequestHandler::getValue('weekSpinner');

$user=getSessionUser();

$periodType=RequestHandler::getValue('periodType'); // not filtering as data as data is only compared against fixed strings
$periodValue='';
if (array_key_exists('periodValue',$_REQUEST))
{
	$periodValue=$_REQUEST['periodValue'];
	$periodValue=Security::checkValidPeriod($periodValue);
}

// Header
$headerParameters="";
if ($paramProject!="") {
  $headerParameters.= i18n("colIdProject") . ' : ' . htmlEncode(SqlList::getNameFromId('Project', $paramProject)) . '<br/>';
}
if ($idOrganization!="") {
  $headerParameters.= i18n("colIdOrganization") . ' : ' . htmlEncode(SqlList::getNameFromId('Organization',$idOrganization)) . '<br/>';
}
if ($paramTeam!="") {
  $headerParameters.= i18n("colIdTeam") . ' : ' . htmlEncode(SqlList::getNameFromId('Team', $paramTeam)) . '<br/>';
}
if ($idDepartement!="") {
	$headerParameters.= i18n("colIdDepartementPlg") . ' : ' . htmlEncode(SqlList::getNameFromId('DepartementPlg',$idDepartement)) . '<br/>';
}
if ($idDirection!="") {
	$headerParameters.= i18n("colIdDirectionPlg") . ' : ' . htmlEncode(SqlList::getNameFromId('DirectionPlg', $idDirection)) . '<br/>';
}
if ($periodType=='year' or $periodType=='month' or $periodType=='week') {
  $headerParameters.= i18n("year") . ' : ' . $paramYear . '<br/>';
}
//ADD qCazelles - Report fiscal year - Ticket #128
if ($periodType=='year' and $paramMonth!="01") {
  if (!$paramMonth ) {
    echo '<div style="background: #FFDDDD;font-size:150%;color:#808080;text-align:center;padding:20px">';
    echo i18n('messageNoData',array(i18n('month'))); // TODO i18n message
    echo '</div>';
    if (!empty($cronnedScript)) goto end; else exit;
  } else {
    $headerParameters.= i18n("startMonth") . ' : ' . i18n(date('F', mktime(0,0,0,$paramMonth,10))) . '<br/>';
  }
}
//END ADD qCazelles - Report fiscal year - Ticket #128
if ($periodType=='month') {
  $headerParameters.= i18n("month") . ' : ' . $paramMonth . '<br/>';
}
if ( $periodType=='week') {
  
  $headerParameters.= i18n("week") . ' : ' . $paramWeek . '<br/>';
}
if (isset($outMode) and $outMode=='excel') {
  $headerParameters.=str_replace('- ','<br/>',Work::displayWorkUnit()).'<br/>';
}

include "header.php";
$where="1=1";
$where.=($periodType=='week')?" and week='" . $periodValue . "'":'';
$where.=($periodType=='month')?" and month='" . $periodValue . "'":'';
if ($periodType=='year') {
  if (!$periodValue ) {
    echo '<div style="background: #FFDDDD;font-size:150%;color:#808080;text-align:center;padding:20px">';
    echo i18n('messageNoData',array(i18n('year'))); // TODO i18n message
    echo '</div>';
    if (!empty($cronnedScript)) goto end; else exit;
  }
  if ($paramMonth<10) $paramMonth='0'.intval($paramMonth);
  $where.=" and ((year='" . $periodValue . "' and month>='" . $periodValue.$paramMonth . "')".
          " or (year='" . ($periodValue + 1) . "' and month<'" . ($periodValue + 1) . $paramMonth . "'))";
}
if ($paramProject!='') {
  $where.=  " and idProject in " . getVisibleProjectsList(false, $paramProject); 
}
$order="idProject asc";
$work=new Work();
$lstWork=$work->getSqlElementsFromCriteria(null,false, $where, $order);
$workSum = array();
$activity = array();
$date = array();
$listResOrg = array();

if($idOrganization){
  $orga = new Organization($idOrganization);
  $listResOrg=$orga->getResourcesOfAllSubOrganizationsListAsArray();
}

$assignmentComment=array();
foreach ($lstWork as $wrk){
	
	$res = new Resource($wrk->idResource, true);
	if($paramTeam and $res->idTeam!=$paramTeam)continue;
	if(property_exists('Resource', 'idDepartementPlg') and $idDepartement and $res->idDepartementPlg!=$idDepartement)continue;
	if(property_exists('Resource', 'idDirectionPlg') and $idDirection and $res->idDirectionPlg!=$idDirection)continue;
	if(count($listResOrg)>0 and !in_array($wrk->idResource, $listResOrg))continue;
	
	if(isset($workSum[$wrk->idResource][$wrk->idProject])){
		$workSum[$wrk->idResource][$wrk->idProject] += $wrk->work;
	}else{
		$workSum[$wrk->idResource][$wrk->idProject] = $wrk->work;
	}
	$month = $periodType;
	if($periodType == "year")$month = 'month';
	if (!isset($date[$wrk->$month])) $date[$wrk->$month]=array();
	$date[$wrk->$month][$wrk->idResource] = $workSum[$wrk->idResource];
	if (!isset($assignmentComment[$wrk->idAssignment])) $assignmentComment[$wrk->idAssignment]=array();
	if (!isset($assignmentComment[$wrk->idAssignment][$wrk->$month])) {
	  if ($periodType=='week') $periodValue='W'.$wrk->$month;  
	  else $periodValue='M'.$wrk->$month; 
	  $assignmentComment[$wrk->idAssignment][$wrk->$month]=getCommentForActivity($wrk->idAssignment,$periodValue);
	  if(!isset($activity[$wrk->idResource][$wrk->idProject])) $activity[$wrk->idResource][$wrk->idProject]=array();
	  if(isset($activity[$wrk->idResource][$wrk->idProject][$wrk->$month])){
	    $activity[$wrk->idResource][$wrk->idProject][$wrk->$month] .= "\n".$assignmentComment[$wrk->idAssignment][$wrk->$month];
	  } else {
	    $activity[$wrk->idResource][$wrk->idProject][$wrk->$month]=$assignmentComment[$wrk->idAssignment][$wrk->$month];
	  }
	}
	
}
echo '<table style="width:95%;" align="center" '.excelName().'>';
echo '<tr><td colspan="5" class="reportTableHeader" '.excelFormatCell('header',80).'>'.i18n('natureColor').'</td></tr>';
echo '<tr><td colspan="5" class="reportTableData"  '.excelFormatCell('data',null,null,'#ccffff',null,'left',null,null).' style="background-color:#ccffff;text-align:left;">sont facturés conformément au forfait contractuel</td></tr>';
echo '<tr><td colspan="5" class="reportTableData"  '.excelFormatCell('data',null,null,'#ffffff',null,'left',null,null).' style="background-color:#ffffff;text-align:left;">sont facturés conformément au nbre de journées indiqués sur la colonne journées à facturer</td></tr>';
echo '<tr><td colspan="5" class="reportTableData"  '.excelFormatCell('data',null,null,'#ccffcc',null,'left',null,null).' style="background-color:#ccffcc;text-align:left;">ne peuvent être facturés que si on procède à un changement du compte, ou si on facture un forfait</td></tr>';
echo '<tr><td colspan="5" class="reportTableData"  '.excelFormatCell('data',null,null,'#ff99cc',null,'left',null,null).' style="background-color:#ff99cc;text-align:left;">ne peuvent être facturés que si on procède à un changement du compte, ou si on facture un forfait</td></tr>';
echo '<tr><td colspan="5" '.excelFormatCell('data',null,null,null,null,'left',null,null,null).'><br></td></tr>';
echo '<tr>';
echo '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>' . i18n('months') . '</td>';
echo '<td style="width:5%" class="reportTableHeader"  '.excelFormatCell('header',20).'>' . i18n('resourceId') . '</td>';
echo '<td style="width:15%" class="reportTableHeader"  '.excelFormatCell('header',40).'>' . i18n('resourceName') . '</td>';
echo '<td style="width:5%" class="reportTableHeader"  '.excelFormatCell('header',20).'>' . i18n('projectId') . '</td>';
echo '<td style="width:25%" class="reportTableHeader"  '.excelFormatCell('header',40).'>' . i18n('projectName') . '</td>';
echo '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>' . i18n('work') . '</td>';
echo '<td style="width:30%" class="reportTableHeader"  '.excelFormatCell('header',60).'>' . i18n('Activity') . '</td>';
echo '</tr>';
foreach ($date as $month=>$workList){
  foreach ($workList as $idResource=>$projectList){
    foreach ($projectList as $idProject=>$work){
        if(property_exists('Resource', 'resourceId')){
          $resourceId = SqlList::getFieldFromId('Resource', $idResource, 'resourceId', false);
        }else{
          $resourceId = $idResource;
        }
        if(property_exists('Resource', 'resourceName')){
          $resourceName = SqlList::getFieldFromId('Resource', $idResource, 'resourceName', false);
        }else{
          $resourceName = SqlList::getNameFromId('Resource', $idResource, false);
        }
        if(property_exists('Project', 'projectId')){
          $projectId = SqlList::getFieldFromId('Project', $idProject, 'projectId', false);
        }else{
          $projectId = $idProject;
        }
        if(property_exists('Project', 'projectName')){
          $projectName = SqlList::getFieldFromId('Project', $idProject, 'projectName', false);
        }else{
          $projectName = SqlList::getNameFromId('Project', $idProject, false);
        }
        $activityList = (isset($activity[$idResource][$idProject][$month]))?htmlEncode($activity[$idResource][$idProject][$month], "html"):'';
        echo '<tr>';
        $dateValue = null;
        if($periodType == 'month' or $periodType == 'year'){
        	$lbMonth = substr(i18n(date('F', mktime(0,0,0,substr($month, 4),1))), 0, 3);
        	$lbYear = date('y', mktime(0,0,0,substr($month, 4),1));
        	$dateValue = $lbMonth.'-'.$lbYear;
        }
        if($periodType == 'week'){
        	$lbMonth = substr(i18n(date('F', firstDayofWeek(substr($month, 4), substr($month, 0, 4)))), 0, 3);
        	$lbYear = date('y', firstDayofWeek(substr($month, 4), substr($month, 0, 4)));
        	$dateValue = $lbMonth.'-'.$lbYear;
        }
    	echo '<td style="width:10%;text-align:left;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'left',null,null,(($dateValue)?$dateValue:null)).'>' . $dateValue . '</td>';
    	echo '<td style="width:5%;text-align:center;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'center',null,null,(($resourceId)?$resourceId:null)).'>' . $resourceId . '</td>';
    	echo '<td style="width:15%;text-align:left;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'left',null,null,(($resourceName)?$resourceName:null)).'>' . $resourceName . '</td>';
    	echo '<td style="width:5%;text-align:center;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'center',null,null,(($projectId)?$projectId:null)).'>' . $projectId . '</td>';
    	echo '<td style="width:25%;text-align:left;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'left',null,null,(($projectName)?$projectName:null)).'>' . $projectName . '</td>';
    	$excelWork = Work::displayWorkWithUnit($work);
    	if (isset($outMode) and $outMode=='excel') {
    		$excelWork = $work;
    	}
    	echo '<td style="width:10%;text-align:center;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'center',null,null,'work').'>' . $excelWork . '</td>';
    	echo "<td style='width:30%;text-align:left;' class='reportTableData'  ".excelFormatCell('data',null,null,null,null,'left',null,null,(($activityList)?$activityList:null)).">$activityList</td>";
    	echo '</tr>';
    }
  }
}
echo '</table>';
end:

function getCommentForActivity($idAss,$period) {
  $periodType=substr($period,0,1);
  $periodValue=substr($period,1);
  if ($periodType=='W') {
    $startWeek=$periodValue;
    $endWeek=$periodValue;
  } else {
    $year=substr($periodValue,0,4);
    $month=substr($periodValue,4);
    $startWeek=getWeekNumberFromDate($year.'-'.$month.'-01');
    $endWeek=getWeekNumberFromDate(substr($periodValue,0,4).'-'.substr($periodValue,4).'-'.lastDayOfMonth($month,$year));
  }
  $ass=new Assignment($idAss);
  $split=explode("\n\n",$ass->comment);
  $str="";
  foreach($split as $com) {
    $var=explode(']: ',$com);
    if (count($var)>1) {
      $dt=str_replace('-','',substr($var[0],1));
      $val=$var[1];
    } else {
      $dt=null;
      $val=$var[0];
    }
    if ( $dt>=$startWeek and $dt<=$endWeek ) {
      if ($str!='') $str.="\n";
      $str.=$val;
    }
  }           
  return $str;
}