<?php
$MODULE="pmsi";
$TITLE="Consolidation PMSI";
$DFTENDSTATUS="OK";
$ARGS="-raz";
/** Laisser les lignes 2 à 5 sans changer la casse et sans espaces et dans cet ordre
 * car le script est lu et analysé quand il est exécuté via .exe ou Jenkins
 * pour gestion des fichiers .pid dans system\batch\logs
 */

global $ENDSTATUS;
global $iCTI_connexion;
global $ADMPROVIDER;
global $ADMPROVIDER2;
global $ADMPROVIDER_PREFIX;
global $ADMPROVIDER2_PREFIX;
global $ENV_TYPEETS;
global $ENV_ADM_ANNEEDEBUT;
global $ENV_CONSO_PMSI_ANNEE_DEBUT;
global $nbE;


require_once("../../../modules/base/php/lib/cti/Batch/iCTI_batch_common.php" );
require_once("../../../modules/base/php/lib/cti/Database/Database2Factory.class.php");
require_once("../../../modules/base/php/lib/cti/Environnement/Environnement.class.php");
require_once("../../../modules/base/php/lib/cti/EnvironmentSettings/EnvironmentDatabaseSettings.php");
require_once("../../../modules/base/php/classSimpleXML.php");
require_once("../../../modules/outils/php/httpService_cacheManager_cleanCache.php");
require_once("../../../modules/pmsi/php/EtudeManager.php");
require_once("../../../modules/pmsi/import_rss_rsf/utils/import_functions.php");
require_once("../../../modules/pmsi/import_rss_rsf/utils/conso_functions.php");
require_once("../../../modules/base/php/utils/cti_args_functions.php");

logStartMsg();


if (iCTI_connect()) {

	// création du répertoire utilisé par la fonction base.cti_copy_table(i_fromdblink text, i_fromtable text, i_totable text)
	if (!is_dir('C:/TEMP')) {
		mkdir('C:/TEMP');
	}
	
	consolidation_environnements();

	logInfoMsg("Nettoyage cache");
	cleanAllCache("iCTI_pmsi", TRUE);
		
	iCTI_disconnect();
}


logEndMsg();

// récupération historique
function consolidation_environnements() {

	global $iCTI_connexion;
	global $environmentVars;
	global $ENV_FINESS_PRINCIPAL;
	global $ENV_CONSO_PMSI_ANNEE_DEBUT;
	global $ENV_CONSO_PMSI_DELETE_BEFORE_YEAR;


	//////////////   PARAMETRE DE COMMANDE   /////////////
	// Arguments transmis 
	$cti_args = new CTI_Args_class();

	// -xx || --except-expert
	$expert = get_cti_args_expert($cti_args);

	// -xe || --except-essentiels
	$essentiels = get_cti_args_essentiels($cti_args);

	// -env
	$forced_env = get_cti_args_env($cti_args);

	// --moisforces || -mf
	// --annee-mois-force || -af
	$moisforces = get_cti_args_mois_forces($cti_args);
	if ($moisforces !== "0"){
		$ENV_CONSO_PMSI_ANNEE_DEBUT = find_min_year($moisforces);
	}

	//////////////   PARAMETRAGE ENVIRONNEMENT   /////////////
	$environmentVars = array();
    $environmentVars["EXPERT"] = $expert;
    $environmentVars["ESSENTIELS"] = $essentiels;
	$environmentVars["FINESS_PRINCIPAL"] = $ENV_FINESS_PRINCIPAL;
	$environmentVars["CONSO_PMSI_ANNEE_DEBUT"] = $ENV_CONSO_PMSI_ANNEE_DEBUT;
	$environmentVars["MOISFORCES"] = $moisforces;


	///////////   INITIALISTATION : INIT  ///////////
	$cti_sqlStatements = new CTI_SqlStatements_class("iCTI_import_pmsi_CONSOLIDATION.XML",$iCTI_connexion,$environmentVars);
	$cti_sqlStatements->executeStatementsNode("INIT");
	
	
	///////////   CONSOLIDATION : GETENV ///////////
 	$executed = execute_statement_node_getenv($forced_env);
	if (!$executed) {
		logErrorMsg("L'établissement $forced_env n'a pas été trouvé dans les settings");
		die_conso();
	}

	
	///////////   POST TRAITEMENT : POST  ///////////

	// Suppression des séjours Et intégrité des la bdd
	nettoyage_sejours_bdd($ENV_CONSO_PMSI_DELETE_BEFORE_YEAR);
	
	$cti_sqlStatements->executeStatementsNode("POST");

}


function execute_statement_node_getenv($forced_env){
	
	global $environments_settings;
	global $iCTI_connexion;
	
	$executed = false;
	foreach ($environments_settings as $environment) {
		$db_name = strtolower($environment["dbname"]);
		if ($forced_env == '' || $forced_env == $db_name) {
			$executed = true;
			$environmentVars = get_environmentVars($environment);
			$cti_sqlStatements_finess = new CTI_SqlStatements_class("iCTI_import_pmsi_CONSOLIDATION.XML",$iCTI_connexion,$environmentVars);
			$cti_sqlStatements_finess->executeStatementsNode("GETENV");
		}
	}
	
	return $executed;
}


function get_environmentVars($environment){

	global $environmentVars;

	$environmentVars["DBNAME"] = $environment["dbname"];
	$environmentVars["DBPORT"] = $environment["dbport"];
	$environmentVars["DBHOST"] = $environment["dbhost"];
	$environmentVars["DBUSERNAME"] = $environment["dbusername"];
	$environmentVars["DBPASSWORD"] = $environment["dbpassword"];
	$environmentVars["FINESS"] = $environment["finess"];
	$environmentVars["FINESS_TEXTE"] = $environment["texte"];
	
	return $environmentVars;
}



function iCTI_connect() {


global $iCTI_connexion;
global $ENV_FINESS_PRINCIPAL;
global $ENV_CONSO_PMSI_ANNEE_DEBUT;
global $ENV_CONSO_PMSI_DELETE_BEFORE_YEAR;

global $environments_settings;

	$iCTI_connexion = FALSE;
	
	
	
	$file = "../../../settings/settings.XML";
	$settings_xml = simplexml_load_file($file);
	
	$ENV_CONSOLIDATION = "0";
	// On traite l'année en cours + 2 années par défault 
	$ENV_CONSO_PMSI_ANNEE_DEBUT = transform_AX_in_annee_mois("A2");
	// Supprimer les séjours avant une année AX donnée dans les settings
	$ENV_CONSO_PMSI_DELETE_BEFORE_YEAR= false;
	
	$properties =  $settings_xml->xpath("/SETTINGS/ENVIRONMENT/PROPERTY");

	foreach ($properties as $propertyNode) {
		if ($propertyNode['name'] == 'CONSOLIDATION') {
			$ENV_CONSOLIDATION = $propertyNode['value'];
		}
		if ($propertyNode['name'] == 'FINESS') {
			$ENV_FINESS_PRINCIPAL = $propertyNode['value'];
		}
		if ($propertyNode['name'] == 'CONSO_PMSI_ANNEE_DEBUT' || $propertyNode['name'] == 'DEPUIS_ANNEE_MOIS_SORTIE') {
			$ENV_CONSO_PMSI_ANNEE_DEBUT = transform_AX_in_annee_mois($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'CONSO_PMSI_DELETE_BEFORE_YEAR') {
			$year_AX = $propertyNode['value'];
			if (is_year_AX($year_AX)){
				//On garde au moins l'année en cours + 2 ans au cas où
				$year_mini_delete_before = date("Y") - 2;
				$year_delete_before = transform_AX_in_year($year_AX);
				if ($year_delete_before <= $year_mini_delete_before){
					$ENV_CONSO_PMSI_DELETE_BEFORE_YEAR = $year_delete_before;
				}
			}
		}
	}

	
	
	if ($ENV_CONSOLIDATION != "1") {
		logErrorMsg("Environnement NON CONSOLIDE");
		return FALSE;
	}
	
	
	$environment_error = FALSE;
	$environments_settings = array();
	
	$environments =  $settings_xml->xpath("/SETTINGS/CONSOLIDATION/ENVIRONMENT");

	// Création d'un tableau comprenant les infos de connexion de tous les environnements du conso
	foreach ($environments as $environmentNode) {

		$environment_dir = "";
		$environment_finess = "";
		$environment_texte = "";
		$environment_dbname = "";
		$environment_host = "";
		$environment_port = "";
		$environment_username = "";
		$environment_password = "";

		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if ($propertyNode['name'] == 'ENVIRONMENT') {
				$environment_texte = utf8_decode($propertyNode['value']);
			}
			if ($propertyNode['name'] == 'DIR') {
				$environment_dir = $propertyNode['value'];
			}
		}
		
		//Chaine de connexion
		$dbSettings = new EnvironmentDatabaseSettings($environment_dir);
		try {
			$dbSettings->readSettings();
		} catch (Exception $e) {
			logErrorMsg($e->getMessage());
			$environment_error = TRUE;
		}
		
		$environment_host = $dbSettings->getHost();
		$environment_port = $dbSettings->getPort();
		$environment_dbname = $dbSettings->getName();
		$environment_username = $dbSettings->getUsername();
		$environment_password = $dbSettings->getPassword();
		
		//Settings de l'environnemnt
		if (file_exists($environment_dir . "/settings/settings.xml")) {
			$environment_settings_xml = simplexml_load_file($environment_dir . "/settings/settings.xml");
			if ($environment_settings_xml) {
				foreach ($environment_settings_xml->ENVIRONMENT as $toEnvironmentNode) {
					foreach ($toEnvironmentNode->PROPERTY as $toPropertyNode) {
						if ($toPropertyNode['name'] == 'FINESS') {
							$environment_finess = $toPropertyNode['value'];
						}
						if ($toPropertyNode['name'] == 'ENVIRONMENT') {
							$environment_texte = utf8_decode($toPropertyNode['value']);
						}
					}
				}
			}
		}
		else {
			logErrorMsg("iCTI_connect : Fichier settings de l'environnement non trouvé, vérifier le DIR du '$environment_texte' dans les settings du consolidé");
			$environment_error = TRUE;
		}
		
		if ($environment_dbname == "") {
			logErrorMsg("iCTI_connect : Nom de la base de donnée non trouvé");
			$environment_error = TRUE;
		}
		if ($environment_finess == "") {
			logErrorMsg("iCTI_connect : Finess non trouvé");
			$environment_error = TRUE;
		}
		
		if ($environment_error == TRUE) {
			logErrorMsg("iCTI_connect : Environnement '$environment_texte' sur '$environment_dir' inexistant ou mal configuré");
			logErrorMsg("iCTI_connect : Au moins un environnement de la consolidation n'est pas correct");
			return FALSE;

		}

		$environment = array();
		$environment["dir"] = $environment_dir;
		$environment["finess"] = $environment_finess;
		$environment["texte"] = $environment_texte;
		$environment["dbname"] = $environment_dbname;
		$environment["dbport"] = $environment_port;
		$environment["dbhost"] = $environment_host;
		$environment["dbusername"] = $environment_username;
		$environment["dbpassword"] = $environment_password;
		$environments_settings[] = $environment;
	}
	
	

	$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
	$ret = $iCTI_connexion->connect();
	if (!$ret) {
		logErrorMsg("La connexion PostgreSQL iCTI a échoué");
		return FALSE;
	}
	
	return $ret;

}


    
?>
