<?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 $cti_args;
global $ADMPROVIDER;
global $ADMPROVIDER2;
global $ADMPROVIDER_PREFIX;
global $ADMPROVIDER2_PREFIX;
global $ENV_TYPEETS;
global $ENV_ADM_ANNEEDEBUT;
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");

logStartMsg();

// Arguments transmis ?
$cti_args = new CTI_Args_class();

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 $environments_array;

    global $cti_args;

    // paramètre permettant d'omettre l'exécution des règles expert
    $expert = "1";
    if (isset($cti_args->args["-xx"]) || isset($cti_args->args["--except-expert"])) {
        $expert = "0";
    }
    
    // paramètre permettant d'omettre le calcul des essentiels
    $essentiels = "1";
    if (isset($cti_args->args["-xe"]) || isset($cti_args->args["--except-essentiels"])) {
        $essentiels = "0";
    }
    
    // Chargement requetes SQL
    $environmentVars=array();
    $environmentVars["EXPERT"] = $expert;
    $environmentVars["ESSENTIELS"] = $essentiels;
    

    $sqlOptions=array();
    
    if (! isset($cti_args->args["-moisforces"])) {
        $cti_args->args["-moisforces"] = "0";
    }
    
    
    $cti_sqlStatements = new CTI_SqlStatements_class("iCTI_import_pmsi_CONSOLIDATIONSIMUL2223.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
    $cti_sqlStatements->executeStatementsNode("INIT");
    
    
    foreach ($environments_array as $environment_array) {
        $environmentVars["DBHOST"] = $environment_array["dbhost"];
        $environmentVars["DBPORT"] = $environment_array["dbport"];
        $environmentVars["DBNAME"] = $environment_array["dbname"];
		$environmentVars["DBUSERNAME"] = $environment_array["dbusername"];
		$environmentVars["DBPASSWORD"] = $environment_array["dbpassword"];
        $environmentVars["FINESS"] = $environment_array["finess"];
        $environmentVars["FINESS_TEXTE"] = $environment_array["texte"];
        $environmentVars["MOISFORCES"] = $cti_args->args["-moisforces"];

        $cti_sqlStatements_finess = new CTI_SqlStatements_class("iCTI_import_pmsi_CONSOLIDATIONSIMUL2223.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
        $cti_sqlStatements_finess->executeStatementsNode("GETENV");
    }
        
    $cti_sqlStatements->executeStatementsNode("POST");

}

function iCTI_connect() {


global $iCTI_connexion;
global $iCTI_cache;

global $environments_array;



    $iCTI_connexion = FALSE;

    $file = "../../../settings/settings.XML";
    $settings_xml = simplexml_load_file($file);
    
    $ENV_CONSOLIDATION = "0";

    foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
        foreach ($environmentNode->PROPERTY as $propertyNode) {
            if ($propertyNode['name'] == 'CONSOLIDATION') {
                $ENV_CONSOLIDATION = $propertyNode['value'];
            }
        }
    }
    
    
    if ($ENV_CONSOLIDATION != "1") {
        logErrorMsg("Environnement NON CONSOLIDE");
        return FALSE;
    }
    
    
    $environment_error = FALSE;
	$environments_array = array();
	foreach ($settings_xml->CONSOLIDATION as $consolidationNode) {
		foreach ($consolidationNode->ENVIRONMENT as $environmentNode) {

			$environment_dir = "";
			$environment_finess = "";
			$environment_texte = "";
			$environment_host = "";
			$environment_port = "";
			$environment_dbname = "";
			$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 = trim($propertyNode['value']);
				}
			}

            $dbSettings = new EnvironmentDatabaseSettings($environment_dir);
            try {
                $dbSettings->readSettings();
            } catch (Exception $e) {
                logErrorMsg($e->getMessage());
                return false;
            }
            
            $environment_host = $dbSettings->getHost();
            $environment_port = $dbSettings->getPort();
            $environment_dbname = $dbSettings->getName();
            $environment_username = $dbSettings->getUsername();
            $environment_password = $dbSettings->getPassword();
			
			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 = trim($toPropertyNode['value']);
							}
							if ($toPropertyNode['name'] == 'ENVIRONMENT') {
								$environment_texte = utf8_decode($toPropertyNode['value']);
							}
						}
					}
				}
			}
			else {
				logErrorMsg("Environnement $environment_texte sur $environment_dir inexistant ou mal configuré");
				$environment_error = TRUE;
			}
			
			if ($environment_dbname == "") {
				logErrorMsg("Environnement $environment_texte sur $environment_dir inexistant ou mal configuré");
				$environment_error = TRUE;
			}
			else {
				if ($environment_finess == "") {
					logErrorMsg("Environnement $environment_texte sur $environment_dir inexistant ou mal configuré");
					$environment_error = TRUE;
				}
				else {
					$environment_array = array();
					$environment_array["dir"] = $environment_dir;
					$environment_array["finess"] = $environment_finess;
					$environment_array["texte"] = $environment_texte;
					$environment_array["dbhost"] = $environment_host;
					$environment_array["dbport"] = $environment_port;
					$environment_array["dbname"] = $environment_dbname;
					$environment_array["dbusername"] = $environment_username;
					$environment_array["dbpassword"] = $environment_password;
					$environments_array[] = $environment_array;
				}
			}

		}
	}
    
    if ($environment_error == TRUE) {
        logErrorMsg("Au moins un environnement de la consolidation n'est pas correct");
        return FALSE;
    }

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

}

function iCTI_disconnect() {

    global $iCTI_connexion;
    
    $iCTI_connexion->close();
}
    
?>
