<?php
$MODULE="activite";
$TITLE="Consolidation ACTIVITE";
$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 $nbE;

require_once("../../../modules/base/php/lib/cti/Batch/iCTI_batch_common.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/lib/cti/Database/Database2Factory.class.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_activite", TRUE);
		
}

iCTI_disconnect();

logEndMsg();

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

	global $iCTI_connexion;
	global $environments_array;
    global $PROPERTY_SENSPARAMETRE_CLASSE;
	global $ENV_ADM_ANNEEDEBUT;

	global $cti_args;
    
	
	// Chargement requetes SQL
	$environmentVars=array();
	$sqlOptions=array();
	
	
	$i_env = "";
	if (isset($cti_args->args["-e"])) {
		$i_env = trim($cti_args->args["-e"]);
	}
	
	$cti_sqlStatements = new CTI_SqlStatements_class("iCTI_import_activite_CONSOLIDATION.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
	
	if ($i_env == "") {
		$cti_sqlStatements->executeStatementsNode("DISABLE_INDEX");
		$cti_sqlStatements->executeStatementsNode("RAZ");
	}

	foreach ($environments_array as $environment_array) {
		if ($i_env == "" || $i_env == $environment_array["PREFIX_CODE"] || $i_env == $environment_array["PREFIX_OID"]) {
			$environmentVars=array();
			$environmentVars["MODE"] = "RAZ";
			if ($i_env != "") {
				$environmentVars["MODE"] = "UPDATE";
			}
			$environmentVars["DBNAME"] = $environment_array["dbname"];
			$environmentVars["DBHOST"] = $environment_array["dbhost"];
			$environmentVars["DBPORT"] = $environment_array["dbport"];
			$environmentVars["DBUSERNAME"] = $environment_array["dbusername"];
			$environmentVars["DBPASSWORD"] = $environment_array["dbpassword"];
			$environmentVars["FINESS"] = $environment_array["finess"];
			$environmentVars["FINESS_TEXTE"] = $environment_array["texte"];
            $environmentVars["KEEP_FINESS"] = $environment_array["keep_finess"];
            $environmentVars["SENSPARAMETRE_CLASSE"] = $PROPERTY_SENSPARAMETRE_CLASSE;
			$environmentVars["TPX"] = $environment_array["PREFIX_CODE"] . "_";
			$environmentVars["CPX"] = $environment_array["PREFIX_CODE"] . "_";
			$environmentVars["IPX"] = $environment_array["PREFIX_OID"] . "000000000000";
			$environmentVars["PPX"] = $environment_array["PREFIX_OID"];
			$environmentVars["PX"] = $environment_array["PREFIX_CODE"];
			$environmentVars["ENV_ADM_ANNEEDEBUT"] = $ENV_ADM_ANNEEDEBUT;
			$cti_sqlStatements_env = new CTI_SqlStatements_class("iCTI_import_activite_CONSOLIDATION.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
			$cti_sqlStatements_env->executeStatementsNode("INIT");
			$cti_sqlStatements_env->executeStatementsNode("PARAM");
			$cti_sqlStatements_env->executeStatementsNode("SEJOUR");
			$cti_sqlStatements_env->executeStatementsNode("FACTURE");
			$cti_sqlStatements_env->executeStatementsNode("CHIFFRIER");
		}
	}

	$cti_sqlStatements->executeStatementsNode("ENABLE_INDEX");
	$cti_sqlStatements->executeStatementsNode("POST");
	$cti_sqlStatements->executeStatementsNode("VACUUM");

}

function iCTI_connect() {

global $iCTI_connexion;
global $iCTI_cache;

global $environments_array;
global $PROPERTY_SENSPARAMETRE_CLASSE;
global $ENV_ADM_ANNEEDEBUT;


	// Chargement des paramètres et connexion BD
	$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
	$ret = $iCTI_connexion->connect();
	if (!$ret) {
		logErrorMsg("La connexion PostgreSQL iCTI a échoué");
		return 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'] == 'CONSOLIDATIONACTIVITE') {
				$ENV_CONSOLIDATION = $propertyNode['value'];
			}
			if ($propertyNode['name'] == 'OPTADM_ANNEEDEBUT') {
				//Soit on utilise dans le setting une année en dur soit un nombre d'année(s) précédé de la lettre A
				if (substr($propertyNode['value'],0,1)==='A'){
					//année en cours moins nombre années demandées
					$nbAnnee = substr($propertyNode['value'],1);
					$ENV_ADM_ANNEEDEBUT = date("Y")-intval($nbAnnee);
				} else if ($propertyNode['value']!="" && strlen($propertyNode['value']) === 4) {
					// si années écrit en dur
					$ENV_ADM_ANNEEDEBUT = $propertyNode['value'];
				}
			}
		}
	}

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

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

			foreach ($environmentNode->PROPERTY as $propertyNode) {
				if ($propertyNode['name'] == 'ENVIRONMENT') {
					$environment_texte = utf8_decode($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'DIR') {
					$environment_dir = $propertyNode['value'];
				}
				if ($propertyNode['name'] == 'PREFIX_CODE') {
					$environment_PREFIX_CODE = strtoupper(trim(utf8_decode($propertyNode['value'])));
				}
				if ($propertyNode['name'] == 'PREFIX_OID') {
					$environment_PREFIX_OID = utf8_decode($propertyNode['value']) + 0;
				}
                if ($propertyNode['name'] == 'KEEP_FINESS') {
					$environment_KEEP_FINESS = strtoupper(trim(utf8_decode($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 {
					if ($environment_PREFIX_CODE == "" || $environment_PREFIX_OID == 0) {
						logErrorMsg("Préfixes obligatoires ($environment_PREFIX_CODE,$environment_PREFIX_OID) pour environnement $environment_texte");
						$environment_error = TRUE;
					}
					else {
						$environment_array = array();
						$environment_array["dir"] = $environment_dir;
						$environment_array["finess"] = $environment_finess;
                        $environment_array["keep_finess"] = $environment_KEEP_FINESS;
						$environment_array["texte"] = $environment_texte;
						$environment_array["dbhost"] = $environment_host;
						$environment_array["dbname"] = $environment_dbname;
						$environment_array["dbport"] = $environment_port;
                        $environment_array["dbusername"] = $environment_username;
                        $environment_array["dbpassword"] = $environment_password;
						$environment_array["PREFIX_CODE"] = $environment_PREFIX_CODE;
						$environment_array["PREFIX_OID"] = $environment_PREFIX_OID;
						$environments_array[] = $environment_array;
					}
				}
			}

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

}

function iCTI_disconnect() {

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