<?php
$MODULE="rh";
$TITLE="Récupération RH";
$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/Log.functions.php");
require_once("../../../modules/base/php/lib/cti/Batch/iCTI_batch_common.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");
require_once("../../../modules/base/php/lib/cti/Database/Database2Factory.class.php");

global $ENDSTATUS;
global $iCTI_connexion;
global $cti_args;
global $RHPROVIDER;
global $RHPROVIDER2;
global $RHPROVIDER_PREFIX;
global $RHPROVIDER2_PREFIX;
global $ENV_TYPEETS;
global $nbE;


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

	extraction_prod($RHPROVIDER);
	
	extraction_environnement($RHPROVIDER, $RHPROVIDER_PREFIX, 0);

	
	
		
}

iCTI_disconnect();

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

logEndMsg();

function extraction_prod($RHPROVIDER_check) {
	global $cti_args;

	echo "\r\n";
	
	// Pas d'aspiration sur import depuis autre environnement
	if ($RHPROVIDER_check == "ICTI_RH") {
			return;
	}
	
	
	if ($cti_args->args["-noactualizeprod"]) {
		logInfoMsg("CONTRÔLE RÉPLICATION BASE DE DONNÉES PRODUCTION $RHPROVIDER_check");
		$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_check.exe");
		$extractCmd = "$prodhm_exe -p $RHPROVIDER_check -m rh";
		$return = exec($extractCmd, $output_array);
		foreach ($output_array as $output_line) {
			if (trim($output_line) != "") {
				echo "\r\n$output_line";
			}
		}
		// Sur QUADRARH, verifier egalement exercice précédent
		if ($RHPROVIDER_check == "QUADRARH") {
			$RHPROVIDER_checkP = $RHPROVIDER_check . 'P';
			logInfoMsg("Exercice précédent");
			$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_check.exe");
			$extractCmd = "$prodhm_exe -p $RHPROVIDER_checkP -m rh";
			unset($output_array);
			$return = exec($extractCmd, $output_array);
			foreach ($output_array as $output_line) {
				if (trim($output_line) != "") {
					echo "\r\n$output_line";
				}
			}
		}
		logInfoMsg("FIN CONTRÔLE RÉPLICATION BASE DE DONNÉES PRODUCTION $RHPROVIDER_check");
	}
	else {
		logInfoMsg("RÉPLICATION BASE DE DONNÉES PRODUCTION $RHPROVIDER_check");
		$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_put.exe");
		$extractCmd = "$prodhm_exe -p $RHPROVIDER_check -m rh";
		$return = exec($extractCmd, $output_array);
		foreach ($output_array as $output_line) {
			if (trim($output_line) != "") {
				echo "\r\n$output_line";
			}
		}
		// Sur QUADRARH, récupérer egalement exercice précédent
		if ($RHPROVIDER_check == "QUADRARH") {
			$RHPROVIDER_checkP = $RHPROVIDER_check . 'P';
			logInfoMsg("Exercice précédent");
			$prodhm_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_put.exe");
			$extractCmd = "$prodhm_exe -p $RHPROVIDER_checkP -m rh";
			unset($output_array);
			$return = exec($extractCmd, $output_array);
			foreach ($output_array as $output_line) {
				if (trim($output_line) != "") {
					echo "\r\n$output_line";
				}
			}
		}
		logInfoMsg("FIN RÉPLICATION BASE DE DONNÉES PRODUCTION $RHPROVIDER_check");
	}


}



// récupération historique
function extraction_environnement($RHPROVIDER, $RHPROVIDER_PREFIX, $RHPROVIDER_OID) {

	global $iCTI_connexion;
	global $ENV_TYPEETS;

	global $cti_args;

	logInfoMsg("RÉCUPERATION DE LA PRODUCTION $RHPROVIDER");
	
	// Paramètres shs
	$file = "../../../settings/databases/$RHPROVIDER.XML";
	$xml = simplexml_load_string(file_get_contents($file));

	$DB_pmsischema = trim($xml['pmsilib']);
	$DB_activiteschema = trim($xml['admlib']);
	$DB_rhschema = trim($xml['rhlib']);
	
	$ETAB = trim($xml['idEtab_rh']);
	
	
	// Chargement requetes SQL
	$environmentVars=array();
	
	
	$environmentVars["PMSISCHEMA"] = $DB_pmsischema;
	$environmentVars["ACTIVITESCHEMA"] = $DB_activiteschema;
	$environmentVars["RHSCHEMA"] = $DB_rhschema;
	
	$environmentVars["ETAB"] = $ETAB;
	$environmentVars["ENV_TYPEETS"] = $ENV_TYPEETS;
	
	if (strtolower($RHPROVIDER) === 'icti_rh') {
        $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_rh_SHARE.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
	
	$cti_sqlStatements_provider = new CTI_SqlStatements_class("iCTI_import_rh_$RHPROVIDER.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
	
	
	
	$cti_sqlStatements_provider->executeStatementsNode("PARAM");

	$cti_sqlStatements_provider->executeStatementsNode("PAIE");
	
	$cti_sqlStatements_provider->executeStatementsNode("POST");
	
	$cti_sqlStatements_provider->executeStatementsNode("VACUUM");
	

	
	logInfoMsg("FIN RÉCUPERATION DE LA PRODUCTION $RHPROVIDER");

}

function iCTI_connect() {

global $iCTI_connexion;
global $ENV_TYPEETS;
global $RHPROVIDER;
global $RHPROVIDER2;
global $RHPROVIDER_PREFIX;
global $RHPROVIDER2_PREFIX;

	$iCTI_connexion = FALSE;

	$file = "../../../settings/settings.XML";
	$settings_xml = simplexml_load_string(file_get_contents($file));
	
	$wRHPROVIDER = "";
	$RHPROVIDER_PREFIX = "";
	$wRHPROVIDER_PREFIX = "";
	$wRHPROVIDER2 = "";
	$RHPROVIDER2_PREFIX = "";
	$wRHPROVIDER2_PREFIX = "";

	foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if (strtoupper($propertyNode['name']) === 'TYPEETS') {
				$ENV_TYPEETS = trim($propertyNode['value']);
			}
			if (strtoupper($propertyNode['name']) === 'RHPROVIDER') {
				$wRHPROVIDER = trim($propertyNode['value']);
			}
			if (strtoupper($propertyNode['name']) === 'RHPROVIDER2') {
				$wRHPROVIDER2 = trim($propertyNode['value']);
			}
			if (strtoupper($propertyNode['name']) === 'RHPROVIDER_PREFIX') {
				$wRHPROVIDER_PREFIX = str_replace('_', '', trim($propertyNode['value']));
			}
			if (strtoupper($propertyNode['name']) === 'RHPROVIDER2_PREFIX') {
				$wRHPROVIDER2_PREFIX = str_replace('_', '',trim($propertyNode['value']));
			}
		}
	}

    switch (strtolower($wRHPROVIDER)) {
        case 'shs' :
        case 'sagex3' :
        case 'sage100rh' :
        case 'sagei7rh' :
        case 'adonix' :
        case 'quadrarh' :
        case 'qsp' :
        case 'sigems' :
        case 'cegi' :
        case 'icti_rh' :
            $RHPROVIDER = strtoupper($wRHPROVIDER);
            break;

        default:
            $RHPROVIDER = '';
    }

	if ($wRHPROVIDER2 !== '') {
        switch (strtolower($wRHPROVIDER2)) {
            case 'shs' :
            case 'sagex3' :
            case 'sage100rh' :
            case 'sagei7rh' :
            case 'adonix' :
            case 'quadrarh' :
            case 'qsp' :
            case 'sigems' :
            case 'cegi' :
                $RHPROVIDER2 = strtoupper($wRHPROVIDER2);
                break;

            default:
                $RHPROVIDER2 = '';
        }

	}
	
	if ($RHPROVIDER === '') {
		logErrorMsg("Prestataire $wRHPROVIDER non traité actuellement");
		return false;
	}
	
	if ($RHPROVIDER2 === '') {
		$RHPROVIDER_PREFIX = '';
		$RHPROVIDER2_PREFIX = '';
	}
	else {
		$RHPROVIDER_PREFIX = $wRHPROVIDER_PREFIX;
		$RHPROVIDER2_PREFIX = $wRHPROVIDER2_PREFIX;
		if ($RHPROVIDER_PREFIX === '') {
			$RHPROVIDER_PREFIX = substr($RHPROVIDER,0,2);
		}
		$RHPROVIDER_PREFIX = '_' . $RHPROVIDER_PREFIX;
		if ($RHPROVIDER2_PREFIX === '') {
			$RHPROVIDER2_PREFIX = substr($RHPROVIDER2,0,2);
		}
		$RHPROVIDER2_PREFIX = '_' . $RHPROVIDER2_PREFIX;
	}

    // 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;
    }

    return true;
}

function iCTI_disconnect() {

	global $iCTI_connexion;

    $iCTI_connexion->close();
}
