<?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");
define("EXEC", "exec");

// 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");
$importFile = getPOST("importFile");

$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";

// DEFINITIONS DE FONCTION

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

	$returnCode = "OK";
	$returnTexte = "";
	
	
	$oid = floatval($recordNode["oid"]);
	$code = utf8_decode($recordNode["code"]);
	$texte = utf8_decode($recordNode["texte"]);
	$texte_court = utf8_decode($recordNode["texte_court"]);
	$code_original = utf8_decode($recordNode["code_original"]);
	
	$rfoids = utf8_decode($recordNode["rfoids"]);
	
	// Champs spécifiques t_articles
	$gere_en_stock = utf8_decode($recordNode["gere_en_stock"]);
	$cacic_id = floatval($recordNode["cacic_id"]);
	
	// Champs spécifiques t_fournisseurs
	$rfcti = floatval($recordNode["rfcti"]);
	$fusionner_vers_fournisseur_id = floatval($recordNode["fusionner_vers_fournisseur_id"]);

	
	// Champs spécifiques t_reference
	$import_data = toSQL(utf8_decode($recordNode["import_data"]));
	
	 //Champs spécifiques à t_type_articles
	$defaut_selon = utf8_decode($recordNode["defaut_selon"]);
    $defaut_selon_codes = utf8_decode($recordNode["defaut_selon_codes"]);
    
    //Champs spécifiques à t_type_mouvemetns
	$particularite_inverser_signe = utf8_decode($recordNode["particularite_inverser_signe"]);
    $sens_force = utf8_decode($recordNode["sens_force"]);
	
	//Champs spécifiques à t_divers
	$valeur = utf8_decode($recordNode["valeur"]);
	$description = utf8_decode($recordNode["complement"]);
	
	// Champts spécifiques aux règles type article cti
	$priorite = floatval($recordNode["priorite"]);
	if ($priorite == 0) {
		$priorite = 5000;
	}
	$type_article_cti_id = floatval($recordNode["type_article_cti_id"]);
	$liste_type_article = toSQL(utf8_decode($recordNode["liste_type_article"]));
	$liste_compte = toSQL(utf8_decode($recordNode["liste_compte"]));
	$liste_famille = toSQL(utf8_decode($recordNode["liste_famille"]));
	$liste_sous_famille = toSQL(utf8_decode($recordNode["liste_sous_famille"]));
	$liste_categorie = toSQL(utf8_decode($recordNode["liste_categorie"]));
	$liste_sous_categorie = toSQL(utf8_decode($recordNode["liste_sous_categorie"]));
	$liste_article = toSQL(utf8_decode($recordNode["liste_article"]));
	
	$updatedOids = "";

	switch ($action) {
		case SAVE :
			$code = toSQL($code);
			$texte = toSQL($texte);
			$texte_court = toSQL($texte_court);
			$code_original = toSQL($code_original);

			// creation ou mise à  jour de la liste
			if ($oid != -1) {
				// Oids Impactés
				if($table_name != 't_divers') {
					$sqlcmd = "SELECT base.cti_group_concat(oid) AS updatedOids ";
					$sqlcmd .= "FROM (";
					$sqlcmd .= "SELECT oid AS oid FROM eco.$tableName WHERE oid = $oid ";
					if ($tableName == "t_article_reference_cti") {
						$sqlcmd .= "UNION ";
						$sqlcmd .= "SELECT article_reference_cti_id AS oid FROM eco.t_articles WHERE oid::text = ANY (string_to_array('$rfoids',',')) ";
					}
					if ($tableName == "t_fournisseur_reference_cti") {
						$sqlcmd .= "UNION ";
						$sqlcmd .= "SELECT fournisseur_reference_cti_id AS oid FROM eco.t_fournisseurs WHERE oid::text = ANY (string_to_array('$rfoids',',')) ";
					}
					
					$sqlcmd .= ") subview";
					$result = $db->exec($sqlcmd);
					if ($result != false) {
						$record = $db->nextRecordAssoc();
						if ($record != FALSE) {
							$updatedOids = toHTML(trim($record['updatedoids']));
						}
					}
				}
				
				// Mise à jour
				$sqlcmd = "UPDATE eco.$tableName SET ";
				$sqlcmd .= " code = '$code'";
				$sqlcmd .= ",texte = '$texte'";

				if ($tableName == "t_articles") {
					$sqlcmd .= ", gere_en_stock = '$gere_en_stock', article_reference_cacic_id = $cacic_id ";
				}
				
				if ($tableName == "t_fournisseurs") {
					$sqlcmd .= ", fournisseur_reference_cti_id = $rfcti , fournisseur_reference_cacic_id = $cacic_id, fusionner_vers_fournisseur_id = $fusionner_vers_fournisseur_id ";
				}
				
				if ($tableName == "t_reference_input") {
					$sqlcmd .= ", import_data = '$import_data' ";
				}
                
                if ($tableName == 't_types_mouvements') {
                    $sqlcmd .= ", particularite_inverser_signe = '$particularite_inverser_signe' ";
                    $sqlcmd .= ", sens_force = '$sens_force' ";
                }
				
				if ($tableName == 't_types_articles') {
                    $sqlcmd .= ", defaut_selon = '$defaut_selon' ";
                    $sqlcmd .= ", defaut_selon_codes = '$defaut_selon_codes' ";
                }
				
				if ($tableName == 't_divers') {
                    $sqlcmd .= ", valeur = '$valeur' ";
                    $sqlcmd .= ", description = '$description' ";
					$sqlcmd .= "WHERE code = '$code';";
                }
				else {
					$sqlcmd .= ",texte_court = '$texte_court'";
					$sqlcmd .= "WHERE oid = $oid;";
				}
				
				// References fournisseurs CTI dans fournisseurs
				if ($tableName == "t_article_reference_cti") {
					$sqlcmd = "$sqlcmd UPDATE eco.t_articles SET 
							article_reference_cti_id = $oid 
							WHERE oid::text = ANY (string_to_array('$rfoids',','));";
					
					$sqlcmd = "$sqlcmd UPDATE eco.t_articles SET 
							article_reference_cti_id = 0 
							WHERE article_reference_cti_id = $oid AND
								oid::text <> ALL (string_to_array('$rfoids',','));";
							
					$sqlcmd = "$sqlcmd UPDATE eco.t_article_reference_cti
							SET texte_court = texte 
							WHERE texte_court <> texte;";
								
					$sqlcmd = "$sqlcmd UPDATE eco.t_articles SET
							article_reference_cti_code = t_article_reference_cti.code,
							article_reference_cti_texte = t_article_reference_cti.texte_court,
							article_reference_cti_section_id = t_article_reference_cti.section_id,
							article_reference_cti_section_code = t_article_reference_cti.section_code,
							article_reference_cti_section_texte = t_article_reference_cti.section_texte
						FROM eco.t_article_reference_cti 
						WHERE article_reference_cti_id = t_article_reference_cti.oid AND
							 (
								article_reference_cti_code IS DISTINCT FROM t_article_reference_cti.code OR
								article_reference_cti_texte IS DISTINCT FROM t_article_reference_cti.texte_court OR
								article_reference_cti_section_id IS DISTINCT FROM t_article_reference_cti.section_id OR
								article_reference_cti_section_code IS DISTINCT FROM t_article_reference_cti.section_code OR
								article_reference_cti_section_texte IS DISTINCT FROM t_article_reference_cti.section_texte
							);";
				}
				// References fournisseurs CTI dans fournisseurs
				if ($tableName == "t_fournisseur_reference_cti") {
					$sqlcmd = "$sqlcmd UPDATE eco.t_fournisseurs SET 
							fournisseur_reference_cti_id = $oid 
							WHERE oid::text = ANY (string_to_array('$rfoids',','));";
					
					$sqlcmd = "$sqlcmd UPDATE eco.t_fournisseurs SET 
							fournisseur_reference_cti_id = 0 
							WHERE fournisseur_reference_cti_id = $oid AND
								oid::text <> ALL (string_to_array('$rfoids',','));";
								
					$sqlcmd = "$sqlcmd UPDATE eco.t_fournisseur_reference_cti
							SET texte_court = texte 
							WHERE texte_court <> texte;";
								
					$sqlcmd = "$sqlcmd UPDATE eco.t_fournisseurs SET
							fournisseur_reference_cti_code = t_fournisseur_reference_cti.code,
							fournisseur_reference_cti_texte = t_fournisseur_reference_cti.texte_court,
							fournisseur_reference_cti_section_id = t_fournisseur_reference_cti.section_id,
							fournisseur_reference_cti_section_code = t_fournisseur_reference_cti.section_code,
							fournisseur_reference_cti_section_texte = t_fournisseur_reference_cti.section_texte
						FROM eco.t_fournisseur_reference_cti 
						WHERE fournisseur_reference_cti_id = t_fournisseur_reference_cti.oid AND
							 (
								fournisseur_reference_cti_code IS DISTINCT FROM t_fournisseur_reference_cti.code OR
								fournisseur_reference_cti_texte IS DISTINCT FROM t_fournisseur_reference_cti.texte_court OR
								fournisseur_reference_cti_section_id IS DISTINCT FROM t_fournisseur_reference_cti.section_id OR
								fournisseur_reference_cti_section_code IS DISTINCT FROM t_fournisseur_reference_cti.section_code OR
								fournisseur_reference_cti_section_texte IS DISTINCT FROM t_fournisseur_reference_cti.section_texte
							);";
							
					
					
				}
				// Règles types d'articles CTI
				if ($tableName == "t_type_article_cti_rule") {
					$sqlcmd = "
						UPDATE eco.t_type_article_cti_rule SET
							priorite = $priorite,
							texte = '$texte',
							type_article_cti_id = $type_article_cti_id,
							liste_type_article = '$liste_type_article',
							liste_compte = '$liste_compte',
							liste_famille = '$liste_famille',
							liste_sous_famille = '$liste_sous_famille',
							liste_categorie = '$liste_categorie',
							liste_sous_categorie = '$liste_sous_categorie',
							liste_article = '$liste_article'
						WHERE oid = $oid AND
							(
							priorite IS DISTINCT FROM $priorite OR
							texte IS DISTINCT FROM '$texte' OR
							type_article_cti_id IS DISTINCT FROM $type_article_cti_id OR
							liste_type_article IS DISTINCT FROM '$liste_type_article' OR
							liste_compte IS DISTINCT FROM '$liste_compte' OR
							liste_famille IS DISTINCT FROM '$liste_famille' OR
							liste_sous_famille IS DISTINCT FROM '$liste_sous_famille' OR
							liste_categorie IS DISTINCT FROM '$liste_categorie' OR
							liste_sous_categorie IS DISTINCT FROM '$liste_sous_categorie' OR
							liste_article IS DISTINCT FROM '$liste_article'
							)";
				}

				$result = $db->exec($sqlcmd);
				if ($db->lastResult) {
					
				}
				else {
					$updatedOids = "";
					$returnCode = "KO";
					$returnTexte = "Erreur SQL : $db->lastError";
				}
				
				
			}
			
			// creation ou mise à  jour de la liste
			if ($oid == -1) {
				
				// Règles types d'articles CTI
				if ($tableName == "t_type_article_cti_rule") {
					
					$sqlcmd = "
						INSERT INTO eco.t_type_article_cti_rule (
							texte,
							priorite,
							type_article_cti_id,
							liste_type_article,
							liste_compte,
							liste_famille,
							liste_sous_famille,
							liste_categorie,
							liste_sous_categorie,
							liste_article
							)
						VALUES (
							'$texte',
							$priorite,
							$type_article_cti_id,
							'$liste_type_article',
							'$liste_compte',
							'$liste_famille',
							'$liste_sous_famille',
							'$liste_categorie',
							'$liste_sous_categorie',
							'$liste_article'
							)
						";
				}

				$result = $db->exec($sqlcmd);
				if ($db->lastResult) {
					
				}
				else {
					$updatedOids = "";
					$returnCode = "KO";
					$returnTexte = "Erreur SQL : $db->lastError";
				}
				
			}
				
			switch ($tableName) {
                case "t_divers" :
                    $sqlcmd = "SELECT eco.cti_create_repartition()";
                    $result = $db->exec($sqlcmd);
                break;
				case "t_fournisseurs" :
                    $sqlcmd = "SELECT eco.cti_reorganize_fournisseur()";
                    $result = $db->exec($sqlcmd);
                break;
			}
			break;
		case UPDATE :
			// nothing to do yet
			break;
		case COPY :
			// nothing to do yet
			break;
		case DELETE :
			if ($tableName == "t_type_article_cti_rule") {
				$sqlcmd = "DELETE FROM eco.t_type_article_cti_rule WHERE oid = $oid";
				$result = $db->exec($sqlcmd);
			}
			break;
		case UPLOAD :
			
			$tmp_path = "../../../temp";
			$code = toSQL($code);

			$in_file = basename($_FILES['Filedata']['name']);
			$uploadfile = $tmp_path . "/" . $in_file;
			
			if (move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadfile)) {
				$uploadfile = realpath($tmp_path . "/" . $in_file);
				$result = $db->exec("SELECT * FROM eco.cti_gen_referentiel_cacic('$code','$uploadfile')");
				$record = $db->nextRecordAssoc();
				if ($record["cti_gen_referentiel_cacic"] != "OK") {
					$returnCode = "KO";
					$returnTexte = substr($record["cti_gen_referentiel_cacic"],4);
				}
				else {
					
				}
			} 
			else {
				$returnTexte = "Le fichier $importFile n'a pas été téléchargé. Erreur système";
				$returnCode = "KO";
			}

			break;
		case EXEC :
			if ($tableName == "t_type_article_cti_rule") {
				$sqlcmd = "SELECT eco.cti_reorganize_type_article_cti()";
			}

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

	$httpString = "<HTTP_SERVICE returnCode=\"$returnCode\" returnTexte=\"$returnTexte\" updatedOids=\"$updatedOids\" >";
	//$httpString = "<HTTP_SERVICE returnCode=\"KO\" returnTexte=\"$updatedOids\" 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");
}

?>