<?php

// IMPORT DES BIBLIOTHEQUES
require_once("../../base/php/startSession.php");
require_once("../../base/php/classDatabase.php");
require_once("../../base/php/Functions.php" );
require_once("../../base/php/WebAppLog.php");
require_once("../../outils/php/httpService_cacheManager_cleanCache.php");

// DECLARATION DES VARIABLES GLOBALES
global $returnTexte;
global $returnCode;

// DECLARATION DES CONSTANTES
define("SAVE", "save");
define("UPDATE", "update");
define("COPY", "copy");
define("DELETE", "delete");
define("UPLOAD", "upload");

// DECLARATION DES VARIABLES
$compress64 = true;
$database = new Database("iCTI");

//
$returnTexte = "";
$returnCode = "OK";

// RECUPERATION DES PARAMETRES HTTP
$softCode = getPOST("softCode");
$tableName = getPOST("tableName");
$action = getPOST("action");
$recordXML = getPOST("recordNode");


$recordNode = @simplexml_load_string($recordXML);



$httpString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
if ($tableName != "" && $action != "" && $recordNode !== FALSE) {
	$httpString .= setRecords($database, $tableName, $action, $recordNode);
}
else {
	$httpString .= "\n<HTTP_SERVICE returnCode=\"KO\" returnTexte=\"Table:$tableName Action:$action incorrecte\" >";
	$httpString .= "\n</HTTP_SERVICE>";
}

//if ($compress64) {
	//$httpString = compress64($httpString);
//}
//echo "<CTICONTENT>$httpString</CTICONTENT>";

echo "$httpString";



/**
 *
 * @param Database $db
 * @param string $tableName
 * @param string $action
 * @param object $recordNode
 */
function setRecords($db, $tableName, $action, $recordNode) {
	if ($tableName == "encours") {
		return setRecords_encours($db, $tableName, $action, $recordNode);
	}
}

// DEFINITIONS DE FONCTION

/**
 *
 * @param Database $db
 * @param string $tableName
 * @param string $action
 * @param object $recordNode
 */
function setRecords_encours($db, $tableName, $action, $recordNode) {

	
	$returnCode = "OK";
	$returnTexte = "";

    /** Informations d'autentification communes */
    $dbuser = $db->user;
    $dbpassword = $db->password;

    $oid = floatval($recordNode["oid"]);
	$code = utf8_decode($recordNode["code"]);
	$texte = utf8_decode($recordNode["texte"]);
	$dateencours = floatval($recordNode["dateencours"]);
	
	
	
	$updatedOids = "";

	switch ($action) {
		case SAVE :
			$dateencours = toSQL($dateencours);

			// creation ou mise à  jour de la liste
			if ($oid != -1) {
				// Oids Impactés
				$sqlcmd = "
					SELECT base.cti_group_concat(oid) AS updatedOids 
					FROM base.t_finess WHERE oid = $oid or $oid = 0";
				$result = $db->exec($sqlcmd);
				if ($result != false) {
					$record = $db->nextRecordAssoc();
					if ($record != FALSE) {
						$updatedOids = toHTML(trim($record['updatedoids'])) . ",$oid";
					}
				}
			
				// Mise à jour
				$sqlcmd = "
					DROP TABLE IF EXISTS w_database;
					CREATE TEMP TABLE w_database AS
					SELECT 
						t_finess.oid,
						replace(t_finess_database.dbname,'icti_','') AS code,
						t_finess.texte,
						dbname,
						dbhost,
						dbport,
						'0'::text AS disabled
					FROM base.t_finess
					JOIN base.t_finess_database ON finess_id = t_finess.oid
					JOIN dblink('host=' || dbhost || ' dbname=postgres port=' || dbport || ' user=$dbuser password=$dbpassword', 
						'SELECT ''1''::text AS ok 
						FROM pg_database
						WHERE datname = ''' || dbname || ''' ') 
						AS dblink(ok text) ON ok='1'
					WHERE oid = $oid OR $oid = 0
					ORDER BY 4
					;

					SELECT 
						dblink_exec('host=' || dbhost || ' dbname=' || dbname || ' port=' || dbport || ' user=$dbuser password=$dbpassword', 
						'UPDATE activite.t_divers
						SET valeur = ''$dateencours''
						WHERE code = ''DATEENCOURS''
						') 
					FROM w_database
					JOIN dblink('host=' || dbhost || ' dbname=' || dbname || ' port=' || dbport || ' user=$dbuser password=$dbpassword', 
						'SELECT ''1''::text AS ok 
						FROM pg_tables 
						WHERE schemaname = ''activite'' AND tablename= ''t_divers''') 
						AS dblink(ok text) ON ok='1'
						";


				$result = $db->exec($sqlcmd);
				if ($db->lastResult) {
					
				}
				else {
					$updatedOids = "";
					$returnCode = "KO";
					$returnTexte = "Erreur SQL : $db->lastError";
				}
				
				
			}
			break;
		case UPDATE :
			// nothing to do yet
			break;
		case COPY :
			// nothing to do yet
			break;
		case DELETE :
			// nothing to do yet
			break;
		case UPLOAD :
			// nothing to do yet
			break;
		default:
			// nothing to do yet
			break;
	}
	
	

	$httpString = "<HTTP_SERVICE returnCode=\"$returnCode\" returnTexte=\"$returnTexte\" updatedOids=\"$updatedOids\" >";
	$httpString .= "\n</HTTP_SERVICE>";
	
	return $httpString;
}

/**
 *
 * @param Database $db
 * @param string eco
 */
function erase_cache($db) {

	// Effacer cache ancienne version
	if ($db->cticache == "true") {
		$sqlcmd = "SELECT cti_cache_erase as result from cache.cti_cache_erase('iCTI_eco')";
		$result = $db->exec($sqlcmd);
	}
	
	// Effacer cache nouvelle version
	cleanAllCache("iCTI_eco");
}

?>