<?php
$MODULE="compta";
$TITLE="Récupération comptabilité";
$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
 */

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/classSimpleXML.php");
require_once("../../../modules/outils/php/httpService_cacheManager_cleanCache.php");
require_once("../../../modules/base/php/lib/cti/EnvironmentSettings/EnvironmentDatabaseSettings.php");

global $ENDSTATUS;
global $iCTI_connexion;
global $cti_args;
global $COMPTAPROVIDER;
global $COMPTAPROVIDER2;
global $COMPTAPROVIDER_PREFIX;
global $COMPTAPROVIDER2_PREFIX;
global $ENV_TYPEETS;
global $nbE;
global $ENV_COMPTA_ANNEEDEBUT;


logStartMsg();

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

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');
	}

	$exitCode = extraction_prod($COMPTAPROVIDER);
	if($exitCode == 0 || $cti_args->args["-f"]) {
		extraction_environnement($COMPTAPROVIDER, $COMPTAPROVIDER_PREFIX, 0);
	}

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

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

logEndMsg();


function extraction_prod($COMPTAPROVIDER_check) {
	global $cti_args;

	// Pas d'aspiration sur import depuis autre environnement
    if ($COMPTAPROVIDER_check == "ICTI_COMPTA") {
            return;
    }
	if ($cti_args->args["-u"] || $cti_args->args["--prod-update"]) {
		if ($cti_args->args["-noactualizeprod"]) {
			logInfoMsg("CONTROLE REPLICATION BASE DE DONNEES PRODUCTION $COMPTAPROVIDER_check");
			$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_check.exe");
			$extractCmd = "$prodhm_exe -p $COMPTAPROVIDER_check -m compta";
			$return = exec($extractCmd, $output_array);
			foreach ($output_array as $output_line) {
				if (trim($output_line) != "") {
					echo PHP_EOL . $output_line;
				}
			}
			// Sur QUADRACOMPTA, verifier egalement exercice précédent
			if ($COMPTAPROVIDER_check == "QUADRACOMPTA") {
				$COMPTAPROVIDER_checkP = $COMPTAPROVIDER_check . 'P';
				logInfoMsg("Exercice précédent");
				$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_check.exe");
				$extractCmd = "$prodhm_exe -p $COMPTAPROVIDER_checkP -m compta";
				unset($output_array);
				$return = exec($extractCmd, $output_array);
				foreach ($output_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
			}
			logInfoMsg("FIN CONTROLE REPLICATION BASE DE DONNEES PRODUCTION $COMPTAPROVIDER_check");
		}
		else {
			logInfoMsg("REPLICATION BASE DE DONNEES PRODUCTION $COMPTAPROVIDER_check");
			$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_put.exe");
			$extractCmd = "$prodhm_exe -p $COMPTAPROVIDER_check -m compta";
			$return = exec($extractCmd, $output_array);
			foreach ($output_array as $output_line) {
				if (trim($output_line) != "") {
					echo PHP_EOL . $output_line;
				}
			}
			// Sur QUADRACOMPTA, récupérer egalement exercice précédent
			if ($COMPTAPROVIDER_check == "QUADRACOMPTA") {
				$COMPTAPROVIDER_checkP = $COMPTAPROVIDER_check . 'P';
				logInfoMsg("Exercice précédent");
				$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_put.exe");
				$extractCmd = "$prodhm_exe -p $COMPTAPROVIDER_checkP -m compta";
				unset($output_array);
				$return = exec($extractCmd, $output_array);
				foreach ($output_array as $output_line) {
					if (trim($output_line) != "") {
						echo PHP_EOL . $output_line;
					}
				}
			}
			logInfoMsg("FIN REPLICATION BASE DE DONNEES PRODUCTION $COMPTAPROVIDER_check");
			return $return;
		}
	}
	else {
		if ($COMPTAPROVIDER_check != "QUADRACOMPTA") return checkLoadedData($COMPTAPROVIDER_check,'compta');
		else return checkLoadedData($COMPTAPROVIDER_check,'compta') + checkLoadedData($COMPTAPROVIDER_check.'P','compta');
	}
}

// récupération historique
function extraction_environnement($COMPTAPROVIDER, $COMPTAPROVIDER_PREFIX, $COMPTAPROVIDER_OID) {

	global $iCTI_connexion;
	global $ENV_TYPEETS;
	global $ENV_COMPTA_ANNEEDEBUT;

	global $cti_args;

	logInfoMsg("RECUPERATION DE LA PRODUCTION $COMPTAPROVIDER");
	
	// Paramètres shs
	$file = "../../../settings/databases/$COMPTAPROVIDER.XML";
	$xml = simplexml_load_string(file_get_contents($file));

	$DB_pmsischema = trim($xml['pmsilib']);
	$DB_activiteschema = trim($xml['admlib']);
	$DB_comptaschema = trim($xml['comptalib']);
	
	$SAGEX3_idSites = $xml['idSites'];
	$SAGEX3_idSites = str_replace("'"," ",$SAGEX3_idSites);
	$QSP_idEtablissement = $xml['idEtablissement'];
	$ETAB = trim($xml['idEtab_compta']);
	$SITES = trim($xml['idSites_compta']);

	// Chargement requetes SQL
	$environmentVars=array();
	
	$environmentVars["PMSISCHEMA"] = $DB_pmsischema;
	$environmentVars["ACTIVITESCHEMA"] = $DB_activiteschema;
	$environmentVars["COMPTASCHEMA"] = $DB_comptaschema;
	
	$environmentVars["SAGEX3_SITES"] = $SAGEX3_idSites;
	$environmentVars["QSP_ETAB"] = $QSP_idEtablissement;
	$environmentVars["ETAB"] = $ETAB;
	$environmentVars["SITES"] = $SITES;
	$environmentVars["ENV_TYPEETS"] = $ENV_TYPEETS;
	$environmentVars["ENV_COMPTA_ANNEEDEBUT"] = $ENV_COMPTA_ANNEEDEBUT;
	
	if (strtolower($COMPTAPROVIDER) === 'icti_compta') {
        $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();
        }
	}
	
	$sqlOptions=array();
	$cti_sqlStatements_share = new CTI_SqlStatements_class("iCTI_import_compta_SHARE.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
	$cti_sqlStatements_provider = new CTI_SqlStatements_class("iCTI_import_compta_$COMPTAPROVIDER.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
	
	// Raz forcé le samedi
	if (date("w") == 6) {
		$cti_args->args["-raz"] = "ONLYKEY";
	}
	
	
	if ($cti_args->args["-raz"]) {
		//$cti_sqlStatements_share->executeStatementsNode("RAZ");
	}
	
	$cti_sqlStatements_provider->executeStatementsNode("PARAM");
	
	$cti_sqlStatements_provider->executeStatementsNode("INIT");

	$cti_sqlStatements_provider->executeStatementsNode("ECRITURES");
	
	$cti_sqlStatements_provider->executeStatementsNode("CHIFFRIER");
	
	$cti_sqlStatements_provider->executeStatementsNode("POST");
	
	$cti_sqlStatements_share->environmentVars = $cti_sqlStatements_provider->environmentVars;
	
	$cti_sqlStatements_share->executeStatementsNode("POST");

	$cti_sqlStatements_share->executeStatementsNode("VACUUM");

	logInfoMsg("FIN RECUPERATION DE LA PRODUCTION $COMPTAPROVIDER");

}

function iCTI_connect() {


global $iCTI_connexion;
global $iCTI_cache;
global $ENV_TYPEETS;
global $COMPTAPROVIDER;
global $COMPTAPROVIDER2;
global $COMPTAPROVIDER_PREFIX;
global $COMPTAPROVIDER2_PREFIX;
global $ENV_COMPTA_ANNEEDEBUT;

	$iCTI_connexion = FALSE;

	$file = "../../../settings/settings.XML";
	$settings_xml = simplexml_load_file($file);
	
	$COMPTAPROVIDER = "";
	$wCOMPTAPROVIDER = "";
	$COMPTAPROVIDER_PREFIX = "";
	$wCOMPTAPROVIDER_PREFIX = "";
	$COMPTAPROVIDER2 = "";
	$wCOMPTAPROVIDER2 = "";
	$COMPTAPROVIDER2_PREFIX = "";
	$wCOMPTAPROVIDER2_PREFIX = "";
	// Par défaut Année en cours - 5
	$ENV_COMPTA_ANNEEDEBUT = date("Y") - 5;

	foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if ($propertyNode['name'] == 'TYPEETS') {
				$ENV_TYPEETS = trim($propertyNode['value']);
			}
			if ($propertyNode['name'] == 'COMPTAPROVIDER') {
				$wCOMPTAPROVIDER = strtoupper(trim($propertyNode['value']));
			}
			if ($propertyNode['name'] == 'COMPTAPROVIDER2') {
				$wCOMPTAPROVIDER2 = strtoupper(trim($propertyNode['value']));
			}
			if ($propertyNode['name'] == 'COMPTAPROVIDER_PREFIX') {
				$wCOMPTAPROVIDER_PREFIX = strtoupper(trim($propertyNode['value']));
			}
			if ($propertyNode['name'] == 'COMPTAPROVIDER2_PREFIX') {
				$wCOMPTAPROVIDER2_PREFIX = strtoupper(trim($propertyNode['value']));
			}
			if ($propertyNode['name'] == 'OPTCOMPTA_ANNEEDEBUT') {
				if (substr($propertyNode['value'], 0, 1) === 'A') {
					$nbAnnee = substr($propertyNode['value'], 1);
					$ENV_COMPTA_ANNEEDEBUT = date("Y") - intval($nbAnnee);
				} else if ($propertyNode['value'] != "" && strlen($propertyNode['value']) === 4) {
					$ENV_COMPTA_ANNEEDEBUT = $propertyNode['value'];
				}
			}
		}
	}

	$listPrestaCompta = array(
		'SHS',
		'SAGEX3',
		'SAGE100COMPTA',
		'SAGEI7COMPTA',
		'ADONIX',
		'QUADRACOMPTA',
		'QSP',
		'SIGEMS',
		'CEGI',
		'ACROPOLE',
		'CEGID',
		'ICTI_COMPTA',
		'TALENTIA_FINANCE',
		'TALENTIA_FINANCE_CSV',
		'ACD',
		'DIVALTO'
	);

	$listPrestaCompta =  array_map('strtoupper', $listPrestaCompta);

	if (in_array($wCOMPTAPROVIDER, $listPrestaCompta)){
		$COMPTAPROVIDER = $wCOMPTAPROVIDER;
	}

	if ($wCOMPTAPROVIDER2 != "") {
		if (in_array($wCOMPTAPROVIDER2, $listPrestaCompta)) {
			$COMPTAPROVIDER2 = $wCOMPTAPROVIDER2;
		}
	}
	
	if ($COMPTAPROVIDER == "") {
		logErrorMsg("Prestataire $wCOMPTAPROVIDER non traité actuellement");
		return FALSE;
	}
	
	if ($COMPTAPROVIDER2 == "") {
		$COMPTAPROVIDER_PREFIX = "";
		$COMPTAPROVIDER2_PREFIX = "";
	}
	else {
		$COMPTAPROVIDER_PREFIX = $wCOMPTAPROVIDER_PREFIX;
		$COMPTAPROVIDER2_PREFIX = $wCOMPTAPROVIDER2_PREFIX;
		if ($COMPTAPROVIDER_PREFIX == "") {
			$COMPTAPROVIDER_PREFIX = substr($COMPTAPROVIDER,0,2);
		}
		$COMPTAPROVIDER_PREFIX = "_" . $COMPTAPROVIDER_PREFIX;
		if ($COMPTAPROVIDER2_PREFIX == "") {
			$COMPTAPROVIDER2_PREFIX = substr($COMPTAPROVIDER2,0,2);
		}
		$COMPTAPROVIDER2_PREFIX = "_" . $COMPTAPROVIDER2_PREFIX;
	}

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

	
	if (! $ret) {
		logErrorMsg("La connexion PostgreSQL iCTI a échoué");
		return FALSE;
	}
	
	return $ret;

}
    
?>