<?php ob_start();
include_once '../tool/projeqtor.php';

$user=getSessionUser();
// ---------------------------
// Filters
// ---------------------------
$globalCrit="";
$critProject=RequestHandler::getId('idProject');
if ($critProject and $critProject>0) {
  $globalCrit.=($globalCrit)?' and ':'';
  $globalCrit.='idProject in '.getVisibleProjectsList(false,$critProject);
} /*else {
  $globalCrit.=($globalCrit)?' and ':'';
  $globalCrit.='idProject in '.transformListIntoInClause($user->getVisibleProjects(false));
}*/
$critDomaine=RequestHandler::getId('idTicketType');
if ($critDomaine and $critDomaine>0) {
  $globalCrit.=($globalCrit)?' and ':'';
  $globalCrit.='idTicketType='.Sql::fmtId($critDomaine);
}
$critRequestor=RequestHandler::getId('requestor');
if ($critRequestor and $critRequestor>0) {
  $globalCrit.=($globalCrit)?' and ':'';
  $globalCrit.='idContact='.Sql::fmtId($critRequestor);
}
$critRespoFonc=RequestHandler::getId('plgIdResponsablefonctionnel__idResource');
if ($critRespoFonc and $critRespoFonc>0) {
	$globalCrit.=($globalCrit)?' and ':'';
	$globalCrit.='IdResponsablefonctionnel__idResource='.Sql::fmtId($critRespoFonc);
}
$critOrganization=RequestHandler::getId('idOrganization');
if ($critOrganization and $critOrganization>0) {
	$globalCrit.=($globalCrit)?' and ':'';
	$globalCrit.='idOrganization='.Sql::fmtId($critOrganization);
}
$critClient=RequestHandler::getId('idClient');
if ($critClient and $critClient>0) {
	$globalCrit.=($globalCrit)?' and ':'';
	$globalCrit.='idClient='.Sql::fmtId($critClient);
}

// ---------------------------
// Initialize the TBS instance
// --------------------------- 
require_once '../external/tbs/tbs_class.php';
require_once '../external/tbs/plugins/tbs_plugin_opentbs.php';
if (version_compare(PHP_VERSION,'5.1.0')>=0 and ini_get('date.timezone')=='') { date_default_timezone_set('UTC');	} // prevent from a PHP configuration problem when using mktime() and date()
$TBS = new clsTinyButStrong; // new instance of TBS 
$TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN); // load the OpenTBS plugin 
$debug=""; // possible values = "current", "info", "show"

// ------------------------------ 
// Prepare data
// ------------------------------ 
$global=array();$global[0]=array();
$date = date('d/m/Y'); // current date 
$global[0]['username'] = $user->resourceName; // user name
$global[0]['date'] = date('Y-m-d');

// -----------------
// Load the template
// -----------------
$template = '../report/template/PortefeuilleDemandes.xlsx';
$TBS->LoadTemplate($template, OPENTBS_ALREADY_UTF8); // Also merge some [onload] automatic fields (depends of the type of document).

$TBS->PlugIn(OPENTBS_SELECT_SHEET, 1);
$TBS->MergeBlock('global', $global);

$ticket=new Ticket();

$crit=$globalCrit;
//$crit.="idle=0";
$list=$ticket->getSqlElementsFromCriteria(null,null,$crit,'reference asc');

$list=addExtraData($list);
$data = SqlElement::toArrayList($list);
fixNameForReference($data);
$TBS->MergeBlock('dmd', $data); 


// Define the name of the output file 
$output_file_name = str_replace('.xlsx', '_'.date('Ymd').'.xlsx', basename($template));
// Options
$TBS->SetOption('noerr', true); 
// Output the result as a downloadable file (only streaming, no data saved in the server) 
ob_get_clean();
$TBS->Show(OPENTBS_DOWNLOAD, $output_file_name); // Also merges all [onshow] automatic fields. 

function addExtraData($list) {
  $result=array();
   foreach ($list as $key=>$obj) {
     foreach ($obj as $fld=>$val) {
       $dataType=$obj->getDataType($fld);
       $dataLength=$obj->getDataLength($fld);
       if (substr($fld,0,2)=='id' and strpos($fld,'__')>0) {
         $class=substr($fld,strpos($fld,'__')+4);
         $extFld='name'.substr($fld,2);
         $obj->$extFld=SqlList::getNameFromId($class,$val);
       }
       if ($dataType=='int' and $dataLength==1) {
         $extFld=$fld.'_OuiNon';
         $obj->$extFld=($val==1)?'OUI':'NON';
         $extFld=$fld.'_Check';
         $obj->$extFld=($val==1)?'X':'';
       }
       if ($dataType=='datetime' ) {
         $obj->$fld=substr($val,0,10);
       }       
       if ($dataType=='decimal' ) {
         $noFmt=$fld.'NoFormat';
         $obj->$noFmt=$val;
       }
     }
     $result[]=$obj;
   }
    return $result;
}
function fixNameForReference(&$data) {
  foreach ($data as $key=>$tab) {
    foreach ($tab as $fld=>$val) {
      if (substr($fld,0,4)=='name' and strpos($fld,'__')>0) { // This is idXxxxx_idClass => its value will erase correct value for nameClass (Fixed on V8.0.5)
        $class=substr($fld,strpos($fld,'__')+4);
        if (isset($tab['name'.$class]) and isset($tab['id'.$class])) {
          $data[$key]['name'.$class]=SqlList::getNameFromId($class,$tab['id'.$class]);
        }
      } else if ((substr($fld,0,4)=='date' or substr($fld,-4)=='Date' or substr($fld,-8)=='DateTime' ) and (strlen($val)==10 or strlen($val)==19)) {
        $data[$key][$fld]=addDaysToDate(substr($val,6,4).'-'.substr($val,3,2).'-'.substr($val,0,2),1);
      }
      
    }
    
  }
  
}