<?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';

$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); 
}

$where .=" and idAssignment is not null";

$order="idProject asc";
$work = new Work();
$lstWork=$work->getSqlElementsFromCriteria(null,false, $where, $order);
$workSum = array();
$activity = array();
$date = array();
$cost = array();
$ass = array();
$listResOrg = array();

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

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->idAssignment][$wrk->idProject])){
    $workSum[$wrk->idAssignment][$wrk->idProject] += round($wrk->work, 2);
  }else{
    $workSum[$wrk->idAssignment][$wrk->idProject] = round($wrk->work, 2);
  }
  if(isset($cost[$wrk->idAssignment][$wrk->idProject])){
  	$cost[$wrk->idAssignment][$wrk->idProject] += round($wrk->cost, 2);
  }else{
  	$cost[$wrk->idAssignment][$wrk->idProject] = round($wrk->cost, 2);
  }
  if(isset($activity[$wrk->idAssignment][$wrk->idProject])){
    $name = SqlList::getNameFromId($wrk->refType, $wrk->refId, false);
    if(strpos($activity[$wrk->idAssignment][$wrk->idProject],$name) === false){
      $activity[$wrk->idAssignment][$wrk->idProject] .= ' / '.$name;
    }
  }else{
  	$name = SqlList::getNameFromId($wrk->refType, $wrk->refId, false);
  	$activity[$wrk->idAssignment][$wrk->idProject] = $name;
  }
  $ass[$wrk->idResource][$wrk->idAssignment] = $workSum[$wrk->idAssignment];
  $month = $periodType;
  if($periodType == "year")$month = 'month';
  $date[$wrk->$month][$wrk->idResource] = $ass[$wrk->idResource];
}
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:15%" 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:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>' . i18n('cost') . '</td>';
echo '<td style="width:10%" class="reportTableHeader"  '.excelFormatCell('header',20).'>' . i18n('revenue') . '</td>';
echo '<td style="width:20%" class="reportTableHeader"  '.excelFormatCell('header',60).'>' . i18n('Activity') . '</td>';
echo '</tr>';
foreach ($date as $month=>$assList){
  foreach ($assList as $idResource=>$workList){
    foreach ($workList as $idAssignment=>$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 = htmlEncode($activity[$idAssignment][$idProject]);
    		$lineCost = $cost[$idAssignment][$idProject];
    		$revenue = $lineCost*$work;
    		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:15%;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)?$work:null)).'>' . $excelWork . '</td>';
  	        $excelLineCost = htmlDisplayCurrency($lineCost);
    		if (isset($outMode) and $outMode=='excel') {
    		  $excelLineCost = $lineCost;
    		}
    		echo '<td style="width:10%;text-align:right;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'right',null,null,(($lineCost)?$lineCost:null)).'>' . $excelLineCost . '</td>';
    	    $excelRevenue = htmlDisplayCurrency($revenue);
    		if (isset($outMode) and $outMode=='excel') {
    		  $excelRevenue = $revenue;
    		}
    		echo '<td style="width:10%;text-align:right;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'right',null,null,(($revenue)?$revenue:null)).'>' . $excelRevenue . '</td>';
    		echo '<td style="width:20%;text-align:left;" class="reportTableData"  '.excelFormatCell('data',null,null,null,null,'left',null,null,(($activityList)?$activityList:null)).'>' . $activityList . '</td>';
    		echo '</tr>';
    	} 
    }
  }
}
echo '</table>';
end: