<?php
$MODULE="pmsi";
$TITLE="Impact Diagnostic";
$ARGS="-raz";
$DFTENDSTATUS="OK";

/*
Influence de la suppression d'une liste de diagnostic associées sur le groupage
objectif: %, CA des rss impactés par non existence d'un diagnostic

méthodologie:
fichier In => extraction RSS 	=> supression des diagnostic liste 1	=> groupage 1 	=>	fichier RDS 1	=> import csv dans table spe pour analyse (+tempo et comparative)
								=> supression des diagnostic liste 2	=> groupage 2 	=>	fichier RDS 2
								=> supression des diagnostic liste 3	=> groupage 3 	=>	fichier RDS 3

2 années d'antériorité (à partir de mars)) => changeable dans $nb_annees

requis:
	- Listes > Diagnostics > Etude Impact Diagnostics > listes $diag_list_rootX répliquées dans les environnements consolidés
	- table pmsi.t_impact_diagnotiques
	- groupeur dans $mgt_path

affichage fait
	- analyse, justificatifs, affichage des erreurs
	- filtre sur diagnostiques présents, changements de GHM, de racine, de sévérité
	- pourcentages(dans analyse)  en fonction du filtre (référentiel)
	
a faire: 
- optimisation par flag sur changement de liste ou import de lot
- changement de liste dans le consoliudé change les liste partout
*/

require_once("../../../modules/base/php/lib/cti/Batch/iCTI_batch_common.php" );
require_once('../../base/php/lib/cti/Database/Database2Factory.class.php');
require_once("../../base/php/classSimpleXML.php");
require_once("../../base/php/Functions.php" );
require_once("../../outils/php/httpService_cacheManager_cleanCache.php");


//chargement des paramètres
$annee = date("Y");
$nb_annees= 2;
$mgt_path	= 'C:/CTI/iCTI_System/mgt';
$tmp_path	= '../../../temp';
$diag_list_root = 'CTI_DIAG_IMP_';
$nr_diag_list = 4;
$diag_code_list = Array();
$yearVars = Array();
$simulationTable		= 'p_impact_diagnostics'; 
$conn = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
$ngExt = '.ng';

echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "START" . "\t" . "SIMULATION IMPACT diagnostic PMSI";

$sql = "TRUNCATE pmsi.$simulationTable;";
$result = $conn->queryFetchAllAssoc($sql);
if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 0";
			}
			
//reprend le groupeur precedent si l fichier relatif au groupeur de l'annéen'est pas trouvé
if (!file_exists("$mgt_path/$annee/iCTI_impact_diag_group_$annee.php")) {
	$annee = $annee - 1;	
	echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "    " . "\t" . "Groupeur année en cours absent. Calcul avec les groupeurs des années précédentes";
}
			
//itérations sur années et listes
for($y = $annee - ($nb_annees-1) ; $y < $annee+1 ; $y++) {
	include_once("$mgt_path/$y/iCTI_impact_diag_group_$y.php");
	$sql = "SELECT max(substr(t_listes.code,length('$diag_list_root')+1)::int) as nr
			FROM pmsi.t_listes 
			WHERE pmsi.t_listes.code like '$diag_list_root%'";
	$result = $conn->queryFetchAllAssoc($sql);
	$nr_diag_list = $result[0]['nr'];
	
	for($num = 1 ; $num <= $nr_diag_list ; $num++) {
		$sql = "SELECT t_listes.oid 
				FROM pmsi.t_listes 
				WHERE pmsi.t_listes.code = '$diag_list_root$num'";
		$result = $conn->queryFetchAllAssoc($sql);
		$liste_id = $result[0]['oid'];
		
		$sql = "SELECT t_listes_tables.select_cmd 
				FROM pmsi.t_listes_tables 
				WHERE t_listes_tables.oid IN (
						SELECT t_listes.table_id 
						FROM pmsi.t_listes 
						WHERE pmsi.t_listes.code = '$diag_list_root$num')";
		$result = $conn->queryFetchAllAssoc($sql);
		if (!$result) echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "ABORT" . "\t" . "SIMULATION $y liste $diag_list_root$num n'existe pas";
		else {
				$sql = "SELECT d.code 
				FROM (".$result[0]['select_cmd'].") as d 
				WHERE d.oid IN (
					SELECT to_id 
					FROM pmsi.t_listes_contenu 
					WHERE liste_id = (
						SELECT t_listes.oid 
						FROM pmsi.t_listes 
						WHERE pmsi.t_listes.code = '$diag_list_root$num'))";		
			$result = $conn->queryFetchAllAssoc($sql);
			foreach($result as $value) $diag_code_list[$liste_id][] = $value['code'];
			
			if (empty($diag_code_list[$liste_id])) echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "ABORT" . "\t" . "SIMULATION $y liste $diag_list_root$num est vide (oid $liste_id)";
			else {
				$tmp_RSSoutfile = $mgt_path . '/' .$y . '/files/' . Environnement::getFiness();
				if (!file_exists($tmp_RSSoutfile)) {
					mkdir($tmp_RSSoutfile);
				}
				$tmp_RSSoutfile .= '/rss_out'.$ngExt;

				echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "START" . "\t" . "SIMULATION $y liste $diag_list_root$num (oid $liste_id)";
				
				//création des fichiers pour le groupeur
				createFile($liste_id);
				
				//group
				call_user_func("group_file_$y");
				//traite
				trtFile($liste_id);
			}
		}
	}
}

// recup des fichier in et placement pour récupération par le groupeur(+tard juste le dernier si les listes n'ont pas été changées)
function createFile($list_id)
{	
	global $y;
	global $conn;
	global $tmp_RSSoutfile;
	global $local_file;
	global $diag_code_list;

	echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "creation fichier non groupé pour ".$y;	
	
	// Calcul des dates clés : 1er mars => 31 déc. => 1 janv. => 28/29 fév.
	$d1					 = $y . '-03-01';
	$d5					 = ($y+1) . '-03-01';
	
	$sql = "SELECT
			(MAX(ARRAY[CASE WHEN numero_editeur_pmsi <> 2 AND annee = " . $y . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi <> 2 AND annee = " . $y . " THEN import_id ELSE 0 END]))[2] as import_id_y_1,
			(MAX(ARRAY[CASE WHEN numero_editeur_pmsi <> 2 AND annee = " . ($y+1) . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi <> 2 AND annee = " . ($y+1) . " THEN import_id ELSE 0 END]))[2] as import_id_y,
			(MAX(ARRAY[CASE WHEN numero_editeur_pmsi =  2 AND annee = " . $y . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi =  2 AND annee = " . $y . " THEN import_id ELSE 0 END]))[2] as import_id_2_y_1,
			(MAX(ARRAY[CASE WHEN numero_editeur_pmsi =  2 AND annee = " . ($y+1) . " THEN nombre ELSE 0 END, CASE WHEN numero_editeur_pmsi =  2 AND annee = " . ($y+1) . " THEN import_id ELSE 0 END]))[2] as import_id_2_y
		FROM
			(
			SELECT
				extract('year' from  date_sortie) AS annee,
				import_id,
				numero_editeur_pmsi,
				count(*) as nombre
			FROM pmsi.p_rss
			WHERE 1=1
				AND date_sortie >= '$d1'
				AND date_sortie < '$d5'
				AND en_cours = '0'
				AND etat = ''
			GROUP BY 1,2,3
			) AS subq";
	$result = $conn->queryFetchAllAssoc($sql);
	// Définition des extentions de fichier

	if (count($result)) {
		$return_code	 = "OK";
		$result=$result[0];
	} else {
		$return_code	 = "$sql";
		$return_message	 = "Erreur SQL";
	}

	if ($return_code == "OK") {
		if (array_sum($result) == 0) {
			$return_code	 = "$sql";
			$return_message	 = "Aucun import pour " . ($y) . " ou " . $y+1;
		}
	}

	if ($return_code == "OK") {
		$tmp_RSSinfileZip = $tmp_path . "/rss_" . $y . "_in.zip";
		if (file_exists($tmp_RSSinfileZip)) {
			unlink($tmp_RSSinfileZip);
		}	

		@unlink($tmp_RSSoutfile);

		// Unites medicales
		extract_um($d1,$d5);

		// Restauration fichier 2
		if ($result['import_id_y_1'] > 0) {
			extract_rss($result['import_id_y_1'], $y);
			filterDiag($diag_code_list[$list_id], $y);
		}
		if ($result['import_id_2_y_1'] > 0) {
			extract_rss($result['import_id_2_y_1'], $y);
			filterDiag($diag_code_list[$list_id], $y);
		}
		if ($result['import_id_y'] > 0) {
			extract_rss($result['import_id_y'], $y);
			filterDiag($diag_code_list[$list_id], $y+1);
		}
		if ($result['import_id_2_y'] > 0) {
			extract_rss($result['import_id_2_y'], $y);
			filterDiag($diag_code_list[$list_id], $y+1);
		}		
	}
	@unlink($local_file);

}

// update/insert dans table
function trtFile($liste_id) {
	global $y;
	global $num;
	global $conn; 
	global $ngExt;
	global $FG_VERSION;
	global $simulationTable; 
	global $tmp_path;
	global $tmp_RSSoutfile;
	global $csvColumns;
	global $diag_list_root;
	
	$csvFile = str_replace($ngExt,'.'.$FG_VERSION,$tmp_RSSoutfile);
	$nextY = $y+1;
	$d5 = $nextY."-03-01";
	$d1 = $y."-03-01";
	$sql = "
			
		INSERT INTO pmsi.$simulationTable
			(
				liste_id,
				liste_code,
				finess,
				rss_id,
				no_rss,
				annee_sortie,
				ghm_fg0_id,
				ghs_fg0_id
			)
			SELECT 
				$liste_id,
				'$diag_list_root$num',
				v_rss_1.finess,
				v_rss_1.rss_id, 
				v_rss_1.no_rss, 
				date_part('year',v_rss_1.date_sortie), 
				ghm_id,
				ghs_id
			FROM pmsi.v_rss_1
			WHERE 1=1
				AND date_sortie >= '$y-03-01'
				AND date_sortie < '$nextY-03-01'
				AND en_cours = '0' 
				AND mco IN ('M', 'C', 'O')
			;
		";
		$result = $conn->dbQuery($sql);
		if($result) {
	//		echo $sql;
			$return_code = "OK";
		} else { 
			$return_code	 = "$sql";
			$return_message	 = "Une erreur SQL a interrompu le traitement 0";
		}
	
		if ($return_code == "OK") {
			$sql	 = "
				UPDATE pmsi.$simulationTable
				SET 
					coefficient_mco_fg0 = subview.coefficient_mco_fg0, 
					montant_ghs_theorique_fg0 = subview.montant_ghs_theorique_fg0, 
					nb_sej_exb_fg0 = subview.nb_sej_exb_fg0,
					montant_exb_fg0 = subview.montant_exb_fg0,
					nb_exh_fg0 = subview.nb_exh_fg0,
					montant_exh_fg0 = subview.montant_exh_fg0
				FROM 
					(
					SELECT v_rsf_detail_1.rss_id,
						MIN(CASE WHEN prestation_code = 'GHS' THEN coefficient_mco ELSE null END) AS coefficient_mco_fg0,
						SUM(
							CASE WHEN prestation_code = 'GHS' THEN 
								CASE WHEN coefficient >= 1 THEN v_rsf_detail_1.base_remboursement ELSE round(v_rsf_detail_1.nombre * v_rsf_detail_1.coefficient_mco * v_rsf_detail_1.prix_unitaire,2) END
							ELSE 0 END
						) AS montant_ghs_theorique_fg0,
						COUNT (DISTINCT CASE WHEN prestation_code = 'GHS' AND coefficient < 1 THEN v_rsf_detail_1.rss_id ELSE null END) AS nb_sej_exb_fg0,
						SUM(CASE WHEN prestation_code = 'GHS' AND coefficient < 1 THEN v_rsf_detail_1.base_remboursement - round(v_rsf_detail_1.nombre * v_rsf_detail_1.coefficient_mco * v_rsf_detail_1.prix_unitaire,2) ELSE 0 END) AS montant_exb_fg0,
						SUM(CASE WHEN prestation_code = 'EXH' THEN nombre ELSE 0 END) as nb_exh_fg0,
						SUM(CASE WHEN prestation_code = 'EXH' THEN v_rsf_detail_1.base_remboursement ELSE 0 END) as montant_exh_fg0
					FROM pmsi.v_rss_7 AS v_rss_1, pmsi.v_rsf_detail_1
					WHERE 1=1
						AND date_sortie >= '$y-03-01' 
						AND date_sortie < '$nextY-03-01' 
						AND v_rsf_detail_1.rss_id = v_rss_1.rss_id
						AND prestation_code IN ('GHS', 'EXH')
						AND en_cours = '0'
					GROUP BY v_rsf_detail_1.rss_id
					) AS subview
				WHERE subview.rss_id = $simulationTable.rss_id
				;
			";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 2";
			}
		}
	
		// On reporte le nombre de GHS 9605 en prod. (fg0) dans le simulé (fg1).
		if ($return_code == "OK") {
			$sql	 = "
				UPDATE pmsi.$simulationTable 
				SET nb_9605_fg1 = nb_9605_fg0
				;
				UPDATE pmsi.$simulationTable
				SET nb_9604_fg1 = nb_9604_fg0
				;
			";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 3";
			}
		}
	
		if ($return_code == "OK") {
			$sql	 = "
				DROP TABLE IF EXISTS w_tmp
				;
				CREATE TEMP TABLE w_tmp
					(".$csvColumns[$y].")
				;
			";
			$result = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 4";
			}
		}

		if ($return_code == "OK") {
			$sql		 = "COPY w_tmp
					FROM '$csvFile'
					WITH DELIMITER AS ';'
					CSV QUOTE AS  '\"' ;";
			$result = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 5";
			}

			// Attention 05K12
			$sql	 = "UPDATE w_tmp
				SET ghs_fg1_code = 1808
				FROM pmsi.v_rss_actes_1, pmsi.$simulationTable
				WHERE $simulationTable.annee_sortie = w_tmp.annee_sortie
					AND $simulationTable.no_rss = w_tmp.no_rss
					AND $liste_id = $simulationTable.liste_id
					AND w_tmp.ghm_fg1_code = '05K121'
					AND w_tmp.ghs_fg1_code = 1707
					AND acte_code = 'DENF003' AND activite_ccam = '1'
				;
					
				UPDATE w_tmp
				SET ghs_fg1_code = 1809
				FROM pmsi.v_rss_actes_1, pmsi.$simulationTable
				WHERE $simulationTable.annee_sortie = w_tmp.annee_sortie
					AND $simulationTable.no_rss = w_tmp.no_rss
					AND $liste_id = $simulationTable.liste_id
					AND w_tmp.ghm_fg1_code = '05K123'
					AND w_tmp.ghs_fg1_code = 1708
					AND acte_code = 'DENF003' AND activite_ccam = '1';	
				
				UPDATE w_tmp
				SET ghs_fg1_code = 1810
				FROM pmsi.v_rss_actes_1, pmsi.$simulationTable
				WHERE $simulationTable.annee_sortie = w_tmp.annee_sortie
					AND $simulationTable.no_rss = w_tmp.no_rss
					AND $liste_id = $simulationTable.liste_id
					AND w_tmp.ghm_fg1_code = '05K123'
					AND w_tmp.ghs_fg1_code = 1709
					AND acte_code = 'DENF003' AND activite_ccam = '1';
					
				UPDATE w_tmp
				SET ghs_fg1_code = 1812
				FROM pmsi.v_rss_actes_1, pmsi.$simulationTable
				WHERE $simulationTable.annee_sortie = w_tmp.annee_sortie
					AND $simulationTable.no_rss = w_tmp.no_rss
					AND $liste_id = $simulationTable.liste_id
					AND w_tmp.ghm_fg1_code = '05K124'
					AND w_tmp.ghs_fg1_code = 1710
					AND acte_code = 'DENF003' AND activite_ccam = '1';
					
				UPDATE w_tmp
				SET ghs_fg1_code = 1813
				FROM pmsi.v_rss_actes_1, pmsi.$simulationTable
				WHERE $simulationTable.annee_sortie = w_tmp.annee_sortie
					AND $simulationTable.no_rss = w_tmp.no_rss
					AND $liste_id = $simulationTable.liste_id
					AND w_tmp.ghm_fg1_code = '05K12T'
					AND w_tmp.ghs_fg1_code = 1712
					AND acte_code = 'DENF003' AND activite_ccam = '1';

				";
			$result = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 6";
			}


			// Attention soins palliatifs
			$sql	 = "
				UPDATE w_tmp
				SET ghs_fg1_code = t_ghs.code
				FROM pmsi.$simulationTable
					JOIN pmsi.t_ghs ON ghs_fg0_id = t_ghs.oid
				WHERE 1=1
					AND $simulationTable.annee_sortie = w_tmp.annee_sortie
					AND $simulationTable.no_rss = w_tmp.no_rss
					AND t_ghs.code IN (7991, 7992, 7993, 7994, 7267, 7281)
					AND w_tmp.ghs_fg1_code IN (7991, 7992, 7993, 7994, 7267, 7281)
				;
			";
			$result = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 7";
			}
		}

		if ($return_code == "OK") {
			if ($typeEts != "2" && $typeEts != "3") {
				$sql	 = "UPDATE pmsi.$simulationTable
							SET 
								erreur = CASE WHEN w_tmp.erreur IS NOT NULL THEN substr(trim(w_tmp.erreur),1,255) ELSE '' END,
								commentaire = CASE WHEN w_tmp.commentaire IS NOT NULL THEN substr(trim(w_tmp.commentaire),1,255) ELSE '' END,
								ghm_fg1_code = w_tmp.ghm_fg1_code,
								ghm_fg1_id = t_ghm.oid,
								ghs_fg1_code = w_tmp.ghs_fg1_code,
								ghs_fg1_id = t_ghs.oid,
								ghs_fg1_tarif_ghs =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_prive_1 AND '$d1' <= t_ghs.date_fin_prive_1 THEN t_ghs.tarif_ghs_prive_1 
								WHEN '$d1' >= t_ghs.date_debut_prive_2 AND '$d1' <= t_ghs.date_fin_prive_2 THEN t_ghs.tarif_ghs_prive_2 
								WHEN '$d1' >= t_ghs.date_debut_prive_3 AND '$d1' <= t_ghs.date_fin_prive_3 THEN t_ghs.tarif_ghs_prive_3 
								WHEN '$d1' >= t_ghs.date_debut_prive_4 AND '$d1' <= t_ghs.date_fin_prive_4 THEN t_ghs.tarif_ghs_prive_4 
								WHEN '$d1' >= t_ghs.date_debut_prive_5 AND '$d1' <= t_ghs.date_fin_prive_5 THEN t_ghs.tarif_ghs_prive_5 
								WHEN '$d1' >= t_ghs.date_debut_prive_6 AND '$d1' <= t_ghs.date_fin_prive_6 THEN t_ghs.tarif_ghs_prive_6 
								WHEN '$d1' >= t_ghs.date_debut_prive_7 AND '$d1' <= t_ghs.date_fin_prive_7 THEN t_ghs.tarif_ghs_prive_7 
								WHEN '$d1' >= t_ghs.date_debut_prive_8 AND '$d1' <= t_ghs.date_fin_prive_8 THEN t_ghs.tarif_ghs_prive_8 
								WHEN '$d1' >= t_ghs.date_debut_prive_9 AND '$d1' <= t_ghs.date_fin_prive_9 THEN t_ghs.tarif_ghs_prive_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_tarif_exh =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_prive_1 AND '$d1' <= t_ghs.date_fin_prive_1 THEN t_ghs.tarif_exh_prive_1 
								WHEN '$d1' >= t_ghs.date_debut_prive_2 AND '$d1' <= t_ghs.date_fin_prive_2 THEN t_ghs.tarif_exh_prive_2 
								WHEN '$d1' >= t_ghs.date_debut_prive_3 AND '$d1' <= t_ghs.date_fin_prive_3 THEN t_ghs.tarif_exh_prive_3 
								WHEN '$d1' >= t_ghs.date_debut_prive_4 AND '$d1' <= t_ghs.date_fin_prive_4 THEN t_ghs.tarif_exh_prive_4 
								WHEN '$d1' >= t_ghs.date_debut_prive_5 AND '$d1' <= t_ghs.date_fin_prive_5 THEN t_ghs.tarif_exh_prive_5 
								WHEN '$d1' >= t_ghs.date_debut_prive_6 AND '$d1' <= t_ghs.date_fin_prive_6 THEN t_ghs.tarif_exh_prive_6 
								WHEN '$d1' >= t_ghs.date_debut_prive_7 AND '$d1' <= t_ghs.date_fin_prive_7 THEN t_ghs.tarif_exh_prive_7 
								WHEN '$d1' >= t_ghs.date_debut_prive_8 AND '$d1' <= t_ghs.date_fin_prive_8 THEN t_ghs.tarif_exh_prive_8 
								WHEN '$d1' >= t_ghs.date_debut_prive_9 AND '$d1' <= t_ghs.date_fin_prive_9 THEN t_ghs.tarif_exh_prive_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_tarif_exb =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_prive_1 AND '$d1' <= t_ghs.date_fin_prive_1 THEN t_ghs.tarif_exb_prive_1 
								WHEN '$d1' >= t_ghs.date_debut_prive_2 AND '$d1' <= t_ghs.date_fin_prive_2 THEN t_ghs.tarif_exb_prive_2 
								WHEN '$d1' >= t_ghs.date_debut_prive_3 AND '$d1' <= t_ghs.date_fin_prive_3 THEN t_ghs.tarif_exb_prive_3 
								WHEN '$d1' >= t_ghs.date_debut_prive_4 AND '$d1' <= t_ghs.date_fin_prive_4 THEN t_ghs.tarif_exb_prive_4 
								WHEN '$d1' >= t_ghs.date_debut_prive_5 AND '$d1' <= t_ghs.date_fin_prive_5 THEN t_ghs.tarif_exb_prive_5 
								WHEN '$d1' >= t_ghs.date_debut_prive_6 AND '$d1' <= t_ghs.date_fin_prive_6 THEN t_ghs.tarif_exb_prive_6 
								WHEN '$d1' >= t_ghs.date_debut_prive_7 AND '$d1' <= t_ghs.date_fin_prive_7 THEN t_ghs.tarif_exb_prive_7 
								WHEN '$d1' >= t_ghs.date_debut_prive_8 AND '$d1' <= t_ghs.date_fin_prive_8 THEN t_ghs.tarif_exb_prive_8 
								WHEN '$d1' >= t_ghs.date_debut_prive_9 AND '$d1' <= t_ghs.date_fin_prive_9 THEN t_ghs.tarif_exb_prive_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_forfait_exb =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_prive_1 AND '$d1' <= t_ghs.date_fin_prive_1 THEN t_ghs.forfait_exb_prive_1 
								WHEN '$d1' >= t_ghs.date_debut_prive_2 AND '$d1' <= t_ghs.date_fin_prive_2 THEN t_ghs.forfait_exb_prive_2 
								WHEN '$d1' >= t_ghs.date_debut_prive_3 AND '$d1' <= t_ghs.date_fin_prive_3 THEN t_ghs.forfait_exb_prive_3 
								WHEN '$d1' >= t_ghs.date_debut_prive_4 AND '$d1' <= t_ghs.date_fin_prive_4 THEN t_ghs.forfait_exb_prive_4 
								WHEN '$d1' >= t_ghs.date_debut_prive_5 AND '$d1' <= t_ghs.date_fin_prive_5 THEN t_ghs.forfait_exb_prive_5 
								WHEN '$d1' >= t_ghs.date_debut_prive_6 AND '$d1' <= t_ghs.date_fin_prive_6 THEN t_ghs.forfait_exb_prive_6 
								WHEN '$d1' >= t_ghs.date_debut_prive_7 AND '$d1' <= t_ghs.date_fin_prive_7 THEN t_ghs.forfait_exb_prive_7 
								WHEN '$d1' >= t_ghs.date_debut_prive_8 AND '$d1' <= t_ghs.date_fin_prive_8 THEN t_ghs.forfait_exb_prive_8 
								WHEN '$d1' >= t_ghs.date_debut_prive_9 AND '$d1' <= t_ghs.date_fin_prive_9 THEN t_ghs.forfait_exb_prive_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_borne_basse =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_prive_1 AND '$d1' <= t_ghs.date_fin_prive_1 THEN t_ghs.borne_basse_prive_1 
								WHEN '$d1' >= t_ghs.date_debut_prive_2 AND '$d1' <= t_ghs.date_fin_prive_2 THEN t_ghs.borne_basse_prive_2 
								WHEN '$d1' >= t_ghs.date_debut_prive_3 AND '$d1' <= t_ghs.date_fin_prive_3 THEN t_ghs.borne_basse_prive_3 
								WHEN '$d1' >= t_ghs.date_debut_prive_4 AND '$d1' <= t_ghs.date_fin_prive_4 THEN t_ghs.borne_basse_prive_4 
								WHEN '$d1' >= t_ghs.date_debut_prive_5 AND '$d1' <= t_ghs.date_fin_prive_5 THEN t_ghs.borne_basse_prive_5 
								WHEN '$d1' >= t_ghs.date_debut_prive_6 AND '$d1' <= t_ghs.date_fin_prive_6 THEN t_ghs.borne_basse_prive_6 
								WHEN '$d1' >= t_ghs.date_debut_prive_7 AND '$d1' <= t_ghs.date_fin_prive_7 THEN t_ghs.borne_basse_prive_7 
								WHEN '$d1' >= t_ghs.date_debut_prive_8 AND '$d1' <= t_ghs.date_fin_prive_8 THEN t_ghs.borne_basse_prive_8 
								WHEN '$d1' >= t_ghs.date_debut_prive_9 AND '$d1' <= t_ghs.date_fin_prive_9 THEN t_ghs.borne_basse_prive_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_borne_haute =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_prive_1 AND '$d1' <= t_ghs.date_fin_prive_1 THEN t_ghs.borne_haute_prive_1 
								WHEN '$d1' >= t_ghs.date_debut_prive_2 AND '$d1' <= t_ghs.date_fin_prive_2 THEN t_ghs.borne_haute_prive_2 
								WHEN '$d1' >= t_ghs.date_debut_prive_3 AND '$d1' <= t_ghs.date_fin_prive_3 THEN t_ghs.borne_haute_prive_3 
								WHEN '$d1' >= t_ghs.date_debut_prive_4 AND '$d1' <= t_ghs.date_fin_prive_4 THEN t_ghs.borne_haute_prive_4 
								WHEN '$d1' >= t_ghs.date_debut_prive_5 AND '$d1' <= t_ghs.date_fin_prive_5 THEN t_ghs.borne_haute_prive_5 
								WHEN '$d1' >= t_ghs.date_debut_prive_6 AND '$d1' <= t_ghs.date_fin_prive_6 THEN t_ghs.borne_haute_prive_6 
								WHEN '$d1' >= t_ghs.date_debut_prive_7 AND '$d1' <= t_ghs.date_fin_prive_7 THEN t_ghs.borne_haute_prive_7 
								WHEN '$d1' >= t_ghs.date_debut_prive_8 AND '$d1' <= t_ghs.date_fin_prive_8 THEN t_ghs.borne_haute_prive_8 
								WHEN '$d1' >= t_ghs.date_debut_prive_9 AND '$d1' <= t_ghs.date_fin_prive_9 THEN t_ghs.borne_haute_prive_9 
								ELSE 0::numeric 
								END,
								nb_exb_fg1 = w_tmp.nb_exb_fg1,
								nb_sej_exb_fg1 = CASE WHEN w_tmp.nb_exb_fg1 > 0 THEN 1 ELSE 0 END,
								nb_exh_fg1 = CASE WHEN t_ghm.oid <> ghm_fg0_id THEN  w_tmp.nb_exh_fg1 ELSE nb_exh_fg0 END,
								tarif_9605_fg1 = (SELECT tarif_ghs
								FROM base.t_ghs
								JOIN base.t_ghs_tarifs ON t_ghs_tarifs.ghs_id = t_ghs.oid
								WHERE 1=1
									AND t_ghs.code = '9605'
									AND t_ghs_tarifs.secteur = 1
									AND '$d1'::date BETWEEN date_debut AND date_fin),
								tarif_9604_fg1 = (SELECT tarif_ghs
								FROM base.t_ghs
								JOIN base.t_ghs_tarifs ON t_ghs_tarifs.ghs_id = t_ghs.oid
								WHERE 1=1
									AND t_ghs.code = '9604'
									AND t_ghs_tarifs.secteur = 1
									AND '$d1'::date BETWEEN date_debut AND date_fin)
							FROM w_tmp, pmsi.t_ghm, pmsi.t_ghs
							WHERE $simulationTable.annee_sortie = w_tmp.annee_sortie
							AND $simulationTable.no_rss = w_tmp.no_rss
							AND $simulationTable.liste_id = $liste_id
							AND w_tmp.ghm_fg1_code = t_ghm.code
							AND w_tmp.ghs_fg1_code = t_ghs.code;
							";
				$result = $conn->dbQuery($sql);
				if (!$result) {
					$return_code	 = "$sql";
					$return_message	 = "Une erreur SQL a interrompu le traitement 8";
				}
			} else {
				
				$sql	 = "UPDATE pmsi.$simulationTable
							SET 
								erreur = CASE WHEN w_tmp.erreur IS NOT NULL THEN substr(trim(w_tmp.erreur),1,255) ELSE '' END,
								commentaire = CASE WHEN w_tmp.commentaire IS NOT NULL THEN substr(trim(w_tmp.commentaire),1,255) ELSE '' END,
								ghm_fg1_code = w_tmp.ghm_fg1_code,
								ghm_fg1_id = t_ghm.oid,
								ghs_fg1_code = w_tmp.ghs_fg1_code,
								ghs_fg1_id = t_ghs.oid,
								ghs_fg1_tarif_ghs =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_public_1 AND '$d1' <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1 
								WHEN '$d1' >= t_ghs.date_debut_public_2 AND '$d1' <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2 
								WHEN '$d1' >= t_ghs.date_debut_public_3 AND '$d1' <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3 
								WHEN '$d1' >= t_ghs.date_debut_public_4 AND '$d1' <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4 
								WHEN '$d1' >= t_ghs.date_debut_public_5 AND '$d1' <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5 
								WHEN '$d1' >= t_ghs.date_debut_public_6 AND '$d1' <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6 
								WHEN '$d1' >= t_ghs.date_debut_public_7 AND '$d1' <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7 
								WHEN '$d1' >= t_ghs.date_debut_public_8 AND '$d1' <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8 
								WHEN '$d1' >= t_ghs.date_debut_public_9 AND '$d1' <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_tarif_exh =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_public_1 AND '$d1' <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_exh_public_1 
								WHEN '$d1' >= t_ghs.date_debut_public_2 AND '$d1' <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_exh_public_2 
								WHEN '$d1' >= t_ghs.date_debut_public_3 AND '$d1' <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_exh_public_3 
								WHEN '$d1' >= t_ghs.date_debut_public_4 AND '$d1' <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_exh_public_4 
								WHEN '$d1' >= t_ghs.date_debut_public_5 AND '$d1' <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_exh_public_5 
								WHEN '$d1' >= t_ghs.date_debut_public_6 AND '$d1' <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_exh_public_6 
								WHEN '$d1' >= t_ghs.date_debut_public_7 AND '$d1' <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_exh_public_7 
								WHEN '$d1' >= t_ghs.date_debut_public_8 AND '$d1' <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_exh_public_8 
								WHEN '$d1' >= t_ghs.date_debut_public_9 AND '$d1' <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_exh_public_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_tarif_exb =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_public_1 AND '$d1' <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_exb_public_1 
								WHEN '$d1' >= t_ghs.date_debut_public_2 AND '$d1' <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_exb_public_2 
								WHEN '$d1' >= t_ghs.date_debut_public_3 AND '$d1' <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_exb_public_3 
								WHEN '$d1' >= t_ghs.date_debut_public_4 AND '$d1' <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_exb_public_4 
								WHEN '$d1' >= t_ghs.date_debut_public_5 AND '$d1' <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_exb_public_5 
								WHEN '$d1' >= t_ghs.date_debut_public_6 AND '$d1' <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_exb_public_6 
								WHEN '$d1' >= t_ghs.date_debut_public_7 AND '$d1' <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_exb_public_7 
								WHEN '$d1' >= t_ghs.date_debut_public_8 AND '$d1' <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_exb_public_8 
								WHEN '$d1' >= t_ghs.date_debut_public_9 AND '$d1' <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_exb_public_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_forfait_exb =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_public_1 AND '$d1' <= t_ghs.date_fin_public_1 THEN t_ghs.forfait_exb_public_1 
								WHEN '$d1' >= t_ghs.date_debut_public_2 AND '$d1' <= t_ghs.date_fin_public_2 THEN t_ghs.forfait_exb_public_2 
								WHEN '$d1' >= t_ghs.date_debut_public_3 AND '$d1' <= t_ghs.date_fin_public_3 THEN t_ghs.forfait_exb_public_3 
								WHEN '$d1' >= t_ghs.date_debut_public_4 AND '$d1' <= t_ghs.date_fin_public_4 THEN t_ghs.forfait_exb_public_4 
								WHEN '$d1' >= t_ghs.date_debut_public_5 AND '$d1' <= t_ghs.date_fin_public_5 THEN t_ghs.forfait_exb_public_5 
								WHEN '$d1' >= t_ghs.date_debut_public_6 AND '$d1' <= t_ghs.date_fin_public_6 THEN t_ghs.forfait_exb_public_6 
								WHEN '$d1' >= t_ghs.date_debut_public_7 AND '$d1' <= t_ghs.date_fin_public_7 THEN t_ghs.forfait_exb_public_7 
								WHEN '$d1' >= t_ghs.date_debut_public_8 AND '$d1' <= t_ghs.date_fin_public_8 THEN t_ghs.forfait_exb_public_8 
								WHEN '$d1' >= t_ghs.date_debut_public_9 AND '$d1' <= t_ghs.date_fin_public_9 THEN t_ghs.forfait_exb_public_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_borne_basse =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_public_1 AND '$d1' <= t_ghs.date_fin_public_1 THEN t_ghs.borne_basse_public_1 
								WHEN '$d1' >= t_ghs.date_debut_public_2 AND '$d1' <= t_ghs.date_fin_public_2 THEN t_ghs.borne_basse_public_2 
								WHEN '$d1' >= t_ghs.date_debut_public_3 AND '$d1' <= t_ghs.date_fin_public_3 THEN t_ghs.borne_basse_public_3 
								WHEN '$d1' >= t_ghs.date_debut_public_4 AND '$d1' <= t_ghs.date_fin_public_4 THEN t_ghs.borne_basse_public_4 
								WHEN '$d1' >= t_ghs.date_debut_public_5 AND '$d1' <= t_ghs.date_fin_public_5 THEN t_ghs.borne_basse_public_5 
								WHEN '$d1' >= t_ghs.date_debut_public_6 AND '$d1' <= t_ghs.date_fin_public_6 THEN t_ghs.borne_basse_public_6 
								WHEN '$d1' >= t_ghs.date_debut_public_7 AND '$d1' <= t_ghs.date_fin_public_7 THEN t_ghs.borne_basse_public_7 
								WHEN '$d1' >= t_ghs.date_debut_public_8 AND '$d1' <= t_ghs.date_fin_public_8 THEN t_ghs.borne_basse_public_8 
								WHEN '$d1' >= t_ghs.date_debut_public_9 AND '$d1' <= t_ghs.date_fin_public_9 THEN t_ghs.borne_basse_public_9 
								ELSE 0::numeric 
								END,
								ghs_fg1_borne_haute =
								CASE 
								WHEN '$d1' >= t_ghs.date_debut_public_1 AND '$d1' <= t_ghs.date_fin_public_1 THEN t_ghs.borne_haute_public_1 
								WHEN '$d1' >= t_ghs.date_debut_public_2 AND '$d1' <= t_ghs.date_fin_public_2 THEN t_ghs.borne_haute_public_2 
								WHEN '$d1' >= t_ghs.date_debut_public_3 AND '$d1' <= t_ghs.date_fin_public_3 THEN t_ghs.borne_haute_public_3 
								WHEN '$d1' >= t_ghs.date_debut_public_4 AND '$d1' <= t_ghs.date_fin_public_4 THEN t_ghs.borne_haute_public_4 
								WHEN '$d1' >= t_ghs.date_debut_public_5 AND '$d1' <= t_ghs.date_fin_public_5 THEN t_ghs.borne_haute_public_5 
								WHEN '$d1' >= t_ghs.date_debut_public_6 AND '$d1' <= t_ghs.date_fin_public_6 THEN t_ghs.borne_haute_public_6 
								WHEN '$d1' >= t_ghs.date_debut_public_7 AND '$d1' <= t_ghs.date_fin_public_7 THEN t_ghs.borne_haute_public_7 
								WHEN '$d1' >= t_ghs.date_debut_public_8 AND '$d1' <= t_ghs.date_fin_public_8 THEN t_ghs.borne_haute_public_8 
								WHEN '$d1' >= t_ghs.date_debut_public_9 AND '$d1' <= t_ghs.date_fin_public_9 THEN t_ghs.borne_haute_public_9 
								ELSE 0::numeric 
								END,
								nb_exb_fg1 = w_tmp.nb_exb_fg1,
								nb_sej_exb_fg1 = CASE WHEN w_tmp.nb_exb_fg1 > 0 THEN 1 ELSE 0 END,
								nb_exh_fg1 = w_tmp.nb_exh_fg1,
								tarif_9605_fg1 = (SELECT tarif_ghs
								FROM base.t_ghs
								JOIN base.t_ghs_tarifs ON t_ghs_tarifs.ghs_id = t_ghs.oid
								WHERE 1=1
									AND t_ghs.code = '9605'
									AND t_ghs_tarifs.secteur = 1
									AND '$d5'::date BETWEEN date_debut AND date_fin),
								tarif_9604_fg1 = (SELECT tarif_ghs
								FROM base.t_ghs
								JOIN base.t_ghs_tarifs ON t_ghs_tarifs.ghs_id = t_ghs.oid
								WHERE 1=1
									AND t_ghs.code = '9604'
									AND t_ghs_tarifs.secteur = 1
									AND '$d5'::date BETWEEN date_debut AND date_fin)
							FROM w_tmp, pmsi.t_ghm, pmsi.t_ghs
							WHERE $simulationTable.annee_sortie = w_tmp.annee_sortie
							AND $simulationTable.no_rss = w_tmp.no_rss
							AND $simulationTable.liste_id = $liste_id
							AND w_tmp.ghm_fg1_code = t_ghm.code
							AND w_tmp.ghs_fg1_code = t_ghs.code
							";
				$result = $conn->dbQuery($sql);
				if (!$result) {
					$return_code	 = "$sql";
					$return_message	 = "Une erreur SQL a interrompu le traitement 9";
				}
			}
		}

		// Calcul des montants simulés.
		if ($return_code == "OK") {
			$sql	 = "
				UPDATE pmsi.$simulationTable
				SET 
					montant_ghs_theorique_fg1 = round(
						ghs_fg1_tarif_ghs 
						* CASE WHEN p_rss.nb_seances <= 1 THEN 1 ELSE p_rss.nb_seances END
						* coefficient_mco_fg1,2
					)
					+ round(tarif_9605_fg1 * nb_9605_fg1 * coefficient_mco_fg1,2)
					+ round(tarif_9604_fg1 * nb_9604_fg1 * coefficient_mco_fg1,2),
					montant_exh_fg1 = round(ghs_fg1_tarif_exh * nb_exh_fg1 * coefficient_mco_fg1,2)
				FROM pmsi.p_rss
				WHERE 1=1
					AND p_rss.oid = $simulationTable.rss_id
				;
			";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 10";
			}
		}

		if ($return_code == "OK") {
			$sql	 = "UPDATE pmsi.$simulationTable
					SET montant_exb_fg1 = 
					CASE WHEN ghs_fg1_forfait_exb > 0 THEN 0 - round(ghs_fg1_forfait_exb * coefficient_mco_fg1,2) 
					ELSE 0 - round(nb_exb_fg1 * ghs_fg1_tarif_exb * coefficient_mco_fg1,2) END
					WHERE nb_exb_fg1 > 0;";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 11";
			}
		}
		
		// Coefficient prodentiel
		if ($return_code == "OK") {
			$sql	 = "UPDATE pmsi.$simulationTable
					SET montant_exb_fg1 = round( montant_exb_fg1 * 0.9965),
					montant_exh_fg1 = round( montant_exh_fg1 * 0.9965),
					montant_ghs_theorique_fg1 = round(montant_ghs_theorique_fg1 * 0.9965);";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 11";
			}
			
			$sql	 = "UPDATE pmsi.$simulationTable
					SET montant_exb_fg1 = montant_exb_fg0,
					montant_exh_fg1 = montant_exh_fg0,
					montant_ghs_theorique_fg1 = montant_ghs_theorique_fg0
					WHERE ghm_fg1_id = ghm_fg0_id;";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 11";
			}
			
			$sql	 = "UPDATE pmsi.$simulationTable
					SET montant_exb_fg1 = montant_exb_fg0,
					montant_exh_fg1 = montant_exh_fg0,
					montant_ghs_theorique_fg1 = montant_ghs_theorique_fg0
					WHERE ghm_fg1_id = 0 OR erreur <> '';";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 11";
			}
		}
		
		if ($return_code == "OK") {
			$sql	 = "UPDATE pmsi.$simulationTable 
						SET erreur = 'RSS en double'
					WHERE no_rss IN (SELECT no_rss FROM pmsi.$simulationTable WHERE liste_id = $liste_id GROUP BY 1 HAVING count(*) > 1);";
			$result	 = $conn->dbQuery($sql);
		}
		
		// RSS significatifs
		if ($return_code == "OK") {
			$sql	 = "
				UPDATE pmsi.p_impact_diagnostics 
				SET ok_diag = subview.ok_diag,
					diags_enleves = subview.diags_enleves
				FROM
				(
					SELECT p_impact_diagnostics.liste_id, p_impact_diagnostics.rss_id, 
						MAX(CASE WHEN t_listes_contenu.liste_id IS NOT NULL THEN '1' ELSE '0' END) AS ok_diag,
						base.cti_group_concat(DISTINCT CASE WHEN t_listes_contenu.liste_id IS NOT NULL THEN t_diagnostics.code ELSE NULL END) AS diags_enleves
					FROM pmsi.p_impact_diagnostics
					LEFT JOIN pmsi.p_rss_diagnostics ON p_rss_diagnostics.rss_id = p_impact_diagnostics.rss_id
					LEFT JOIN pmsi.t_diagnostics ON diagnostic_id = t_diagnostics.oid
					LEFT JOIN pmsi.t_listes_contenu ON p_rss_diagnostics.diagnostic_id = t_listes_contenu.to_id AND p_impact_diagnostics.liste_id = t_listes_contenu.liste_id
					GROUP BY 1,2
				) subview
				WHERE p_impact_diagnostics.liste_id = subview.liste_id AND
					p_impact_diagnostics.rss_id = subview.rss_id AND
					(p_impact_diagnostics.ok_diag IS DISTINCT FROM subview.ok_diag OR
					p_impact_diagnostics.diags_enleves IS DISTINCT FROM subview.diags_enleves );
					";
			$result	 = $conn->dbQuery($sql);
			if (!$result) {
				$return_code	 = "$sql";
				$return_message	 = "Une erreur SQL a interrompu le traitement 10";
			}
		}

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

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

	echo "$return_code $return_message";
	// Nettoyage du cache PMSI MCO.
	cleanAllCache("iCTI_pmsi");

}

//functions utiles
function extract_um($d1,$d5) {
	global $conn;
	global $tmp_RSSoutfile;

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

	fwrite($tmp_RSSouthandle, "TYPEETS=".Environnement::getTypeets()."\r\n");

	$sql	 = "SELECT 
			'UNITEMEDIC' ||
			rpad(trim(code), 4, ' ') ||
			'".Environnement::getFiness()."' ||
			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'
					AND p_rss.date_sortie < '$d5'
				GROUP BY 1)
	";
	foreach($conn->queryFetchAllNum($sql) as $data) fwrite($tmp_RSSouthandle, "$data[0]\r\n");
	fclose($tmp_RSSouthandle);
}

function extract_rss($import_id,$year) {
	global $conn;
	global $tmp_path;

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

	$qrss = FALSE;

	$sql	 = "SELECT data FROM pmsi.p_imports_data 
				WHERE import_id = $import_id AND data_type = 'RSS' 
				ORDER BY data_num  ";
	foreach($conn->queryFetchAllNum($sql) as $data) {
		$handle = fopen($tmp_RSSinfile, 'a');
		fwrite($handle, uncompress(pg_unescape_bytea($data[0])));
		fclose($handle);
		$qrss = TRUE;
	}

	// pas de RSS, aller dans IN.ZIP
	if ($qrss == FALSE) {
		$sql	 = "SELECT data FROM pmsi.p_imports_data 
				WHERE import_id = $import_id AND data_type = 'ZIN' 
				ORDER BY data_num  ";
		foreach($conn->queryFetchAllNum($sql) as $data) {
			$handle = fopen($tmp_RSSinfileZip, 'a');
			fwrite($handle, uncompress(pg_unescape_bytea($data[0])));
			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);
						if ($filesuffix == "rss.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);
		}
	}

}

// traitement texte pour elenver diagnostics choisi
function filterDiag($diag_code_list,$year) {
	
	global $tmp_path;
	global $tmp_RSSoutfile;
	global $y;
	
		// préparation fichier
	// Premier passage, RSS à extraire (>= $d1)
	// rss à traiter
	$rss_array		 = array();
	$no_ligne		 = 0;

	$time_3103 = mktime(0, 0, 0, 03, 31, $y);

	$tmp_RSSinfile = $tmp_path . "/rss_" . $y . "_in.txt";
	$tmp_RSSinhandle = @fopen($tmp_RSSinfile, "r");
	$tmp_RSSouthandle = fopen($tmp_RSSoutfile, "a");
	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)));
				$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  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 (substr($RUMannee,0,2) == "20" and (int)substr($RUMversionFormat,1,2) >= 16 ) {
							if ($RUMannee == $y && $RUMmois >= '03' && $RUMmois <= '12') $rss_array[$no_rss] = "OK";
							if ($RUMannee == ($y+1) && $RUMmois >= '01' && $RUMmois <= '02') $rss_array[$no_rss] = "OK";
						}
					}
				}
			}
		}
	}
	fclose($tmp_RSSinhandle);
	
	//echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "FILTE" . "\t" . "Filtrage diagnostics ".$diag_code_list;
	
	$no_ligne = 0;
	$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)));

				if ($rss_array[$no_rss] == "OK") {			
					$no_rss_out = $year . substr("000000000000000000000" . $no_rss, -16, 16);
					$buffer = substr_replace($buffer, $no_rss_out, 27, 20);

					$codepost	 = substr($buffer, 112, 2) . "000";
					$buffer		 = substr_replace($buffer, $codepost, 112, 5);
					$nb_diags	 = (int)(substr($buffer, 133, 2));
					for ($i=0 ; $i < $nb_diags ; $i++) {
						if(in_array(trim(substr($buffer,192 + ($i * 8),8)) ,$diag_code_list))  {
							$nb_diags--;
							$buffer = substr_replace($buffer, ($nb_diags < 10 ? '0'.$nb_diags : $nb_diags) , 133 , 2);
							$buffer = substr_replace($buffer,'',192 + ($i * 8),8);
							$changed = true;
							
						}
					}
					fwrite($tmp_RSSouthandle, $buffer);
				}
			}
		}
		fclose($tmp_RSSouthandle);
		fclose($tmp_RSSinhandle);
	}
}

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

//get ghm for grouping function
function get_ghm($from_code) {

    global $conn;
    global $ghms_array;
    global $ok_ghms_array;

    $texte = "";

    if ($from_code == "") {
        return $texte;
    }

    if ($ok_ghms_array !== TRUE) {
        $ghms_array = array();
		foreach($conn->queryFetchAllAssoc("SELECT code, texte FROM pmsi.t_ghm ") as $record) {
                $code = trim($record["code"]);
                $texte = $record["texte"];
                $ghms_array[$code] = $texte;
        }

        $ok_ghms_array = TRUE;
    }

    $texte = "";
    if ($ok_ghms_array === TRUE) {
        $texte = @$ghms_array[$from_code];
    }

    return $texte;
}

//get error for grouping function
function get_err($from_code) {
    global $workDir;
    global $errs_array;
    global $ok_errs_array;

    $texte = "";

    if ($from_code == "") {
        return $texte;
    }

    if ($ok_errs_array !== TRUE) {
        $errs_array = array();
        $err_handle = fopen($workDir ."/pgm/fg/LIB/LIBERRFG.TXT", "r");

        while (($data = fgetcsv($err_handle, 1000, "|")) !== FALSE) {
            $code = substr(trim($data[0]), 1);
            $texte = trim($data[0]) . " " . $data[1];
            $errs_array[$code] = $texte;
        }
        fclose($err_handle);

        $ok_errs_array = TRUE;
    }

    $texte = $from_code;
    if ($ok_errs_array === TRUE) {
        $texte = @$errs_array[$from_code];
    }

    return $texte;
}
?>