<?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 $rh_profil_tables;

// DECLARATION DES CONSTANTES
define("SAVE", "save");
define("UPDATE", "update");
define("COPY", "copy");
define("DELETE", "delete");
define("PER_EXECUTE_RULES", "PER_execute_regles");
define("PURGE", "purge_history");

// DECLARATION DES VARIABLES
$compress64 = true;
$database = new Database("iCTI");
$schema = "rh";
$rh_profil_tables = array(
    't_types_contrat' => 'type_contrat',
    't_motifs_debut_contrat' => 'motif_debut',
    't_motifs_fin_contrat' => 'motif_fin',
    't_qualifications' => 'qualification',
    't_services' => 'service',
    't_specialites' => 'specialite',
    't_types_temps_travail' => 'type_temps_travail',
    't_categories_socio_professionnelle' => 'categorie_socio_professionnelle',
    't_statuts' => 'statut',
    't_codes_emploi' => 'code_emploi',
    't_societes_interim' => 'societe_interim',
    't_sections_analytiques_paie' => 'section_analytique_paie',
    't_sections_analytiques' => 'section_analytique',
    't_grilles' => 'grille',
    't_grilles_groupes' => 'grille_groupe',
    't_types_horaire' => 'type_horaire',
    't_groupes_cotisant' => 'groupe_cotisant',
    't_cadre_emploi' => 'cadre_emploi',
    't_categorie_conge' => 'categorie_conge',
    't_categorie_statutaire' => 'categorie_statutaire',
    't_commission_paritaire' => 'commission_paritaire',
    't_compte_imputation' => 'compte_imputation',
    't_filiere' => 'filiere',
    't_lettre_budgetaire' => 'lettre_budgetaire',
    't_unite_fonctionnelle' => 'unite_fonctionnelle'
);

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

$recordNode = @simplexml_load_string($recordXML);

// ECRITURE DE LA REPONSE HTTP
$httpString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
$httpString .= "\n<HTTP_SERVICE>";
if ($schema != "" && $tableName != "" && $action != "" && $recordNode !== FALSE) {
    $httpString .= setRecords($database, $schema, $tableName, $action, $recordNode);
}
if ($action === PER_EXECUTE_RULES)  {
    $sqlcmd = "SELECT $schema.cti_reorganize_population();";
    $result  =  $database->exec($sqlcmd);
}
$httpString .= "\n</HTTP_SERVICE>";
if ($compress64) {
    $httpString = compress64($httpString);
}
echo "<CTICONTENT>$httpString</CTICONTENT>";

// DEFINITIONS DE FONCTION

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

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

    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) {
                $sqlcmd = "UPDATE $schema.$tableName SET ";

                $sqlcmd .= "texte = '$texte'";

                switch ($tableName) {
                    case "t_divers" :
                    case "t_transformation" :
                    case "t_population_regle" :
                        // Pas de colonne texte_court dans ces 3 tables.
                        break;
                    default :
                        $sqlcmd .= ", texte_court = '$texte_court' ";
                        break;
                }

                switch ($tableName) {
                    case "t_rubriques" :
                        $sqlcmd .= ", code_calcul = '".utf8_decode($recordNode["code_calcul"])."' ";
                        $sqlcmd .= ", unite = '".utf8_decode($recordNode["unite"])."' ";
                        $sqlcmd .= ", coefficient = ".floatval(utf8_decode($recordNode["coefficient"]))." ";
                        $sqlcmd .= ", coefficient_base = ".floatval(utf8_decode($recordNode["coefficient_base"]))." ";
                        $sqlcmd .= ", coefficient_nombre = ".floatval(utf8_decode($recordNode["coefficient_nombre"]))." ";
                        $sqlcmd .= ", coefficient_txs = ".floatval(utf8_decode($recordNode["coefficient_txs"]))." ";
                        $sqlcmd .= ", coefficient_txp = ".floatval(utf8_decode($recordNode["coefficient_txp"]))." ";

                        $sqlcmd .= ", user_modified = CASE WHEN user_modified THEN ".(utf8_decode($recordNode["user_modified"]) == 'M' ? "true" : "false")." ELSE true END "; // On peut le décocher que s'il était coché. Sinon ça coche.
                        $sqlcmd .= ", p_cumul = ".(utf8_decode($recordNode["p_cumul"]) == 'C' ? "true" : "false")." ";
                        $sqlcmd .= ", p_detail = ".(utf8_decode($recordNode["p_detail"]) == 'D' ? "true" : "false")." ";
                        $sqlcmd .= ", proratiser_conversion = ".(utf8_decode($recordNode["proratiser_conversion"]) == 'X' ? "true" : "false")." ";

                        $tmpRubArray = array(
                            "nombre",
                            "base",
                            "heures_contrat",
                            "heures_payees",
                            "heures_travaillees",
                            "masse_salariale",
                            "brut",
                            "avantage_nature",
                            "frais_imposables",
                            "cotisation_salarie",
                            "cotisation_patronale",
                            "od_net_salarie",
                            "od_net_patronale",
                            "net_imposable",
                            "net_a_payer",
							"nombre_provisions",
							"montant_provisions",
							"masse_salariale_provisionnee"
                        );

                        foreach ($tmpRubArray as $ind) {
                            $sqlcmd .= ", p_$ind = ".($recordNode["p_$ind"] == 'X' ? "true" : "false")." ";
                            if ($recordNode["p_$ind"] == 'X') {
                                $sqlcmd .= ", s_$ind = ".$recordNode["s_$ind"]." ";
                                $tmpCoeff = 1;
                                if ($recordNode["c_$ind"] != "") {
                                    $tmpCoeff = floatval($recordNode["c_$ind"]);
                                }
                                $sqlcmd .= ", c_$ind = ".$tmpCoeff." ";
                            }
                        }

                        break;
                    case "t_etablissements" :
                        $sqlcmd .= ", base_calcul_etp = '".utf8_decode($recordNode["base_calcul_etp"])."' ";
                        $sqlcmd .= ", planning_code = '".utf8_decode($recordNode["code_ets_planning"])."' ";
                        $sqlcmd .= ", finess_id = '".floatval($recordNode["finess_id"])."' ";
                        break;
                    case "t_entreprises" :
                        $sqlcmd .= ", planning_code = '".utf8_decode($recordNode["code_ent_planning"])."' ";
                        break;
                    case "t_divers" :
                        $sqlcmd .= ", valeur = '".utf8_decode($recordNode["valeur"])."' ";
                        $sqlcmd .= ", show_info_module = (".utf8_decode($recordNode["show_info_module"])." = 1) ";
                        // On n'a pas de raison de mettre à jour la date dans rh.t_divers.
                        // Donc la ligne qui suit est commentée.
                        //$sqlcmd .= ", valeur_date = '" . utf8_decode($recordNode["valeur_date"]) . "'::date ";
                        break;
                    case "t_transformation" :
                        $sqlcmd .= ", date_debut = '".utf8_decode($recordNode["date_debut"])."' ";
                        $sqlcmd .= ", date_fin = '".utf8_decode($recordNode["date_fin"])."' ";
                        $sqlcmd .= ", salarie_id = '".utf8_decode($recordNode["salarie_id"])."' ";
                        $sqlcmd .= ", from_service_id = '".utf8_decode($recordNode["from_service_id"])."' ";
                        $sqlcmd .= ", to_service_id = '".utf8_decode($recordNode["to_service_id"])."' ";
                        $sqlcmd .= ", from_qualification_id = '".utf8_decode($recordNode["from_qualification_id"])."' ";
                        $sqlcmd .= ", to_qualification_id = '".utf8_decode($recordNode["to_qualification_id"])."' ";
                        break;
					case "t_data_profile" :	
						$sqlcmd .= ", etablissement_inclus = '".toSQL(utf8_decode($recordNode["etablissement_inclus"]))."' ";
						$sqlcmd .= ", etablissement_exclus = '".toSQL(utf8_decode($recordNode["etablissement_exclus"]))."' ";
						$sqlcmd .= ", service_inclus = '".toSQL(utf8_decode($recordNode["service_inclus"]))."' ";
						$sqlcmd .= ", service_exclus = '".toSQL(utf8_decode($recordNode["service_exclus"]))."' ";
						$sqlcmd .= ", statut_inclus = '".toSQL(utf8_decode($recordNode["statut_inclus"]))."' ";
						$sqlcmd .= ", statut_exclus = '".toSQL(utf8_decode($recordNode["statut_exclus"]))."' ";
						break;
                    case "t_planning_service" :
                        $sqlcmd .= ", service_id = '".floatval(utf8_decode($recordNode["service_id"]))."' ";
                        break;
                    case "t_planning_qualification" :
                        $sqlcmd .= ", qualification_id = '".floatval(utf8_decode($recordNode["qualification_id"]))."' ";
                        break;
                    case 't_population_regle' :
                        $sqlcmd .= "
                            ,code                                  = '" . utf8_decode($recordNode['code']) . "'
                            ,priorite                              = " . utf8_decode($recordNode['priorite']) . "
                            ,population_id                         = " . utf8_decode($recordNode['population_id']) . "
                            ,liste_finess                          = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_finess']) . "')
                            ,liste_etablissement                   = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_etablissement']) . "')
                            ,liste_service                         = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_service']) . "')
                            ,liste_specialite                      = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_specialite']) . "')
                            ,liste_section_analytique              = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_section_analytique']) . "')
                            ,liste_section_analytique_paie         = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_section_analytique_paie']) . "')
                            ,liste_qualification                   = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_qualification']) . "')
                            ,liste_grille                          = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_grille']) . "')
                            ,liste_code_emploi                     = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_code_emploi']) . "')
                            ,liste_categorie_socio_professionnelle = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_categorie_socio_professionnelle']) . "')
                            ,liste_statut                          = rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_statut']) . "')
                        ";
                        break;
					case 't_expert_controle' :
                        $sqlcmd .= "
						    ,code                                  	= '" . utf8_decode($recordNode['code']) . "'
							,texte_abrege							= '" . utf8_decode($recordNode['texte_abrege']) . "'
							,description 							= '" . utf8_decode($recordNode['description']) . "'
							,is_cti 								= '" . utf8_decode($recordNode['is_cti']) . "'
							,is_hide 								= '" . utf8_decode($recordNode['is_hide']) . "'
							,gravite_id 							= " . utf8_decode($recordNode['gravite']) . "
							,prestataire_id 						= " . utf8_decode($recordNode['prestataire']) . "
							,is_active 								= '" . utf8_decode($recordNode['is_active']) . "'
							,alert_exp 								= '" . utf8_decode($recordNode['is_alert']) . "'
                        ";
                        break;
                }

                if ($tableName == "t_divers") {
                    $sqlcmd .= "WHERE code = '$code'";
                } else {
                    $sqlcmd .= "WHERE oid = $oid";
                }

                if ($tableName != 't_expert_controle') {
					$result = $db->exec($sqlcmd);
				}
				else {
					if ($recordNode['mode'] == 2) {
						$EXPERT_ACTIVE = utf8_decode($recordNode["EXPERT_ACTIVE"]);
						$EXPERT_DATE_DEBUT = utf8_decode($recordNode["EXPERT_DATE_DEBUT"]);

						$sqlcmd = "UPDATE rh.t_divers
								SET valeur = '$EXPERT_ACTIVE'
								WHERE code = 'EXPERT_ACTIVE' AND
									valeur IS DISTINCT FROM '$EXPERT_ACTIVE'; ";
						$result  = $db->exec($sqlcmd);
						
						$sqlcmd = "UPDATE rh.t_divers
								SET valeur_date = to_date('$EXPERT_DATE_DEBUT','DD/MM/YYYY'),
									valeur = '$EXPERT_DATE_DEBUT'
								WHERE code = 'EXPERT_DATE_DEBUT' AND
									valeur_date IS DISTINCT FROM to_date('$EXPERT_DATE_DEBUT','DD/MM/YYYY'); ";
						$result  = $db->exec($sqlcmd);
					} else {
						$result = $db->exec($sqlcmd);
						$sqlcmd = 
							"UPDATE rh.t_expert_controle_rule
							SET sqlcmd_where = '" . toSQL(utf8_decode($recordNode['sqlcmd_where1'])) . "', 
								sqlcmd_justificatif = '" . toSQL(utf8_decode($recordNode['sqlcmd_justificatif1'])) . "',
								table_id = " . toSQL(utf8_decode($recordNode['table1'])) . "
							WHERE controle_id = ". $oid;
						$result  = $db->exec($sqlcmd);
					}
				}
				
                if (array_key_exists($tableName, $rh_profil_tables)) {
                    $sqlcmd = "SELECT rh.cti_reorganize_profils_table('$tableName', '".$rh_profil_tables[$tableName]."');";
                    $result = $db->exec($sqlcmd);
                }

                switch ($tableName) {
                    case "t_transformation" :
                        $sqlcmd = "SELECT rh.cti_execute_transform()";
                        $result = $db->exec($sqlcmd);
                        break;
                    case "t_etablissements" :
                        $sqlcmd = "
                            UPDATE rh.t_etablissements SET
                                finess_code = t_finess.code,
                                finess_texte = t_finess.texte,
                                finess_section_id = t_finess.section_id,
                                finess_section_code = t_finess.section_code,
                                finess_section_texte = t_finess.section_texte
                            FROM base.t_finess
                            WHERE 1=1
                                AND t_etablissements.finess_id = t_finess.oid
                                AND t_etablissements.oid = $oid
                        ";
                        $result = $db->exec($sqlcmd);
                        break;
					 case "t_data_profile" :
						$sqlcmd = "SELECT rh.cti_gen_data_profile_views()";
						$result = $db->exec($sqlcmd);
						break;
                    case "t_divers" :
                        $sqlcmd = "SELECT rh.cti_hp_create_views()";
                        $result = $db->exec($sqlcmd);
                        break;
                    case "t_planning_service" :
                        $sqlcmd = "
                            UPDATE rh.t_planning_service SET
                                service_code          = t_services.code,
                                service_texte         = t_services.texte_court,
                                service_section_id    = t_services.section_id,
                                service_section_code  = t_services.section_code,
                                service_section_texte = t_services.section_texte
                            FROM rh.t_services
                            WHERE 1=1
                                AND t_planning_service.Service_id = t_services.oid
                                AND (1!=1
                                    OR service_code IS DISTINCT          FROM t_services.code
                                    OR service_texte IS DISTINCT         FROM t_services.texte_court
                                    OR service_section_id IS DISTINCT    FROM t_services.section_id
                                    OR service_section_code IS DISTINCT  FROM t_services.section_code
                                    OR service_section_texte IS DISTINCT FROM t_services.section_texte)
                        ";
                        $result = $db->exec($sqlcmd);
                        break;
                    case "t_planning_qualification" :
                        $sqlcmd = "
                            UPDATE rh.t_planning_qualification SET
                                qualification_code = t_qualifications.code,
                                qualification_texte = t_qualifications.texte_court,
                                qualification_section_id = t_qualifications.section_id,
                                qualification_section_code = t_qualifications.section_code,
                                qualification_section_texte = t_qualifications.section_texte
                            FROM rh.t_qualifications
                            WHERE 1=1
                                AND t_planning_qualification.Service_id = t_qualifications.oid
                                AND (1!=1
                                    OR qualification_code IS DISTINCT FROM t_qualifications.code
                                    OR qualification_texte IS DISTINCT FROM t_qualifications.texte_court
                                    OR qualification_section_id IS DISTINCT FROM t_qualifications.section_id
                                    OR qualification_section_code IS DISTINCT FROM t_qualifications.section_code
                                    OR qualification_section_texte IS DISTINCT FROM t_qualifications.section_texte)
                        ";
                        $result = $db->exec($sqlcmd);
                        break;
                }
            } else {
                // Ajouts
                if ($tableName == "t_transformation") {
                    $sqlcmd = "INSERT INTO $schema.$tableName (";
                    $sqlcmd .= "texte, ";
                    $sqlcmd .= "date_debut, ";
                    $sqlcmd .= "date_fin, ";
                    $sqlcmd .= "salarie_id, ";
                    $sqlcmd .= "from_service_id, ";
                    $sqlcmd .= "to_service_id, ";
                    $sqlcmd .= "from_qualification_id, ";
                    $sqlcmd .= "to_qualification_id";
                    $sqlcmd .= ") ";
                    $sqlcmd .= "VALUES (";
                    $sqlcmd .= "'".toSQL(utf8_decode($recordNode["texte"]))."', ";
                    $sqlcmd .= "'".utf8_decode($recordNode["date_debut"])."', ";
                    $sqlcmd .= "'".utf8_decode($recordNode["date_fin"])."', ";
                    $sqlcmd .= "".utf8_decode($recordNode["salarie_id"]).", ";
                    $sqlcmd .= "".utf8_decode($recordNode["from_service_id"]).", ";
                    $sqlcmd .= "".utf8_decode($recordNode["to_service_id"]).", ";
                    $sqlcmd .= "".utf8_decode($recordNode["from_qualification_id"]).", ";
                    $sqlcmd .= "".utf8_decode($recordNode["to_qualification_id"])." ";
                    $sqlcmd .= ")";
                    $result = $db->exec($sqlcmd);

                    $sqlcmd = "SELECT rh.cti_execute_transform()";
                    $result = $db->exec($sqlcmd);
                }
				  // Ajouts
                if ($tableName == "t_data_profile") {
                    $sqlcmd = "INSERT INTO $schema.$tableName (";
					$sqlcmd .= "code, ";
                    $sqlcmd .= "texte, ";
					$sqlcmd .= "texte_court, ";
                    $sqlcmd .= "etablissement_inclus, ";
                    $sqlcmd .= "etablissement_exclus, ";
                    $sqlcmd .= "service_inclus, ";
                    $sqlcmd .= "service_exclus, ";
                    $sqlcmd .= "statut_inclus, ";
                    $sqlcmd .= "statut_exclus";
                    $sqlcmd .= ") ";
                    $sqlcmd .= "VALUES (";
					$sqlcmd .= "'".toSQL(utf8_decode($recordNode["code"]))."', ";
					$sqlcmd .= "'".toSQL(utf8_decode($recordNode["texte"]))."', ";
					$sqlcmd .= "'".toSQL(utf8_decode($recordNode["texte"]))."', ";
                    $sqlcmd .= "'".toSQL(utf8_decode($recordNode["etablissement_inclus"]))."', ";
                    $sqlcmd .= "'".toSQL(utf8_decode($recordNode["etablissement_exclus"]))."', ";
				    $sqlcmd .= "'".toSQL(utf8_decode($recordNode["service_inclus"]))."', ";
				    $sqlcmd .= "'".toSQL(utf8_decode($recordNode["service_exclus"]))."', ";
				    $sqlcmd .= "'".toSQL(utf8_decode($recordNode["statut_inclus"]))."', ";
				    $sqlcmd .= "'".toSQL(utf8_decode($recordNode["statut_exclus"]))."' ";
                    $sqlcmd .= ")";
                    $result = $db->exec($sqlcmd);

					$sqlcmd = "SELECT rh.cti_gen_data_profile_views()";
					$result = $db->exec($sqlcmd);
                }
                
                if ($tableName == "t_population") {
                    $sqlcmd = "
                        INSERT INTO rh.t_population (
                            code,
                            texte)
                        VALUES(
                            '" . utf8_decode($recordNode["code"]) . "',
                            '" . utf8_decode($recordNode["texte"]) . "')
                    ";
                    $result = $db->exec($sqlcmd);
                }

                if ($tableName == "t_population_regle") {
                    $sqlcmd = "
                        INSERT INTO rh.t_population_regle (
                            texte,
                            code,
                            priorite,
                            population_id,
                            liste_finess,
                            liste_etablissement,
                            liste_service,
                            liste_specialite,
                            liste_section_analytique,
                            liste_section_analytique_paie,
                            liste_qualification,
                            liste_grille,
                            liste_code_emploi,
                            liste_categorie_socio_professionnelle,
                            liste_statut)
                        VALUES(
                            '" . utf8_decode($recordNode["texte"]) . "',
                            '" . utf8_decode($recordNode["code"]) . "',
                            " . utf8_decode($recordNode["priorite"]) . ",
                            " . utf8_decode($recordNode["population_id"]) . ",
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_finess']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_etablissement']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_service']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_specialite']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_section_analytique']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_section_analytique_paie']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_qualification']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_grille']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_code_emploi']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_categorie_socio_professionnelle']) . "'),
                            rh.cti_util_translate_list('" . utf8_decode($recordNode['liste_statut']) . "'))
                    ";
                    $result = $db->exec($sqlcmd);
                }
				
				if ($tableName == 't_expert_controle') {
                    $sqlcmd = "
					INSERT INTO rh.t_expert_controle 
						( 
							code, 
							texte, 
							texte_court, 
							texte_abrege, 
							description, 
							is_cti, 
							is_hide, 
							gravite_id,
							prestataire_id,
							is_active, 
							alert_exp
						) 
						VALUES(
							'" . $code . "'
							,'" . $texte . "'
							,'" . $texte_court . "'
							,'" . utf8_decode($recordNode['texte_abrege']) . "'
							,'" . utf8_decode($recordNode['description']) . "'
							,'" . utf8_decode($recordNode['is_cti']) . "'
							,'" . utf8_decode($recordNode['is_hide']) . "'
							," . utf8_decode($recordNode['gravite']) . "
							," . utf8_decode($recordNode['prestataire']) . "
							,'" . utf8_decode($recordNode['is_active']) . "'
							,'" . utf8_decode($recordNode['is_alert']) . "')
                    ";
					$result  = $db->exec($sqlcmd);
					if ($result == FALSE) {
					
					}
					else {
						$result = $db->exec(
							"SELECT max(oid) as oid FROM
							rh.t_expert_controle 
							WHERE code = '" . utf8_decode($recordNode['code']). "' AND texte = '$texte'"
						);
						if ($result != false) {
							$record = $db->nextRecordInto();
							if ($record != FALSE) {
								$oid = $record[0] + 0;
								$sqlcmd = "
									DELETE FROM rh.t_expert_controle_rule
									USING 
									(
									SELECT t_expert_controle_rule.oid
									FROM rh.t_expert_controle_rule
									LEFT JOIN rh.t_expert_controle ON t_expert_controle_rule.controle_id = t_expert_controle.oid
									WHERE t_expert_controle.oid IS NULL
									) subview
									WHERE t_expert_controle_rule.oid = subview.oid;

									INSERT INTO rh.t_expert_controle_rule (
										controle_id,
										numero,
										sqlcmd_where,
										sqlcmd_justificatif,
										table_id
										)
									VALUES 
									(" . $oid . ",  
										1::bigint,
										'" . toSQL(utf8_decode($recordNode['sqlcmd_where1'])) . "', 
										'" . toSQL(utf8_decode($recordNode['sqlcmd_justificatif1'])) . "',
										" . toSQL(utf8_decode($recordNode['table1'])) . ");";
								error_log($sqlcmd);$result = $db->exec($sqlcmd);
							}
						}
					}
				}
			}
            break;
        case UPDATE :
            // nothing to do yet
            break;
        case COPY :
            // nothing to do yet
				if ($tableName == 't_expert_controle') {
				$sqlcmd = "SELECT count(*)+1 as index
						FROM rh.t_expert_controle 
						JOIN rh.t_expert_controle tout
						ON LEFT(tout.code,LENGTH(t_expert_controle.code)) = t_expert_controle.code
						WHERE t_expert_controle.oid = $oid";
				$result = $db->exec($sqlcmd);
				$record = $db->nextRecordInto();
				$index = $record[0];
				error_log($index);
                $sqlcmd = "
				INSERT INTO rh.t_expert_controle 
					( 
						code, 
						texte, 
						texte_court, 
						texte_abrege, 
						description, 
						is_cti, 
						is_hide, 
						gravite_id,
						prestataire_id,
						is_active, 
						alert_exp
					) 
					SELECT 
						code || '_' || $index, 
						'Copie ' || ($index - 1) || ' de ' || texte, 
						texte_court, 
						texte_abrege, 
						description, 
						is_cti, 
						is_hide, 
						gravite_id,
						prestataire_id,
						is_active, 
						alert_exp
					FROM rh.t_expert_controle
					WHERE oid = $oid";
				$result  = $db->exec($sqlcmd);
				if ($result == FALSE) {
				
				}
				else {
					$record = $db->nextRecordInto();
					$result = $db->exec(
						"SELECT max(oid) as oid FROM
						rh.t_expert_controle 
						WHERE code = '" . $code . "_". $index . "'"
					);
					if ($result != false) {
						$record = $db->nextRecordInto();
						if ($record != FALSE) {
							$oid = $record[0] + 0;
							$sqlcmd = "
								DELETE FROM rh.t_expert_controle_rule
								USING 
								(
								SELECT t_expert_controle_rule.oid
								FROM rh.t_expert_controle_rule
								LEFT JOIN rh.t_expert_controle ON t_expert_controle_rule.controle_id = t_expert_controle.oid
								WHERE t_expert_controle.oid IS NULL
								) subview
								WHERE t_expert_controle_rule.oid = subview.oid;

								INSERT INTO rh.t_expert_controle_rule (
									controle_id,
									numero,
									sqlcmd_where,
									sqlcmd_justificatif,
									table_id
									)
								VALUES 
								(" . $oid . ",  
									1::bigint,
									'" . toSQL(utf8_decode($recordNode['sqlcmd_where1'])) . "', 
									'" . toSQL(utf8_decode($recordNode['sqlcmd_justificatif1'])) . "',
									" . toSQL(utf8_decode($recordNode['table1'])) . ");";
						}
					}
				}
			}
		
            break;
        case DELETE :
            if ($tableName == "t_transformation") {
                $sqlcmd = "DELETE FROM $schema.$tableName WHERE oid = $oid";
                $result = $db->exec($sqlcmd);

                $sqlcmd = "SELECT rh.cti_execute_transform()";
                $result = $db->exec($sqlcmd);
            }
            if ($tableName == "t_data_profile") {
                $sqlcmd = "DELETE FROM $schema.$tableName WHERE oid = $oid";
                $result = $db->exec($sqlcmd);

                $sqlcmd = "SELECT rh.cti_gen_data_profile_views()";
                $result = $db->exec($sqlcmd);
            }
            if ($tableName == "t_population") {
                $sqlcmd = "DELETE FROM $schema.$tableName WHERE oid = $oid";
                $result = $db->exec($sqlcmd);
            }
            if ($tableName == "t_population_regle") {
                $sqlcmd = "DELETE FROM $schema.$tableName WHERE oid = $oid";
                $result = $db->exec($sqlcmd);
            }
			if ($tableName == "t_expert_controle") {
                $sqlcmd = "DELETE FROM $schema.$tableName WHERE oid = $oid";
                $result = $db->exec($sqlcmd);
				$sqlcmd = "DELETE FROM $schema." . $tableName ."_rule WHERE controle_id = $oid";
                $result = $db->exec($sqlcmd);
            }
            break;
			case PURGE :
				if ($tableName == "t_expert_controle") {
					if ($oid != '') {
						$sqlcmd = "DELETE FROM $schema.p_expert_controle WHERE controle_id = $oid";
					}
					else {
						$sqlcmd = "TRUNCATE $schema.p_expert_controle";
					}
					$result = $db->exec($sqlcmd);
					$sqlcmd = "UPDATE $schema.$tableName" . "_rule SET last_execution_date = null, last_execution_ok = '' WHERE controle_id = $oid";
					$result = $db->exec($sqlcmd);
				}
			break;
        default:
            // nothing to do yet
            break;
    }
    erase_cache($db, $schema);
}

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

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

    // Effacer cache nouvelle version
    cleanAllCache("iCTI_$schema");
}

?>