<?php

require_once("../../base/php/startSession.php");
require_once("../../base/php/Environnement.php" );
require_once("../../base/php/Functions.php" );
require_once("../../base/php/classDatabase.php");
require_once("../../base/php/class_HttpCTISante.php" );
require_once("../../base/php/WebAppLog.php");
require_once("../../outils/php/httpService_cacheManager_cleanCache.php");
require_once("../../base/php/lib/cti/Http/HttpFactory.class.php" );
require_once("../../base/php/classSimpleXML.php");
require_once('../../base/php/lib/cti/Database/Database2Factory.class.php');
require_once('../../base/php/lib/cti/Environnement/Environnement.class.php');
require_once("../../../modules/base/php/lib/cti/Batch/iCTI_batch_common.php" );


global $finess;
global $serverName;

global $database;
global $tmp_path;
global $tmp_RSSoutfile;
global $typeEts;

set_time_limit(3600);


$operation	 = $_POST['operation'];
$fileFG12	 = $_POST['file'];
$fg_year	 = $_POST['FG_YEAR'];

// A CONFIGURER : Année de sortie de la Fonction Groupage
define('FG_YEAR', $fg_year);
// A CONFIGURER : Année de sortie des dossiers a extraire (par defaut = FG_YEAR) 
// mais on peut travailler sur l'année précédente en modifiant en DUR lors de l'extraction
define('FG_YEAR_RSS', $fg_year);
// A CONFIGURER : Version de la Fonction Groupage et de la Classification des GHM
define('FG_VERSION', 'fg' . substr((FG_YEAR - 1), 2, 2) . substr((FG_YEAR), 2, 2) );
// A CONFIGURER : Site CTI Santé
$siteCTI	 = "www.ctisante.com";
// A CONFIGURER : PHP distant
$CTISantePHP = "simulation/PMSI_simulation_serveur.php";
// A CONFIGURER : Taille en octet des portions de fichier à envoyer en HTTP
define('BUFFER_SIZE', 5000);
// Chemin complet de la racine du repertoire CTI
define('__ROOT__', dirname(dirname(dirname(dirname(__FILE__)))) . '/');




// Définition des extentions de fichier
$extCurrent			 = '.NG'; // Non Groupé
$fg0FileExt			 = "_" . strtoupper(FG_VERSION) . $extCurrent; // Non Groupé
if (FG_YEAR_RSS <> FG_YEAR) {
	$fg0FileExt			 = "_" . FG_YEAR . "VS" . (FG_YEAR_RSS-1) . "_" . strtoupper(FG_VERSION) . $extCurrent; // Non Groupé
}
$fg1FileExt			 = "_" . strtoupper(FG_VERSION) . "." . strtoupper(FG_VERSION); // Groupé
// Définition des fichiers
// $fileFG12	 = $_POST['file']; correspond au fichier de base non groupe -> support pour récupérer le nom de fichier
$manual_file     =   "_MANUEL";
if (isset($fileFG12)) {
	$fileFG13		 = substr($fileFG12, 0, strlen($fileFG12) - strlen($fg1FileExt)) . $fg1FileExt;
	$manual_file	 = $fileFG13 . "_MANUEL";
}


// Calcul des dates clés : 1er mars => 31 déc. => 1 janv. => 28/29 fév.
$d1					 = (FG_YEAR_RSS - 1) . '-03-01';
$d2					 = (FG_YEAR_RSS - 1) . '-12-31';
$d3					 = FG_YEAR_RSS . '-01-01';
$d4					 = FG_YEAR_RSS . '-02-' . date('d', mktime(0, 0, 0, 3, 0, FG_YEAR_RSS));
$d5					 = FG_YEAR . '-03-01';
// Tables temporaire et de simulation
$tempTableFG		 = "w_simulation_" . FG_VERSION;
$simulationTableFG	 = "p_simulation_" . FG_VERSION;
$tempTableLPP		 = "w_lpp_" . FG_VERSION;
$tempTableUCD		 = "w_ucd_" . FG_VERSION;
$tempTableSuppl		 = "w_simulation_suppl_" . FG_VERSION;

$environmentVars=array();
$environmentVars["DATE_1"] = $d1;
$environmentVars["DATE_2"] = $d2;
$environmentVars["DATE_3"] = $d3;
$environmentVars["DATE_4"] = $d4;
$environmentVars["DATE_5"] = $d5;
$environmentVars["tempTableFG"] = $tempTableFG;
$environmentVars["simulationTableFG"] = $simulationTableFG;
$environmentVars["tempTableLPP"] = $tempTableLPP;
$environmentVars["tempTableUCD"] = $tempTableUCD;
$environmentVars["FG_YEAR"] = FG_YEAR;
$environmentVars["FG_YEAR_RSS"] = FG_YEAR_RSS;
$environmentVars["typeEts"] = $typeEts;
$environmentVars["tempTableSuppl"] = $tempTableSuppl;


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

$return_code			 = "OK";
$return_message			 = "";
$return_warning			 = "";
$return_complement		 = "";
$return_complement_v1	 = "";
$return_complement_v2	 = "";
$return_complement_v3	 = "";

$httpCTISante = new HttpCTISante();

$_finess	 = utf8_encode($finess);
$_serverName = utf8_encode($serverName);
$_serverName = strtoupper($_serverName);
$_serverName = str_replace("-", "", $_serverName);
$_serverName = str_replace("_", "", $_serverName);
$_serverName = str_replace(".", "", $_serverName);


$tmp_path		 = rootDir() . "temp";
$remote_file	 = "$_finess" . "_" . "$_serverName" . $fg0FileExt;
$local_file		 = $tmp_path . "/" . $remote_file;
$headerFG12 = utf8_encode( "$_finess" . "_" . "$_serverName" );
if (FG_YEAR_RSS <> FG_YEAR) {
	$headerFG12 = utf8_encode( "$_finess" . "_" . "$_serverName" . "_" . FG_YEAR . "VS" . (FG_YEAR_RSS-1) );
}

$http_connect = HttpFactory::createInstance();
$url = $siteCTI . "/" . $CTISantePHP ;


// Connexion base de données.
$database = new Database("iCTI");

// Connexion iCTI
$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
                                  

// Selon la commande envoyé depuis le swf action:
switch ($operation) {
    case kill_all:
		$to_operation = "kill_all";

		$content = $httpCTISante->get_streamdata($CTISantePHP . "?header=$headerFG12&operation=$to_operation");

		$contentNode = @simplexml_load_string($content);
		if ($contentNode) {
			if ($contentNode["returnCode"] != "OK") {
				$return_code	 = "KO";
				$return_message	 = "Erreur lors du ménage http http (1) " . $contentNode["returnMessage"];
			}
		} else {
			$return_code	 = "KO";
			$return_message	 = "Erreur lors du ménage http http (2) " . $content;
		}
		if ($return_code == "OK") {
			$return_message = $contentNode["returnSize"] . " fichier(s) supprimé(s)";
		}
        break;
    case get_list:
		$messages = array();

		// Controle GHS
		$sqlcmd	 = "select count(*) from pmsi.t_ghs where '$d5'::date IN (date_debut_prive_1, date_debut_prive_2,date_debut_prive_3,date_debut_prive_4,date_debut_prive_5,date_debut_prive_6,date_debut_prive_7,date_debut_prive_8,date_debut_prive_9)";
		$result	 = $database->exec($sqlcmd);
		if ($result !== false) {
			$record = $database->nextRecordInto();
			if ($record !== false) {
				if ($record[0] == 0) {
					$tmpDate	 = new DateTime($d5);
					$messages[]	 = "Pas de GHS daté du " . $tmpDate->format('d/m/Y') . ".\rVous devriez actualiser les tables PMSI.";
				}
			}
		}

		// Traitement des messages d'avertissement.
		$return_warning = (count($messages) > 0 ? 'ATTENTION' . PHP_EOL : '') . implode(PHP_EOL, $messages);

		// recuperation liste
		$params = array('header'=>$headerFG12,
						'operation'=>"get_list",
					 	'FG_YEAR'=>"$fg_year",
					 	'PMSI_TYPE'=>"MCO"
						);	


		$returnContentNode = url_request($http_connect, $url ,$params, "Erreur lors de l'initialisation de la liste " , $headerFG12, '',  "get_list");

		if ($returnContentNode['return_code'] == 'OK') {
			$contentNode = $returnContentNode['return_content'];
			foreach ($contentNode->FILE as $fileNode) {
				$httpString .= "\n" . $fileNode->asXML();
			}
		}

        break;
    case send_file:

    	// Vérification présence d'imports sur année N et N-1 et récupére les id
		$result = getLastImports($database, $d1);
		
		// Si on a des imports alors on va recuperer les fichiers RSS des differents import, les compiler pour les transformer partiellement et enfin envoye sur le servuer pour la suite envoi groupeur
		if ($result['return_code'] == "OK" ) {

			$tmp_RSSoutfile = $tmp_path . "/rss_out.txt";
			if (file_exists($tmp_RSSoutfile)){
				unlink($tmp_RSSoutfile);
			}			

			// Unites medicales
			extract_um();

			// récupére les rss les tarnsforme et les ecrits dans un nouveau fichier globalise pour tous les imports disponibles
			foreach ($result as $import => $value){

                switch ($import ){
                    CASE 'import_id_N_moins_1_editeur_1' :
                    CASE 'import_id_N_moins_1_editeur_2':
                        $year_import = FG_YEAR_RSS - 1;
                        break ;
                    CASE 'import_id_N_editeur_1' : CASE 'import_id_N_editeur_2':
                        $year_import = FG_YEAR_RSS;
                        break;
                    default :
                        $year_import = FG_YEAR_RSS;
                        break;
                }

				$tmp_RSSinfile = '';
				if ($import != 'return_code'){
					if ($value > 0){
						$tmp_RSSinfile = extract_rss($value, $year_import);
						transform_extract_rss( $tmp_RSSinfile, $tmp_RSSoutfile, $year_import );
					}
				}
			}
			// envoi vers le serveur
			$dataFG12 = compress64(file_get_contents($tmp_RSSoutfile));
			file_put_contents($local_file, $dataFG12);

			$fileFG12		 = utf8_encode($remote_file);
			$fileFG12_size	 = filesize($local_file);

			$to_operation	 = "send_init";
			$start			 = 0;

			while ($start <= $fileFG12_size) {
				$dataFG12_5000 = file_get_contents($local_file, FALSE, NULL, $start, BUFFER_SIZE);

				$params = array(
					'file'		 => $fileFG12,
					'data'		 => $dataFG12_5000,
					'operation'	 => $to_operation
				);

				$url = $siteCTI . "/" . $CTISantePHP ;
				$content = $http_connect->get($url, $params);
				
				$contentNode = @simplexml_load_string($content);
				if ($contentNode) {
					if ($contentNode["returnCode"] != "OK") {
						$return_code	 = "KO";
						$return_message	 = "Erreur lors de l'envoi http (1)";
						break;
					}
				} 
				else {
					$return_code	 = "KO";
					$return_message	 = "Erreur lors de l'envoi http (2) " . $content;
					break;
				}
				$start += BUFFER_SIZE;
				$to_operation = "send_append";
			}

			if ($return_code == "OK") {
				
				$params = array(
					'file'		 => $fileFG12,
					'operation'	 => "send_end"
				);

				$url = $siteCTI . "/" . $CTISantePHP ;
				$content = $http_connect->get($url, $params);
				
				$contentNode = @simplexml_load_string($content);
				if ($contentNode) {
					if ($contentNode["returnCode"] != "OK") {
						$return_code	 = "KO";
						$return_message	 = "Erreur lors de la validation http (1)";
					} else {
						$return_message = $contentNode["returnSize"] . " octets envoyés par HTTP dans fichier " . $remote_file;
					}
				} else {
					$return_code	 = "KO";
					$return_message	 = "Erreur lors de la validation http (2) " . $content;
				}
			}

			if ($return_code == "KO") {
				$return_complement		 = $httpCTISante->site . '/' . $CTISantePHP;
				$return_complement_v1	 = $fileFG12;
				$return_complement_v2	 = $dataFG12;
				$return_complement_v3	 = "send_oneshot";
			}


			unlink($local_file);


		} 
		else {
			$return_code	 = $result['return_code'];
			$return_message	 = $result['return_message'];
		}

        break;
    case get_file:
		//fileFG13 est le fichier regroupe par le nouveau groupeur
		if (file_exists($tmp_path . "/" . $manual_file)) {
			if (file_exists($tmp_path . "/" . $fileFG13)) {
				unlink($tmp_path . "/" . $fileFG13);
			}
			$dataFG13		 = uncompress(utf8_decode(file_get_contents($tmp_path . "/" . $manual_file)));
			file_put_contents($tmp_path . "/" . $fileFG13, $dataFG13);
			$return_message	 = strlen($dataFG13) . " octets chargés dans " . $fileFG13;
			break;
		} 
		else {
    	    // On recupere le nom du fichier groupé sur le Web le plus récent.
    		// recuperation liste
    		$params = array('header'          => $headerFG12,
    						'operation'       => "get_list",
    					 	'FG_YEAR'         => "$fg_year",
    					 	'PMSI_TYPE'       => "MCO"
    						);	

            $content = $http_connect->get($url, $params);
            $contentNode = simplexml_load_string($content);

            if ($contentNode) {
                if ($contentNode["returnCode"] != "OK") {
                    $return_code     = "KO";
                    $return_message     = "Erreur lors de l'initialisation de la liste " . $contentNode["returnMessage"];
                    break;
                }
                else {
                    foreach ($contentNode->FILE as $fileNode) {
                        $tmpAtt = (string)$fileNode['fg1_name'];
                        if ($fileFG12 < $tmpAtt) {
                            $fileFG12 = $tmpAtt;
                        }
                    }
                }
            } else {
                $return_code             = "KO";
                $return_message          = "Erreur HTTP lors de l'initialisation de la liste " . $content;
                $return_complement       = $httpCTISante->site . '/' . $CTISantePHP;
                $return_complement_v1    = $headerFG12;
                $return_complement_v2    = "";
                $return_complement_v3    = "get_list";
                break;
            }
    		
    	   $fileFG13         = substr($fileFG12, 0, strlen($fileFG12) - strlen($fg1FileExt)) . $fg1FileExt;

			// On le télécharge
			unlink($tmp_path . "/" . $fileFG13);
			if ($fileFG13 != "") {
				$params = array(
									'file'		       => $fileFG13 ,
									'operation'	       => "get_file" , 
                                    'FG_YEAR'          => "$fg_year",
                                    'PMSI_TYPE'        => "MCO"
								);
			
				$returnContentNode = url_request($http_connect, $url ,$params, "Erreur lors de la récupération " , $fileFG13, '',  "get_file");

				if ($returnContentNode['return_code'] == 'OK') {
					$contentNode = $returnContentNode['return_content'];
					$dataFG13		 = uncompress(utf8_decode($contentNode["returnData"]));
					file_put_contents($tmp_path . "/" . $fileFG13, $dataFG13);
					$return_code	 = "OK";
					$return_message	 = strlen($dataFG13) . " octets chargés par HTTP dans " . $fileFG13;
				}

			} 
			else {
				$return_code			 = "KO";
				$return_message			 = "Pas de fichier regroupé disponible" . $content;
				$return_complement		 = $httpCTISante->site . '/' . $CTISantePHP;
				$return_complement_v1	 = $fileFG13;
				$return_complement_v2	 = "";
				$return_complement_v3	 = "get_list";
			}
		}
        break;
	case trt_file:
		if ($fileFG13 == "") {

    		// recuperation liste
    		$params = array('header'      => $headerFG12,
    						'operation'   => "get_list",
    					 	'FG_YEAR'     => "$fg_year",
    					 	'PMSI_TYPE'   => "MCO"
    						);

           $content = $http_connect->get($url, $params);
           $contentNode = simplexml_load_string($content);

           if ($contentNode) {
               if ($contentNode["returnCode"] != "OK") {
                   $return_code     = "KO";
                   $return_message     = "Erreur lors de l'initialisation de la liste " . $contentNode["returnMessage"];
                   break;
               }
               else {
                   foreach ($contentNode->FILE as $fileNode) {
                       $tmpAtt = (string)$fileNode['fg1_name'];
                       if ($fileFG12 < $tmpAtt) {
                           $fileFG12 = $tmpAtt;
                       }
                   }
               }
           } else {
               $return_code               = "KO";
               $return_message            = "Erreur HTTP lors de l'initialisation de la liste " . $content;
               $return_complement         = $httpCTISante->site . '/' . $CTISantePHP;
               $return_complement_v1      = $headerFG12;
               $return_complement_v2      = "";
               $return_complement_v3      = "get_list";
               break;
           }
            $fileFG13         = substr($fileFG12, 0, strlen($fileFG12) - strlen($fg1FileExt)) . $fg1FileExt;
		}

		$realpathfileFG13	 = realpath($tmp_path . "/" . $fileFG13);
		$realpathfileFG13	 = str_replace("\\", "/", $realpathfileFG13);
        $environmentVars['realpathfileFG13'] = $realpathfileFG13 ;

		if ($return_code == "OK") {

			// Défintion des différents noeuds a executer l'etape 15 est conditionnée sur le type d'etbs
			$etapes = array(
						'ETAPE_1',
						'ETAPE_2',
						'ETAPE_3',
						'ETAPE_4',
						'ETAPE_5',
						'ETAPE_6',
						'ETAPE_7',
						'ETAPE_8',
						'ETAPE_9',
						'ETAPE_10',
						'ETAPE_11',
						'ETAPE_12',
						'ETAPE_13',
						'ETAPE_14',
						'ETAPE_15',
						'ETAPE_16',
						'ETAPE_17',
						'ETAPE_18',
						'ETAPE_19',
						'ETAPE_20',
						'ETAPE_21',
						'ETAPE_22',
						'ETAPE_23',
						'ETAPE_24',
                        'ETAPE_25'
			);

			// stoppe le script s erreur
			$stopError = TRUE;
			$sqlOptions= array('-stop', '-debugsql', '--show-queries');


			$nodesXml = __ROOT__ . '/modules/pmsi/php/lib_simulations/iCTI_simulation_FG' . $fg_year . '.XML';

			if (!file_exists($nodesXml)) {
				$return_message	 = "Erreur chargement fichier de traitement de RSS de simulation";
				$return_code	 = "KO";
				break;
			}

			$cti_sqlStatements = new CTI_SqlStatements_class($nodesXml,$iCTI_connexion,$environmentVars,$sqlOptions);


			// Exécution requetes SQL
			foreach($etapes as $etape){

				$return_codee = $cti_sqlStatements->executeStatementsNode($etape);

				if ($return_codee == 'ERROR') {
					$return_message	 = "Une erreur SQL a interrompu le traitement /  voir $etape";
					$return_code	 = "KO";
					break;
				}

			}


			if ($return_code == "OK") {
				$sqlcmd	 = "SELECT count(*) as count FROM pmsi.$simulationTableFG WHERE est_regroupe = '1' ";
				$count	 = 0;
				$result	 = $database->exec($sqlcmd);
				if ($result != false) {
					$record = $database->nextRecordInto();
					if ($record != FALSE) {
						$count = $record[0] + 0;
					}
				}

				if ($count > 0) {
					$return_message = filesize($tmp_path . "/" . $fileFG13) . " octets chargés dans " . $fileFG13 . ", $count dossiers regroupés";
				} else {
					$return_code	 = "KO";
					$return_message	 = filesize($tmp_path . "/" . $fileFG13) . " octets chargés dans " . $fileFG13 . ", mais aucun dossier regroupé";
				}
			}
		}


		// Nettoyage du cache PMSI MCO.
		cleanAllCache("iCTI_pmsi");
        break;
}

// tableau contenant les retour en cas d'erreur
if ($returnContentNode['return_code'] == 'KO') {
	$return_code			 = $returnContentNode['return_code'] ;
	$return_message			 = $returnContentNode['return_message'] ;
	//$return_complement		 = $returnContentNode['return_complement'] ;
	$return_complement_v1	 = $returnContentNode['return_complement_v1'] ;
	$return_complement_v2	 = $returnContentNode['return_complement_v2'] ;
	$return_complement_v3	 = $returnContentNode['return_complement_v3'] ;
}

$httpString .= "<RETURN code=\"$return_code\" message=\"$return_message\" 
			complement=\"$return_complement\" 
			warning=\"$return_warning\" 
			complement_v1=\"$return_complement_v1\"
			complement_v2=\"$return_complement_v2\"
			complement_v3=\"$return_complement_v3\"
			/>";

$httpString .= "\n</HTTP_SERVICE>";
echo "<CTICONTENT>$httpString</CTICONTENT>";
@pg_close($iCTI_connexion);




////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////                 FONCTIONS                     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Extrait les unités médicales paramétrées dans iCTI et les ecrits dans le fichier de sortie.
 *
 * @global type $database
 * @global type $tmp_RSSoutfile
 * @global type $typeEts
 * @global string $d1
 * @global type $finess
 */
function extract_um() {

	global $database;
	global $tmp_RSSoutfile;
	global $typeEts;
	global $d1;
	global $finess;

	$tmp_RSSouthandle = fopen($tmp_RSSoutfile, 'a');

	fwrite($tmp_RSSouthandle, "TYPEETS=$typeEts\r\n");

	$sqlcmd	 = "
		SELECT 
			'UNITEMEDIC' ||
			rpad(trim(code), 4, ' ') ||
			'$finess' ||
			rpad(trim(type_autorisation), 3, ' ') ||
			to_char(date_effet_autorisation, 'DDMMYYYY') ||
			lpad(nb_lits, 3, '0') ||
			mode_hospitalisation
		FROM pmsi.t_unites_medicales 
		WHERE 1=1
			AND oid > 0
			AND trim(code) <> ''
			AND trim(type_autorisation) != ''
			AND oid IN (
				SELECT unite_medicale_id 
				FROM pmsi.p_rss 
					JOIN pmsi.p_rss_rum ON p_rss_rum.rss_id = p_rss.oid
				WHERE p_rss.date_sortie >= '$d1'
				GROUP BY 1)
				GROUP BY 1;
	";
	$result	 = $database->exec($sqlcmd);
	while ($row = pg_fetch_array($result)) {
			$data	 = $row[0];
			fwrite($tmp_RSSouthandle, "$data\r\n");
    }


	fclose($tmp_RSSouthandle);
}

function extract_rss($import_id, $anneeToExtract) {

	global $database;
	global $tmp_path;

	// Restauration fichier
	$tmp_RSSinfile = $tmp_path . "/rss_" . $anneeToExtract . "_in.txt";
	if (file_exists($tmp_RSSinfile)) {
		unlink($tmp_RSSinfile);
	}
	$tmp_RSSinfileZip = $tmp_path . "/rss_" . $anneeToExtract . "_in.zip";
	if (file_exists($tmp_RSSinfileZip)) {
		unlink($tmp_RSSinfileZip);
	}

	// Aller dans IN.ZIP
	$sqlcmd	 = "
			SELECT data FROM pmsi.p_imports_data 
			WHERE import_id = $import_id AND data_type = 'ZIN' 
			ORDER BY data_num  
			";
	$result	 = $database->exec($sqlcmd);

    while ($row = pg_fetch_array($result)) {
        $data	 = $row[0];
        $handle = fopen($tmp_RSSinfileZip, 'a');
        fwrite($handle, uncompress(pg_unescape_bytea($data)));
        fclose($handle);
	}

	if (file_exists($tmp_RSSinfileZip)) {

        $zip = zip_open(realpath($tmp_RSSinfileZip));
		if ($zip) {
			while ($zip_entry = zip_read($zip)) {
				if (zip_entry_open($zip, $zip_entry)) {
					$filename	 = trim(zip_entry_name($zip_entry));
					$filesuffix	 = substr($filename, strlen($filename) - 7, 7);
					$filesuffixIni	= substr($filename, strlen($filename) - 11, 11);

                    if ($filesuffix == "rss.txt") {
                        $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
						file_put_contents($tmp_RSSinfile, $buf);
					} elseif ($filesuffixIni == "rss.ini.txt") {
                        $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                        file_put_contents($tmp_RSSinfile, $buf);
                    }
                    zip_entry_close($zip_entry);
				}
			}
			zip_close($zip);
		}
		unlink($tmp_RSSinfileZip);
	}


	return $tmp_RSSinfile;
}


function transform_extract_rss($tmp_RSSinfile, $tmp_RSSoutfile, $anneeToExtract ) {

	// préparation fichier
	// Premier passage, RSS à extraire (>= $d1)
	// rss à traiter
	$rss_array		 = array();
	$rss_ecart_array = array();
	$no_ligne		 = 0;

	$time_31032011 = mktime(0, 0, 0, 03, 31, FG_YEAR);

	$tmp_RSSinhandle = fopen($tmp_RSSinfile, "r");
	if ($tmp_RSSinhandle) {
		while (!feof($tmp_RSSinhandle)) {
			$buffer = fgets($tmp_RSSinhandle, 10240);
			$no_ligne++;
			if (trim($buffer) != "" && $no_ligne < 1000000000000000) {
				$no_rss						 = get_num(trim(substr($buffer, 27, 20)));
				$date_in					 = substr($buffer, 102, 8);
				$mktime_in					 = mktime(0, 0, 0, substr($date_in, 2, 2), substr($date_in, 0, 2), substr($date_in, 4, 4));
				$rss_ecart_array[$no_rss]	 = floor(($time_31032011 - $mktime_in) / (60 * 60 * 24));
				$cmd_code					 = trim(substr($buffer, 3, 2));
				$rss_array[$no_rss]			 = "KO";
				if ($cmd_code != "" && $cmd_code != "90" && $cmd_code != "00") {
					if (substr($buffer, 100, 1) != "0" || substr($buffer, 120, 1)) {
						// Le format possible est 016 UNIQUEMENT pour les années 2011 de mars à décembre
						// et 2012 de janvier à février.
						$RUMversionFormat	 = substr($buffer, 24, 3);
						$RUMannee			 = substr($buffer, 106, 4);
						$RUMmois			 = substr($buffer, 104, 2);
						if ($RUMversionFormat == "017") {
							if ($RUMannee == (FG_YEAR_RSS - 1) && $RUMmois >= '03' && $RUMmois <= '12') {
								$rss_array[$no_rss] = "OK";
							}
							if ($RUMannee == FG_YEAR_RSS && $RUMmois >= '01' && $RUMmois <= '02') {
								$rss_array[$no_rss] = "OK";
							}
						}
						if ($RUMversionFormat == "018") {
							if ($RUMannee == (FG_YEAR_RSS - 1) && $RUMmois >= '03' && $RUMmois <= '12') {
								$rss_array[$no_rss] = "OK";
							}
							if ($RUMannee == FG_YEAR_RSS && $RUMmois >= '01' && $RUMmois <= '02') {
								$rss_array[$no_rss] = "OK";
							}
						}
						if ($RUMversionFormat == "019") {
							if ($RUMannee == (FG_YEAR_RSS - 1) && $RUMmois >= '03' && $RUMmois <= '12') {
								$rss_array[$no_rss] = "OK";
							}
							if ($RUMannee == FG_YEAR_RSS && $RUMmois >= '01' && $RUMmois <= '02') {
								$rss_array[$no_rss] = "OK";
							}
						}
						if ($RUMversionFormat == "020") {
							if ($RUMannee == (FG_YEAR_RSS - 1) && $RUMmois >= '03' && $RUMmois <= '12') {
								$rss_array[$no_rss] = "OK";
							}
							if ($RUMannee == FG_YEAR_RSS && $RUMmois >= '01' && $RUMmois <= '02') {
								$rss_array[$no_rss] = "OK";
							}
						}
						if ($RUMversionFormat == "021") {
							if ($RUMannee == (FG_YEAR_RSS - 1) && $RUMmois >= '03' && $RUMmois <= '12') {
								$rss_array[$no_rss] = "OK";
							}
							if ($RUMannee == FG_YEAR_RSS && $RUMmois >= '01' && $RUMmois <= '02') {
								$rss_array[$no_rss] = "OK";
							}
						}
						if ($RUMversionFormat == "022") {
							if ($RUMannee == (FG_YEAR_RSS - 1) && $RUMmois >= '03' && $RUMmois <= '12') {
								$rss_array[$no_rss] = "OK";
							}
							if ($RUMannee == FG_YEAR_RSS && $RUMmois >= '01' && $RUMmois <= '02') {
								$rss_array[$no_rss] = "OK";
							}
						}
					}
				}
			}
		}
	}
	fclose($tmp_RSSinhandle);

	// second passage, creation fichier en sortie

	$tmp_RSSinhandle	 = fopen($tmp_RSSinfile, "r");
	$no_ligne			 = 0;
	while (!feof($tmp_RSSinhandle)) {
		$buffer = fgets($tmp_RSSinhandle, 10240);

		if (trim($buffer) != "" && $no_ligne < 1000000000000000) {
			$no_rss		 = get_num(trim(substr($buffer, 27, 20)));
			$no_rss_out	 = $anneeToExtract . substr("000000000000000000000" . $no_rss, -16, 16);

			if ($rss_array[$no_rss] == "OK") {
				$no_ligne++;

				// Translation n° rss
				$buffer = substr_replace($buffer, $no_rss_out, 27, 20);

				// Translation des dates

				$ecart = $rss_ecart_array[$no_rss];

				$date_in	 = substr($buffer, 77, 8);
				$mktime_out	 = mktime(0, 0, 0, substr($date_in, 2, 2), substr($date_in, 0, 2) + $ecart, substr($date_in, 4, 4));
				$date_out	 = date("dmY", $mktime_out);
				$buffer		 = substr_replace($buffer, $date_out, 77, 8);

				$date_in	 = substr($buffer, 92, 8);
				$mktime_out	 = mktime(0, 0, 0, substr($date_in, 2, 2), substr($date_in, 0, 2) + $ecart, substr($date_in, 4, 4));
				$date_out	 = date("dmY", $mktime_out);
				$buffer		 = substr_replace($buffer, $date_out, 92, 8);


				$date_in	 = substr($buffer, 102, 8);
				$mktime_out	 = mktime(0, 0, 0, substr($date_in, 2, 2), substr($date_in, 0, 2) + $ecart, substr($date_in, 4, 4));
				$date_out	 = date("dmY", $mktime_out);
				$buffer		 = substr_replace($buffer, $date_out, 102, 8);

				$codepost	 = substr($buffer, 112, 2) . "000";
				$buffer		 = substr_replace($buffer, $codepost, 112, 5);

				//Une nouvelle variable en 2023 passage urgence récupère les provenances 'U'
				//On modifie leur place rss pour ne pas avoir d'erreur de la part du groupeur

				if (FG_YEAR_RSS >= "2023"){
				$provenance = substr($buffer, 101, 1);
					if ($provenance === "U" || $provenance === "5") {
						$buffer	= substr_replace($buffer, ' ', 101, 1);
						$buffer	= substr_replace($buffer, $provenance, 184, 1);
					}
				}

				$nb_diags	 = substr($buffer, 133, 2) + 0;
				$nb_datac	 = substr($buffer, 135, 2) + 0;
				$nb_actes	 = substr($buffer, 137, 3) + 0;

				// forcage de la confiration$buffer
				$buffer		 = substr_replace($buffer, '1', 179, 1);

				$i			 = 192 + ($nb_diags * 8) + ($nb_datac * 8);

				$n = 1;

				for ($x = 1; $x <= $nb_actes; $x++) {

					$date_in = substr($buffer, $i, 8);
					if ($date_in + 0 > 0) {
						$mktime_out	 = mktime(0, 0, 0, substr($date_in, 2, 2), substr($date_in, 0, 2) + $ecart, substr($date_in, 4, 4));
						$date_out	 = date("dmY", $mktime_out);
						$buffer		 = substr_replace($buffer, $date_out, $i, 8);
					}
					$i = $i + 29;
					$n++;
				}

				file_put_contents($tmp_RSSoutfile, $buffer, FILE_APPEND);
			}
		}
	}

	fclose($tmp_RSSinhandle);
}

function get_num($value, $defaultValue = 0) {
	if (!is_numeric($value)) {
		return $defaultValue;
	}
	return $value + 0;
}


function getLastImports($database, $dateDebutImport) {

    $toRet = false;

    $sqlcmd = "
        SELECT
            (MAX(ARRAY[CASE WHEN data_type = 'ZIN' AND numero_editeur_pmsi <> 2 AND annee = " . (FG_YEAR_RSS - 1) . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi <> 2 AND annee = " . (FG_YEAR_RSS - 1) . " THEN import_id ELSE 0 END]))[2] as import_id_" . (FG_YEAR_RSS - 1) . " ,
            (MAX(ARRAY[CASE WHEN data_type = 'ZIN' AND numero_editeur_pmsi <> 2 AND annee = " . FG_YEAR_RSS . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi <> 2 AND annee = " . FG_YEAR_RSS . " THEN import_id ELSE 0 END]))[2] as import_id_" . FG_YEAR_RSS . " ,
            (MAX(ARRAY[CASE WHEN data_type = 'ZIN' AND numero_editeur_pmsi =  2 AND annee = " . (FG_YEAR_RSS - 1) . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi =  2 AND annee = " . (FG_YEAR_RSS - 1) . " THEN import_id ELSE 0 END]))[2] as import_id_2_" . (FG_YEAR_RSS - 1) . " ,
            (MAX(ARRAY[CASE WHEN data_type = 'ZIN' AND numero_editeur_pmsi =  2 AND annee = " . FG_YEAR_RSS . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi =  2 AND annee = " . FG_YEAR_RSS . " THEN import_id ELSE 0 END]))[2] as import_id_2_" . FG_YEAR_RSS . "
        FROM
            (
            SELECT
                extract('year' from  date_sortie) AS annee,
                p_rss.import_id,
                numero_editeur_pmsi,
                count(*) as nombre,
                data_type                
            FROM pmsi.p_rss
            JOIN pmsi.p_imports_data on p_rss.import_id = p_imports_data.import_id   AND data_type = 'ZIN'         
            WHERE 1=1
                AND date_sortie >= '$dateDebutImport'
                AND en_cours = '0'
                AND etat = ''
            GROUP BY 1,2,3,data_type
            ) AS subq
    ";

    $result = $database->exec($sqlcmd);
    if ($result != false) {
        $record = $database->nextRecordInto();
        if ($record != FALSE) {
            $toRet['return_code']                   = "OK";
            $toRet['import_id_N_moins_1_editeur_1'] = $record[0];
            $toRet['import_id_N_editeur_1']         = $record[1];
            $toRet['import_id_N_moins_1_editeur_2'] = $record[2];
            $toRet['import_id_N_editeur_2']         = $record[3];
        }

        if (  ($toRet['import_id_N_moins_1_editeur_1'] == 0 && $toRet['import_id_N_editeur_1'] == 0 && $toRet['import_id_N_moins_1_editeur_2']  == 0 && $toRet['import_id_N_editeur_2'] == 0) OR ($toRet['import_id_N_moins_1_editeur_1'] == '' && $toRet['import_id_N_editeur_1'] == '' && $toRet['import_id_N_moins_1_editeur_2']  == '' && $toRet['import_id_N_editeur_2'] == ''))
        {
            $return['return_code']      = "KO";
            $return['return_message']   = "Aucun import pour " . (FG_YEAR_RSS - 1) . " ou " . FG_YEAR_RSS;
            return $return;
        }

        return $toRet;

    }
    else{
        $return['return_code']      = "KO";
        $return['return_message']   = "Erreur SQL" . $sqlcmd ;
        return $return;
    }
}

function generation_donnees_complementaires_execute($environmentVars, $node, $provider) {

	global $iCTI_connexion;
	// stoppe le script s erreur
	$stopError = TRUE;
	$sqlOptions=array('-stop', 'debugsql');
	$cti_sqlStatements = new CTI_SqlStatements_class("$provider.XML",$iCTI_connexion,$environmentVars,$sqlOptions);

	// Exécution requetes SQL
	$rer =  $cti_sqlStatements->executeStatementsNode($node);

	return $rer;
}

function url_request($http_connect, $url, $parametres, $libelle_erreur = "Erreur lors de l'initialisation de la liste ", $return_complement_v1 = '', $return_complement_v2 = '', $return_complement_v3 = ''){

	$return = '';
	$content = $http_connect->get($url, $parametres);

	$contentNode = simplexml_load_string($content);

	if ($contentNode) {
		if ($contentNode["returnCode"] != "OK") {
			$return['return_code']		= "KO";
			$return['return_message']	= $libelle_erreur . $contentNode["returnMessage"];
		}
		else {
			$return['return_code']		= "OK";
			$return['return_content']	= $contentNode;
		}
	} else {
		$return['return_code']		 		= "KO";
		$return['$return_message']			= $libelle_erreur;
		//$return['$return_complement']		= $httpCTISante->site . '/' . $CTISantePHP;
		$return['$return_complement_v1']	= $return_complement_v1;
		$return['$return_complement_v2']	= $return_complement_v2;
		$return['$return_complement_v3']	= $return_complement_v3;
	}

	return $return;

}

?>