<?php
$MODULE="ECO";
$TITLE="Récupération ECO";
$DFTENDSTATUS = "OK";
$ARGS="";
/** 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
 */

if (!defined('__ROOT__') ) {
	list($environmentPath) = explode(DIRECTORY_SEPARATOR.'modules', dirname(__FILE__));
	$environmentPath .= DIRECTORY_SEPARATOR;
	define('__ROOT__', $environmentPath);
}

require_once __ROOT__ . '/modules/base/php/lib/cti/Batch/iCTI_batch_common.php';
require_once __ROOT__ . '/modules/base/php/classSimpleXML.php';
require_once __ROOT__ . '/modules/outils/php/httpService_cacheManager_cleanCache.php';
require_once __ROOT__ . '/modules/base/php/lib/cti/Database/Database2Factory.class.php';
require_once __ROOT__ . '/modules/base/php/lib/cti/Environnement/Environnement.class.php';
require_once __ROOT__ . '/modules/base/php/lib/cti/EnvironmentSettings/EnvironmentDatabaseSettings.php';

global $ENDSTATUS;
global $iCTI_connexion;
global $iCTI_cache;
global $cti_args;
global $cti_sqlStatements;
global $ENV_TYPEETS;
global $ENV_FINESS;
global $p1;
global $p2;
global $p3;
global $p4;
global $p1Start;
global $p2Start;
global $p3Start;
global $p4Start;
global $p1End;
global $p2End;
global $p3End;
global $p4End;
global $nbE;
global $ENV_ECO_ANNEEDEBUT;

$p2 = '';
$p3 = '';
$p4 = '';
logStartMsg();


$prefixes = array(
    'cegi' => 'CJ',
	'cliwin' => 'CL',
    'pharma' => 'PH',
    'sagex3' => 'SX',
    'sage100compta' => 'SC',
    'evolucare_hygie' => 'HY',
    'shs' => 'SH',
    'sigems' => 'SI',
	'winpharm' => 'WP',
	'web100t' => 'W1',
    'hsp' => 'HS',
	'qsp' => 'QS',
	'medicagest' => 'MG',
	'optim' => 'OP',
	'hestia' => 'HE',
	'qualiac' => 'QU',
	'expert_sante' => 'EX'
);

// Récupération des arguments passés en paramètres
$cti_args = new CTI_Args_class();
$cti_args->checkArgs();

$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
$ret = $iCTI_connexion->connect();

// Chargement des paramètres et connexion BD
init();


// Mise à niveau production
if (!array_key_exists($p1,$prefixes)) {
	$delpos = strrpos($p1,'_');
	$prefixes[$p1] = (in_array(substr($p1,$delpos+1),$prefixes) ? $prefixes[substr($p1,0,$delpos)].'_' : '').substr($p1,$delpos+1);
}
if (!isset($cti_args->args["--fusion_only"])) {
	$exitCode1 = extraction_prod($p1);
}
if ($p2 != '') {
	//detection provider manaquant mais comme un autre avec _suffixe
	if (!array_key_exists($p2,$prefixes)) {
		$delpos = strrpos($p2,'_');
		$prefixes[$p2] = (in_array(substr($p2,$delpos+1),$prefixes) ? $prefixes[substr($p2,0,$delpos)].'_' : '').substr($p2,$delpos+1);
	}
	if (!isset($cti_args->args["--fusion_only"])) {
		$exitCode2 = extraction_prod($p2);
	}
}
else $p2 = 0;
if ($p3 != '') {
	if (!array_key_exists($p3,$prefixes)) {
		$delpos = strrpos($p3,'_');
		$prefixes[$p3] = (in_array(substr($p3,$delpos+1),$prefixes) ? $prefixes[substr($p3,0,$delpos)].'_' : '').substr($p3,$delpos+1);
	}
	if (!isset($cti_args->args["--fusion_only"])) {
		$exitCode3 = extraction_prod($p3);
	}
}
else $p3 = 0;
if ($p4 != '') {
	if (!array_key_exists($p4,$prefixes)) {
		$delpos = strrpos($p4,'_');
		$prefixes[$p4] = (in_array(substr($p4,$delpos+1),$prefixes) ? $prefixes[substr($p4,0,$delpos)].'_' : '').substr($p4,$delpos+1);
	}
	$exitCode4 = extraction_prod($p4);
}
else $p4 = 0;
if (isset($cti_args->args["--fusion_only"])) {
	$exitCode1 = 0;
	$exitCode2 = 0;
	$exitCode3 = 0;
}

if (($exitCode1 + $exitCode2 + $exitCode3 + $exitCode4 > 0) && !isset($cti_args->args["-f"])) {
	  logErrorMsg("Problème de chargement des données prestataire.");
} else {
    logInfoMsg("Données prestataire chargées avec succès.");

    // Auto-réparation des schémas eco_xx si plantage en cours.
    if (schemaExists('eco_ori')) {
        logInfoMsg("Auto-réparation des schémas.");
        if (schemaExists('eco') && schemaExists("eco_".strtolower($prefixes[strtolower($p2)])) 
				&& ($p3 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p3)])))
				&& ($p4 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p4)])))) {
            changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p1)]));
        } elseif (schemaExists('eco') && schemaExists("eco_".strtolower($prefixes[strtolower($p1)]))
				&& ($p3 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p3)])))
				&& ($p4 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p4)])))) {
            changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p2)]));
        } elseif ( schemaExists('eco') && schemaExists("eco_".strtolower($prefixes[strtolower($p1)])) 
				&& schemaExists("eco_".strtolower($prefixes[strtolower($p2)]))
				&& ($p4 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p4)])))
				&& $p3 != 0) {
            changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p3)]));
        } elseif ( schemaExists('eco') && schemaExists("eco_".strtolower($prefixes[strtolower($p1)]))
				&& schemaExists("eco_".strtolower($prefixes[strtolower($p2)]))
				&& schemaExists("eco_".strtolower($prefixes[strtolower($p3)]))
				&& $p4 != 0) {
            changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p4)]));
        }
        if (!schemaExists('eco')) {
            changeSchemaName("eco_ori", "eco");
        }
    }
    if (schemaExists('eco_src')) {
        logInfoMsg("Auto-réparation des schémas.");
        if (schemaExists("eco_".strtolower($prefixes[strtolower($p2)])) 
				&& ($p3 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p3)])))
				&& ($p4 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p4)])))) {
            changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p1)]));
        } elseif (schemaExists("eco_".strtolower($prefixes[strtolower($p1)]))
				&& ($p3 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p3)])))
				&& ($p4 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p4)])))) {
            changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p2)]));
        } elseif (schemaExists("eco_".strtolower($prefixes[strtolower($p1)])) 
				&& schemaExists("eco_".strtolower($prefixes[strtolower($p2)]))
				&& ($p4 == 0 || schemaExists("eco_".strtolower($prefixes[strtolower($p4)])))
				&& $p3 != 0) {
            changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p3)]));
        } elseif (schemaExists("eco_".strtolower($prefixes[strtolower($p1)])) 
			&& schemaExists("eco_".strtolower($prefixes[strtolower($p2)]))
			&& schemaExists("eco_".strtolower($prefixes[strtolower($p3)]))
			&& $p4 != 0) {
            changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p4)]));
        }
        if (!schemaExists('eco') && schemaExists('eco_ori')) {
            changeSchemaName("eco_ori", "eco");
        }
    }
	// vérification des schemma prod si plusieurs bases avec même prestataire
    if (schemaExists('prod_'.$p1.'_ori')) {
        logInfoMsg("Auto-réparation des schémas prod_$p1.");
        if (!schemaExists('prod_'.$p2)) {
            changeSchemaName('prod_'.$p1, 'prod_'.$p2);
        } elseif (!schemaExists('prod_'.$p3)) {
            changeSchemaName('prod_'.$p1, 'prod_'.$p3);
		} elseif (!schemaExists('prod_'.$p4)) {
            changeSchemaName('prod_'.$p1, 'prod_'.$p4);
        }
        changeSchemaName('prod_'.$p1.'_ori', 'prod_'.$p1);
    }
    if (schemaExists('prod_'.$p2.'_ori')) {
        logInfoMsg("Auto-réparation des schémas prod_$p1.");
        if (!schemaExists('prod_'.$p3)) {
            changeSchemaName('prod_'.$p1, 'prod_'.$p3);
			changeSchemaName('prod_'.$p1.'_ori', 'prod_'.$p1);
		}
    }
	if (schemaExists('prod_'.$p3.'_ori')) {
        logInfoMsg("Auto-réparation des schémas prod_$p1.");
        if (!schemaExists('prod_'.$p4)) {
            changeSchemaName('prod_'.$p1, 'prod_'.$p4);
			changeSchemaName('prod_'.$p1.'_ori', 'prod_'.$p1);
		}
    }
	
	$sqlOptions = array();
		
	foreach ($cti_args->args as $key => $value) {
		$sqlOptions[] = $key;
	}

	$environmentVars = array();
	
	$cti_sqlStatements_share = new CTI_SqlStatements_class("iCTI_import_eco_SHARE.XML", $iCTI_connexion, $environmentVars, $sqlOptions);
	if (!isset($cti_args->args["--only-expert"])) {
		if (!isset($cti_args->args["--no_fusion"])) {
			$cti_sqlStatements_share->executeStatementsNode("INIT");
		}
		// Import CTI
		if (!isset($cti_args->args["--fusion_only"])) {
			if ($p2 != '') {
				changeSchemaName("eco", "eco_ori");
				changeSchemaName("eco_".strtolower($prefixes[strtolower($p1)]), "eco");
				initialisationSchemas(0, '');
			}
			
			if((!isset($cti_args->args["-p2"]) && !isset($cti_args->args["-p3"]) && !isset($cti_args->args["-p4"])) || isset($cti_args->args["-p1"])) {
				extraction_environnement($p1);
			}

			if ($p2 != '') {
				changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p1)]));
				changeSchemaName("eco_".strtolower($prefixes[strtolower($p2)]), "eco");

				initialisationSchemas(1, strtolower($prefixes[strtolower($p2)]));
				if((!isset($cti_args->args["-p1"]) && !isset($cti_args->args["-p3"]) && !isset($cti_args->args["-p4"])) || isset($cti_args->args["-p2"])) {
					if (schemaExists("prod_".strtolower(substr($p2,0,strrpos($p2,'_')))) && schemaExists("prod_".$p2)) {
						changeSchemaName("prod_".strtolower(substr($p2,0,strrpos($p2,'_'))),"prod_".strtolower(substr($p2,0,strrpos($p2,'_'))).'_ori');
						changeSchemaName("prod_".strtolower($p2),"prod_".strtolower(substr($p2,0,strrpos($p2,'_'))));
					}
					extraction_environnement($p2);
					if (schemaExists("prod_".strtolower(substr($p2,0,strrpos($p2,'_'))).'_ori')) {
						changeSchemaName("prod_".strtolower(substr($p2,0,strrpos($p2,'_'))),"prod_".strtolower($p2));
						changeSchemaName("prod_".strtolower(substr($p2,0,strrpos($p2,'_'))).'_ori',"prod_".strtolower(substr($p2,0,strrpos($p2,'_'))));
					}
				}
				changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p2)]));
				if ($p3 != '') {
					changeSchemaName("eco_".strtolower($prefixes[strtolower($p3)]), "eco");

					initialisationSchemas(2, strtolower($prefixes[strtolower($p3)]));
					if((!isset($cti_args->args["-p2"]) && !isset($cti_args->args["-p1"]) && !isset($cti_args->args["-p4"])) || isset($cti_args->args["-p3"])) {
						if (schemaExists("prod_".strtolower(substr($p3,0,strrpos($p3,'_')))) && schemaExists("prod_".$p3)) {
							changeSchemaName("prod_".strtolower(substr($p3,0,strrpos($p3,'_'))),"prod_".strtolower(substr($p3,0,strrpos($p3,'_'))).'_ori');
							changeSchemaName("prod_".strtolower($p3),"prod_".strtolower(substr($p3,0,strrpos($p3,'_'))));
						}
						extraction_environnement($p3);
						if (schemaExists("prod_".strtolower(substr($p3,0,strrpos($p3,'_'))).'_ori')) {
							changeSchemaName("prod_".strtolower(substr($p3,0,strrpos($p3,'_'))),"prod_".strtolower($p3));
							changeSchemaName("prod_".strtolower(substr($p3,0,strrpos($p3,'_'))).'_ori',"prod_".strtolower(substr($p3,0,strrpos($p3,'_'))));
						}
					}
					changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p3)]));
					if ($p4 != '') {
						changeSchemaName("eco_".strtolower($prefixes[strtolower($p4)]), "eco");

						initialisationSchemas(3, strtolower($prefixes[strtolower($p4)]));
						if((!isset($cti_args->args["-p2"]) && !isset($cti_args->args["-p1"]) && !isset($cti_args->args["-p3"])) || isset($cti_args->args["-p4"])) {
							if (schemaExists("prod_".strtolower(substr($p4,0,strrpos($p4,'_')))) && schemaExists("prod_".$p4)) {
								changeSchemaName("prod_".strtolower(substr($p4,0,strrpos($p4,'_'))),"prod_".strtolower(substr($p4,0,strrpos($p4,'_'))).'_ori');
								changeSchemaName("prod_".strtolower($p4),"prod_".strtolower(substr($p4,0,strrpos($p4,'_'))));
							}
							extraction_environnement($p4);
							if (schemaExists("prod_".strtolower(substr($p4,0,strrpos($p4,'_'))).'_ori')) {
								changeSchemaName("prod_".strtolower(substr($p4,0,strrpos($p4,'_'))),"prod_".strtolower($p4));
								changeSchemaName("prod_".strtolower(substr($p4,0,strrpos($p4,'_'))).'_ori',"prod_".strtolower(substr($p4,0,strrpos($p4,'_'))));
							}
						}
						changeSchemaName("eco", "eco_".strtolower($prefixes[strtolower($p4)]));
					}
				}
				changeSchemaName("eco_ori", "eco");
			}
		}
		
		// Fusion CTI
		if (!isset($cti_args->args["--no_fusion"])) {
			if ($p2 != '') {
				changeSchemaName("eco_".strtolower($prefixes[strtolower($p1)]), "eco_src");
				fusionEnvironnement($p1, 0, '', $p1Start, $p1End);
				changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p1)]));
				changeSchemaName("eco_".strtolower($prefixes[strtolower($p2)]), "eco_src");
				fusionEnvironnement($p2, 1, $prefixes[strtolower($p2)], $p2Start, $p2End);
				changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p2)]));
				if ($p3 != '') {
					changeSchemaName("eco_".strtolower($prefixes[strtolower($p3)]), "eco_src");
					fusionEnvironnement($p3, 2, $prefixes[strtolower($p3)], $p3Start, $p3End);
					changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p3)]));
					if ($p4 != '') {
						changeSchemaName("eco_".strtolower($prefixes[strtolower($p4)]), "eco_src");
						fusionEnvironnement($p4, 3, $prefixes[strtolower($p4)], $p4Start, $p4End);
						changeSchemaName("eco_src", "eco_".strtolower($prefixes[strtolower($p4)]));
					}
				}
			}
		}
		
		$cti_sqlStatements_share->executeStatementsNode("POST");
		$cti_sqlStatements_share->executeStatementsNode("VACUUM");
	}

}

// Déconnexion BD
$iCTI_connexion->close();

// nettoyage du cache
logInfoMsg("Nettoyage cache");
cleanAllCache("iCTI_eco", TRUE);

logEndMsg();

// extraction production
function extraction_prod($PROVIDER) {
	global $cti_args;

	// Pas d'aspiration sur import depuis autre environnement
	if (strtolower($PROVIDER) == "icti_eco") {
			return;
	}

	$doNotActualizeProd = false;
	$unknownArgs = array();
	
	
	foreach ($cti_args->args as $key => $value) {
		switch ($key) {
			case "-noactualizeprod":
				$doNotActualizeProd = true;
				break;
			case "-raz":
				break;
			default:
				$unknownArgs[] = $key;
				break;
		}
	}
	if ($cti_args->args["-u"] || $cti_args->args["--prod-update"]) {
		if ($doNotActualizeProd) {
			logInfoMsg("CONTROLE REPLICATION BASE DE DONNEES PRODUCTION");
			$prod_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_check.exe");
			if (strtolower($PROVIDER) != 'winpharm' && strtolower($PROVIDER) != 'hsp') {
				$extractCmd = "$prod_exe -p $PROVIDER -m eco";
				$return = exec($extractCmd, $output_array);
				foreach ($output_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
			}
            elseif (strtolower($PROVIDER) == 'hsp') {
				$extractCmd = "$prod_exe -p EVOLUCARE_HYGIE -m eco";
				$return = exec($extractCmd, $output1_array);
				foreach ($output1_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
				$extractCmd = "$prod_exe -p SAGE100COMPTA -m eco";
				$return = exec($extractCmd, $output2_array);
				foreach ($output2_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
            }
			else {
				$extractCmd = "$prod_exe -p WINPHARM_THESAURUS -m eco";
				$return = exec($extractCmd, $output1_array);
				foreach ($output1_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
				$extractCmd = "$prod_exe -p WINPHARM_GESTION -m eco";
				$return = exec($extractCmd, $output2_array);
				foreach ($output2_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
			}
			logInfoMsg("FIN CONTROLE REPLICATION BASE DE DONNEES PRODUCTION");
		}
		else {
			logInfoMsg("REPLICATION BASE DE DONNEES PRODUCTION");
			$prod_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_put.exe");
			if (strtolower($PROVIDER) != 'winpharm' && strtolower($PROVIDER) != 'hsp') {
				$extractCmd = "$prod_exe -p $PROVIDER -m eco";
				$return = exec($extractCmd, $output_array);
				foreach ($output_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
			}
            elseif (strtolower($PROVIDER) == 'hsp') {
				$extractCmd = "$prod_exe -p EVOLUCARE_HYGIE -m eco";
				$return = exec($extractCmd, $output1_array);
				foreach ($output1_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
				$extractCmd = "$prod_exe -p SAGE100COMPTA -m eco";
				$return = exec($extractCmd, $output2_array);
				foreach ($output2_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
            }
			else {
				$extractCmd = "$prod_exe -p WINPHARM_THESAURUS -m eco";
				$return = exec($extractCmd, $output1_array);
				foreach ($output2_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
				$extractCmd = "$prod_exe -p WINPHARM_GESTION -m eco";
				$return = exec($extractCmd, $output2_array);
				foreach ($output1_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
			}
			logInfoMsg("FIN REPLICATION BASE DE DONNEES PRODUCTION");
		}
	}
	else {
		if (strtolower($PROVIDER) == 'winpharm') return checkLoadedData('WINPHARM_THESAURUS','eco') + checkLoadedData('WINPHARM_GESTION','eco');	
        elseif (strtolower($PROVIDER) == 'hsp') return checkLoadedData('EVOLUCARE_HYGIE','eco') + checkLoadedData('SAGE100COMPTA','eco');	
		elseif (strtolower($PROVIDER) != 'icti_eco') return checkLoadedData($PROVIDER,'eco');	
		else return 0;	
	}
}

// récupération historique
function extraction_environnement($PROVIDER) {
	global $cti_sqlStatements;
	global $iCTI_connexion;
    global $cti_sqlStatements_share;
	global $cti_args;
	global $ENV_ECO_ANNEEDEBUT;
	global $ENV_FINESS;
	global $prefixes;

	// Traitement du fichier XML de paramètres de connexions à la base de données du prestataire
	try {
		// Emplacement relatif du fichier
		if (strtolower($PROVIDER) === 'shs') {
			$file = "../../../settings/databases/SHS.XML";
		}
		else
			if (strtolower($PROVIDER) === 'winpharm') {
				$file = "../../../settings/databases/WINPHARM_GESTION.XML";
			}
            if (strtolower($PROVIDER) === 'hsp') {
				$file = "../../../settings/databases/EVOLUCARE_HYGIE.XML";
			}
			else {
				$file = "../../../settings/databases/" . strtoupper($PROVIDER) . ".XML";
			}
		// Chargement du fichier
		$xml = simplexml_load_string(file_get_contents($file));
		$ETAB = "";
		// Initiatlisation du tableau de paramètres
		$environmentVars = array();
		$environmentVars["ENV_ECO_ANNEEDEBUT"] = $ENV_ECO_ANNEEDEBUT;

		// Spécifique prestataire, à alimenter au besoin
		switch (strtolower($PROVIDER)) {
			case "shs" :

				// Définition du schéma des tables ECO
				$environmentVars['ECOLIB'] = strtoupper(trim($xml['ecolib']));
				if ($environmentVars['ECOLIB'] === '') {
					$environmentVars['ECOLIB'] = strtoupper(trim($xml['gefilib']));
				}
				if ($environmentVars['ECOLIB'] === '') {
					$environmentVars['ECOLIB'] = str_replace("PMSI","GEFI",strtoupper(trim($xml['pmsilib'])));
				}
				if ($environmentVars['ECOLIB'] === '') {
					logErrorMsg("la bibliothèque GEFI n'est pas précisée");
					logEndMsg();
					exit(0);
				}

				// Définition du schéma des tables COMPTA
				$environmentVars['COMPTALIB'] = strtoupper(trim($xml['comptalib']));
				if ($environmentVars['COMPTALIB'] === '') {
					$environmentVars['COMPTALIB'] = strtoupper(trim($xml['admlib']));
				}
				if ($environmentVars['COMPTALIB'] === '') {
					logErrorMsg("la bibliothèque COMPTA n'est pas précisée");
					logEndMsg();
					exit(0);
				}

				break;

			case "cegi" :
			case "pharma" :
			case "qualiac" :
			case "winpharm" :
			case "web100t" :
			case "icti_eco" :

				$ETAB = $xml['idEtab_eco'];
				break;

			case "sigems" :
				// TODO
				break;

			default :
				break;
		}
	} catch (Exception $e) {
		logErrorMsg("Impossible de charger les paramètres du prestataire " . $PROVIDER);
		logEndMsg();
		exit(0);
	}

	// Initialisation du requêteur
	try {
		$sqlOptions = array();
		
		foreach ($cti_args->args as $key => $value) {
			$sqlOptions[] = $key;
		}
		
		
		
		$environmentVars["FINESS"] = $ENV_FINESS;
		$environmentVars["ETAB"] = $ETAB;
		$environmentVars["ETAB_ID"] = $ETAB;
		if (strtolower($PROVIDER) === "icti_eco") {
			$dbSettings = new EnvironmentDatabaseSettings();
			try {
				$dbSettings->readSettings($file);
				$environmentVars["DBHOST"] = $dbSettings->getHost();
				$environmentVars["DBPORT"] = $dbSettings->getPort();
				$environmentVars["DBNAME"] = $dbSettings->getName();
				$environmentVars["DBUSER"] = $dbSettings->getUsername();
				$environmentVars["DBPASSWORD"] = $dbSettings->getPassword();
			} catch (Exception $e) {
				logErrorMsg($e->getMessage());
				logEndMsg();
				exit();
			}
		}
		
		$cti_sqlStatements = new CTI_SqlStatements_class("iCTI_import_eco_" . (strpos($PROVIDER,'_') != FALSE && array_key_exists(substr($PROVIDER,0,strpos($PROVIDER,'_')),$prefixes) ? substr($PROVIDER,0,strpos($PROVIDER,'_')) : $PROVIDER) . ".XML", $iCTI_connexion, $environmentVars, $sqlOptions);
	} catch (Exception $e) {
		logErrorMsg("Impossible de charger les requêtes SQL.");
		logEndMsg();
		exit(0);
	}
	
	logInfoMsg("RECUPERATION DE LA PRODUCTION $PROVIDER");

	// Raz automatique le samedi
	if (date("w") == 6) {
		$cti_args->args["-raz"] = "ONLYKEY";
	}

	if ($cti_args->args["-raz"]) {
		$cti_sqlStatements_share->executeStatementsNode("RAZ");
		$cti_sqlStatements_share->executeStatementsNode("VACUUM");
	}
    
	$cti_sqlStatements_share->executeStatementsNode("INIT");
	$cti_sqlStatements->executeStatementsNode("INIT");
	$cti_sqlStatements->executeStatementsNode("PROD");
	$cti_sqlStatements->executeStatementsNode("POST");

	logInfoMsg("FIN RECUPERATION DE LA PRODUCTION $PROVIDER");
}


function init() {
	global $iCTI_connexion;
	global $iCTI_cache;
	global $cti_args;
	global $ENV_TYPEETS;
	global $ENV_FINESS;
	global $p1;
	global $p2;
    global $p3;
	global $p4;
	global $cti_sqlStatements;
    global $cti_sqlStatements_share;
	global $ENV_ECO_ANNEEDEBUT;
	global $p1Start;
	global $p2Start;
    global $p3Start;
	global $p4Start;
	global $p1End;
	global $p2End;
    global $p3End;
	global $p4End;

	//Initialisation de l'année de début à année en cours -3
	$ENV_ECO_ANNEEDEBUT = date("Y")-3;
	$p1Start = '1900-01-01';
	$p2Start = '1900-01-01';
    $p3Start = '1900-01-01';
	$p4Start = '1900-01-01';
	$p1End = '2099-12-31';
	$p2End = '2099-12-31';
    $p3End = '2099-12-31';
	$p4End = '2099-12-31';
	
	// Traitement du fichier de paramètres généraux de l'application
	try {
		$file = "../../../settings/settings.XML";
		$settings_xml = simplexml_load_file($file);

		foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
			foreach ($environmentNode->PROPERTY as $propertyNode) {
				if ($propertyNode['name'] == 'TYPEETS') {
					$ENV_TYPEETS = trim($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'ECOPROVIDER') {
					$p1 = trim($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'ECOPROVIDER2') {
					$p2 = trim($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'ECOPROVIDER3') {
					$p3 = trim($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'ECOPROVIDER4') {
					$p4 = trim($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'FINESS') {
					$ENV_FINESS = trim($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'OPTECO_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 = intval(substr($propertyNode['value'],1));
						if ($nbAnnee === 0 && intval(date("m"))<7) {
							$nbAnnee++;
						}
						$ENV_ECO_ANNEEDEBUT = date("Y")-$nbAnnee;
					} else if ($propertyNode['value']!="" && strlen($propertyNode['value']) === 4) {
						// si années écrit en dur
						$ENV_ECO_ANNEEDEBUT = $propertyNode['value'];
					}
				}
				if ($propertyNode['name'] == 'OPTECO_DATEBASCULE') {
					$p1Start = $propertyNode['value'];
					$p2End = $propertyNode['value'];
				}
                if ($propertyNode['name'] == 'OPTECO_DATEBASCULE2') {
					$p2Start = $propertyNode['value'];
					$p3End = $propertyNode['value'];
				}
				if ($propertyNode['name'] == 'OPTECO_DATEBASCULE3') {
					$p3Start = $propertyNode['value'];
					$p4End = $propertyNode['value'];
				}
				// comportement destiné à Europe (bascule de 4 vers 1,2,3)
				if ($propertyNode['name'] == 'OPTECO_DATEBASCULE_DEBUT') {
					$p1Start = $propertyNode['value'];
				}
				if ($propertyNode['name'] == 'OPTECO_DATEBASCULE2_DEBUT') {
					$p2Start = $propertyNode['value'];
				}
				if ($propertyNode['name'] == 'OPTECO_DATEBASCULE3_DEBUT') {
					$p3Start = $propertyNode['value'];
				}
				if ($propertyNode['name'] == 'OPTECO_DATEBASCULE4_FIN') {
					$p3Start = $propertyNode['value'];
				}
			}
		}

		logInfoMsg("DEPUIS " . $ENV_ECO_ANNEEDEBUT);

		if (strlen($p1) == 0) {
			logErrorMsg("Solution ECO non définie.");
			logEndMsg();
			exit(0);
		}
		// si pas de fusion 
		if ($p1Start == '1900-01-01') {
			$p1Start = $ENV_ECO_ANNEEDEBUT.'-01-01';
		}
		else {
			$p2Start = $ENV_ECO_ANNEEDEBUT.'-01-01';			
            $p3Start = $ENV_ECO_ANNEEDEBUT.'-01-01';			
		}
	} catch (Exception $e) {
		logErrorMsg("Impossible de charger les paramètres i-CTI.");
		logEndMsg();
		exit(0);
	}
}

function run_expert_controls() {

	logInfoMsg("CONTROLES EXPERT ACTVITE");
	$exp_manager = new ControleExpertManager();
	if ($exp_manager->run_controls()) {
		$exp_message = $exp_manager->msg;
	}
	else {
		$exp_message = $exp_manager->error_msg;
	}
	logInfoMsg($exp_message);

}

?>
