<?php
/** Le dossier de l'environnement est le dossier parent du dossier 'modules' */
list($environmentPath) = explode(DIRECTORY_SEPARATOR.'modules', dirname(__FILE__));
$environmentPath .= DIRECTORY_SEPARATOR;

require_once $environmentPath . 'modules/base/php/startSession.php';
require_once $environmentPath . 'modules/base/php/Environnement.php';
require_once $environmentPath . 'modules/base/php/Functions.php';
require_once $environmentPath . 'modules/base/php/classDatabase.php';

$httpString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
$httpString .= "\r\n<HTTP_SERVICE>";

$databaseName = "iCTI";
$database = new Database($databaseName);

$sqlcmd = "SELECT * FROM pmsi.create_view_consolidation_imports_1()";
$result  =  $database->exec($sqlcmd);
$sqlcmd = "SELECT * FROM pmsi.create_view_chiffrier_imports_1()";
$result  =  $database->exec($sqlcmd);

// Chiffriers
$sqlcmd = <<<SQL
SELECT
	t_finess.code AS finess
	,t_finess.texte AS finess_texte
	,c_datemin
	,c_datemax
	,c_rsa
	,c_ca
	,d_datemin
	,d_datemax
	,d_rsa
	,d_ca
FROM base.t_finess
LEFT JOIN
	(
	 SELECT
		finess
		,MIN(mois || '01') AS c_datemin
		,MAX(mois || '01') AS c_datemax
		,SUM(nb_rsa) AS c_rsa
		,SUM(ca_sejour) AS c_ca
	 FROM pmsi.p_chiffrier
	 WHERE mois >= 200701
	 GROUP BY finess
	) subview_c
	ON (subview_c.finess = t_finess.code)
LEFT JOIN
	(
	 SELECT
		finess_id
		,MIN(mois || '01') AS d_datemin
		,MAX(mois || '01') AS d_datemax
		,SUM(nb_rsa) AS d_rsa
		,SUM(ca_sejour) AS d_ca
	 FROM pmsi.v_consolidation_chiffrier_1
	 WHERE mois >= 200701
	 GROUP BY finess_id
	) subview_d
	ON (subview_d.finess_id = t_finess.oid)
WHERE t_finess.secondaire = '1'
ORDER BY t_finess.code
;
SQL;

$result  =  $database->exec($sqlcmd);

if ($result != false) {

    $ok = TRUE;

    while ($ok == TRUE) {
        $ok = FALSE;

        $record = $database->nextRecordAssoc();
        if ($record != FALSE) {

            $ok = TRUE;

            $finess = trim($record['finess']);
            $finess_texte = toHTML(trim($record['finess_texte']));

            $min_conso = trim($record['c_datemin']);
            $max_conso = trim($record['c_datemax']);
            $rsa_conso = $record['c_rsa'];
            $ca_conso = $record['c_ca'];

            $min_det = trim($record['d_datemin']);
            $max_det = trim($record['d_datemax']);
            $rsa_det = $record['d_rsa'];
            $ca_det = $record['d_ca'];

            $node = <<<XML
            <CHIFFRIER
                finess="$finess"
                finess_texte="$finess_texte"
                min_det="$min_det"
                max_det="$max_det"
                rsa_det="$rsa_det"
                ca_det="$ca_det"
                min_conso="$min_conso"
                max_conso="$max_conso"
                rsa_conso="$rsa_conso"
                ca_conso="$ca_conso"
            />
XML;
            $httpString .= "\r\n$node";
        }
    }
}

// Imports
$sqlcmd = <<<SQL
SELECT
	v_consolidation_imports_1.oid
	,v_consolidation_imports_1.texte
	,v_consolidation_imports_1.date_import
	,v_consolidation_imports_1.etat
	,v_consolidation_imports_1.etat_en_cours
	,v_consolidation_imports_1.traitement_a_faire
	,finess_code AS finess
	,date_debut
	,date_fin
	,nb_rss
	,nb_rum
	,nb_rsf
	,nb_erreurs
	,nb_avertissements
	,t_finess_database.dbname
	,t_finess.texte AS finess_texte
FROM
	pmsi.v_consolidation_imports_1
	,base.t_finess_database
	,base.t_finess
WHERE v_consolidation_imports_1.finess_id = t_finess_database.finess_id
	AND v_consolidation_imports_1.finess_id = t_finess.oid
	AND v_consolidation_imports_1.date_fin >= '20070101'
ORDER BY t_finess.code
	,v_consolidation_imports_1.oid DESC
;
SQL;

$result  =  $database->exec($sqlcmd);

if ($result != false) {

    $ok = TRUE;

    while ($ok == TRUE) {
        $ok = FALSE;

        $record = $database->nextRecordAssoc();
        if ($record != FALSE) {

            $ok = TRUE;

            $oid = $record['oid'];
            $texte = toHTML(trim($record['texte']));
            $date_import = trim($record['date_import']);
            $etat = trim($record['etat']);
            $etat_en_cours = trim($record['etat_en_cours']);
            $traitement_a_faire = trim($record['traitement_a_faire']);
            $finess = trim($record['finess']);
            $date_debut = trim($record['date_debut']);
            $date_fin = trim($record['date_fin']);
            $nb_rss = trim($record['nb_rss']);
            $nb_rum = trim($record['nb_rum']);
            $nb_rsf = trim($record['nb_rsf']);
            $nb_erreurs = trim($record['nb_erreurs']);
            $nb_avertissements = trim($record['nb_avertissements']);
            $dbname = trim($record['dbname']);

            /** Informations d'autentification communes */
            $dbuser = $database->user;
            $dbpassword = $database->password;

            $finess_texte = toHTML(trim($record['finess_texte']));

            $node = <<<XML
            <IMPORT
                oid="$oid"
                texte="$texte"
                date_import="$date_import"
                etat="$etat"
                etat_en_cours="$etat_en_cours"
                traitement_a_faire="$traitement_a_faire"
                finess="$finess"
                date_debut="$date_debut"
                date_fin="$date_fin"
                nb_rss="$nb_rss"
                nb_rum="$nb_rum"
                nb_rsf="$nb_rsf"
                nb_erreurs="$nb_erreurs"
                nb_avertissements="$nb_avertissements"
                dbname="$dbname"
                dbuser="$dbuser"
                dbpassword="$dbpassword"
                finess_texte="$finess_texte"
            />
XML;
            $httpString .= "\r\n$node";
        }
    }
}

// Historique des travaux

// travaux actifs
$httpString .= getJobs("active");
// travaux terminés
$httpString .= getJobs("endded");

$httpString .= "\r\n</HTTP_SERVICE>";

$httpString = gzcompress($httpString,9);
$httpString = "_c_" . base64_encode($httpString);

echo "<CTICONTENT>$httpString</CTICONTENT>";

// recherche historique des travaux
function getJobs($type) {

	$httpString = "";

	global $jobs;
	global $jobsDate;
	global $jobsType;

	if ($type == "active") {
		$path = rootDir() . "system/batch/activejobs";
	}
	else {
		$path = rootDir() . "system/batch/jobs";
	}
	
	// lecture
	$rep=@opendir($path);
	if ($rep > 0) {
		while ($file = readdir($rep)){
			if($file != '..' && $file !='.' && $file !=''  ){
				$suffix = strtolower(substr($file,strlen($file)-4));
				if ($suffix == ".pid") {
					$longFile = $path . '/' . $file;
					
					$pid="";
					$name="";
					$module="";
					$title="";
					$start="";
					$end="";
					$endStatus="";
					$duration="";
					$log="";
					
					if ($type == "active") {
						$endStatus="En cours";
						$end="En-cours";
					}
					
					
					$handle = @fopen($longFile, "r");
					$contents = "";
					while (!feof($handle)) {
						$contents = @fgets($handle);
						if (substr($contents, 0, 4) == 'pid=') {
							$pid = trim(substr($contents, 4, strlen($contents)-4));
						}
						if (substr($contents, 0, 5) == 'name=') {
							$name = trim(substr($contents, 5, strlen($contents)-5));
						}
						if (substr($contents, 0, 7) == 'module=') {
							$module = trim(substr($contents, 7, strlen($contents)-7));
						}
						if (substr($contents, 0, 6) == 'title=') {
							$title = trim(substr($contents, 6, strlen($contents)-6));
						}
						if (substr($contents, 0, 6) == 'start=') {
							$start = trim(substr($contents, 6, strlen($contents)-6));
						}
						if (substr($contents, 0, 4) == 'end=' && $type != "active") {
							$end = trim(substr($contents, 4, strlen($contents)-4));
						}
						if (substr($contents, 0, 9) == 'duration=') {
							$duration = trim(substr($contents, 9, strlen($contents)-9));
							$duration = mktime(0, 0, $duration, 1, 1, 2007);
							$duration = date("G:i:s", $duration);
						}
						if (substr($contents, 0, 10) == 'endStatus=' && $type != "active") {
							$endStatus = trim(substr($contents, 10, strlen($contents)-10));
						}
						if (substr($contents, 0, 4) == 'log=') {
							$log = trim(substr($contents, 4, strlen($contents)-4));
						}
					}
					@fclose($handle);

                    if ($pid !== '' && (strtolower($name) === "icti_consolidation_pmsi" || strtolower($name) === "icti_consolidation_pmsi_2")) {
                        $node = <<<XML
                        <JOB
                            pid="$pid"
                            logFile="$log"
                            name="$name"
                            module="$module"
                            title="$title"
                            start="$start"
                            end="$end"
                            duration="$duration"
                            endStatus="$endStatus"
                            pidfile="$longFile"
                        />
XML;
                        $httpString .= "\r\n$node";
                    }
				}
			}
		}
	}
	@closedir($rep);
	
	return $httpString;
}