<?php
$MODULE="pmsi";
$TITLE="Import des données MAT2A";
$DFTENDSTATUS="OK";
$ARGS="";
/** 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
 */


// Paramètres
//	-fs ou --filename-source = Fichier importé : C:/cti/icti_xxx/temp/xxxxxxxxxxxxxx_appli_05 11 2013.zip
//	-fd ou --filename-destination = Nom du fichier : appli05.zip


list($environmentPath) = explode(DIRECTORY_SEPARATOR.'modules', dirname(__FILE__));
$environmentPath .= DIRECTORY_SEPARATOR;

require_once $environmentPath . '/modules/base/php/lib/cti/Autoloader.php';
Autoloader::register();

require_once $environmentPath . '/modules/base/php/lib/cti/Batch/iCTI_batch_common.php';
require_once $environmentPath . '/modules/base/php/classSimpleXML.php';
require_once $environmentPath . '/modules/base/php/Functions.php';
require_once $environmentPath . '/modules/outils/php/httpService_cacheManager_cleanCache.php';

global $ENDSTATUS;
global $iCTI_connexion;
global $cti_args;


global $ENV_TYPEETS;
global $ENV_FINESS;
global $ENV_LOCALKEYS;

global $MAT2A_zipfile;
global $MAT2A_zipfilename;
global $debug;

$debug = false;

logStartMsg("TRAITEMENT DES DONNEES MAT2A");

// Initialisations et connexions
if (initialize()) {
	if (iCTI_connect()) {
		
		main_exec();
	
		iCTI_disconnect();
	}
}

logEndMsg("TRAITEMENT DES DONNEES MAT2A");


// Exécution générale
function main_exec() {

	global $MAT2A_zipfile;
	global $MAT2A_zipfilename;
    global $ENV_TYPEETS;
	
	
	// Détection finess, année, mois
	$MAT2A_annee = "";
	$MAT2A_mois = "";
	$MAT2A_finess = "";
	
	$zip = @zip_open(realpath($MAT2A_zipfile));
	$MAT2A_count = 0;
	if ($zip) {
		
		while ($zip_entry = zip_read($zip)) {

			if (zip_entry_open($zip, $zip_entry)) {
				
				$MAT2A_filename = trim(zip_entry_name($zip_entry));
				$eFileName = explode('.', $MAT2A_filename);
		
				if ($MAT2A_finess == "") {
					// Druide 2023
					$MAT2A_finess = $eFileName[0];
					$MAT2A_annee = $eFileName[1];
					$MAT2A_mois = $eFileName[2];

					if (stripos($MAT2A_finess, "ovalide") > -1){
						//Dans l'ancienne version le premier élément commence par "ovalide t2a"
						//Ancienne Version
						$MAT2A_finess = $eFileName[count($eFileName) - 5];
						$MAT2A_annee = $eFileName[count($eFileName) - 4];
						$MAT2A_mois = $eFileName[count($eFileName) - 3];
					}	

					zip_entry_close($zip_entry);
				}
				
				$MAT2A_count++;
			}
		}
		zip_close($zip);
	}
	
	// Erreur si un seul fichier dans le zip
	if ($MAT2A_count <= 1) {
		logErrorMsg("Le fichier $MAT2A_zipfile ne contient qu'un seul fichier");
		return FALSE;
	}
	
	// Identification SHA1 du fichier ZIP
	$MAT2A_sha1 = sha1_file($MAT2A_zipfile);
	
	// Initialisation entete (ajout ou raz)
	$MAT2A_annee = floatval($MAT2A_annee);
	$MAT2A_mois = floatval($MAT2A_mois);
	
	// Seulement à partir de 2012
	if ($MAT2A_annee < 2012) {
		logErrorMsg("Les tableaux MAT2A/OVALIDE ne sont traités qu'à partir de 2012");
		return FALSE;
	}
	
	$sqlcmd = "UPDATE pmsi.p_mat2a_import SET
					fichier = '$MAT2A_zipfilename',
					date = now()::date,
					mat2a_annee = $MAT2A_annee,
					mat2a_mois = $MAT2A_mois,
					mat2a_date = '20991231',
					mat2a_rsa_transmis = 0,
					mat2a_rsa_traites = 0,
					mat2a_rsa_seances = 0,
					mat2a_rsa_0_nuits = 0,
					mat2a_rsa_prestations_nb_total = 0,
					mat2a_rsa_prestations_base_remb = 0,
					mat2a_nb_sejours_valorises = 0,
					mat2a_br_sejours_valorises = 0
				WHERE sha1 = '$MAT2A_sha1';
						
				INSERT INTO pmsi.p_mat2a_import(
					sha1,
					fichier,
					date,
					mat2a_annee,
					mat2a_mois,
					mat2a_date,
					mat2a_rsa_transmis,
					mat2a_rsa_traites,
					mat2a_rsa_seances,
					mat2a_rsa_0_nuits,
					mat2a_rsa_prestations_nb_total,
					mat2a_rsa_prestations_base_remb,
					mat2a_nb_sejours_valorises,
					mat2a_br_sejours_valorises
					)
				SELECT
					'$MAT2A_sha1',
					'$MAT2A_zipfilename',
					now()::date,
					$MAT2A_annee,
					$MAT2A_mois,
					'20991231',
					0,
					0,
					0,
					0,
					0,
					0,
					0,
					0
				WHERE '$MAT2A_sha1' NOT IN (SELECT sha1 FROM pmsi.p_mat2a_import)
				;				
				
				UPDATE pmsi.p_mat2a_import
				SET mat2a_mois = mat2a_mois_last
				FROM
					(
					SELECT mat2a_annee, MAX(mat2a_mois) AS mat2a_mois_last
					FROM pmsi.p_mat2a_import
					WHERE mat2a_mois > 0
					GROUP BY 1
					) subview
				WHERE p_mat2a_import.mat2a_annee = subview.mat2a_annee AND
					p_mat2a_import.mat2a_mois = 0 AND
					p_mat2a_import.sha1 = '$MAT2A_sha1'
					;
			";
	iCTI_execute($sqlcmd);
	
	$sqlcmd = "SELECT oid FROM pmsi.p_mat2a_import WHERE sha1 = '$MAT2A_sha1'";
	$record = iCTI_query($sqlcmd);
	$MAT2A_oid = floatval($record["oid"]);
	
	// Suppression génération temporaire
	$sqlcmd = "DELETE FROM pmsi.p_mat2a_file WHERE mat2a_import_id = $MAT2A_oid OR mat2a_import_id NOT IN (SELECT OID from pmsi.p_mat2a_import)";
	iCTI_execute($sqlcmd);
	
	$data_path = realpath($MAT2A_zipfile);
	debug($MAT2A_oid);
	debug($MAT2A_zipfile);
	debug($data_path);
	
	$tmp_file = "..\..\..\\temp\\" . $MAT2A_zipfile;
	if (file_exists($data_path)) {
		$file_size = filesize($data_path);
		$file_name = toSQL($MAT2A_zipfilename);
		$data_type = 'ZIP';
		$start = 0;
		$data_num = 0;
		debug($file_size);
		debug($file_name);
		debug($data_type);
		debug($MAT2A_sha1);
		while ($start <= $file_size) {
			$filebuff = file_get_contents($data_path, FALSE, NULL, $start, 10000000);
			if ($filebuff === false) {
				debug('ca lit pas');
			} 
			else {
				debug('ca marche !');
			}
			$filebuff = pg_escape_bytea($filebuff);
			$sqlcmd = "INSERT INTO pmsi.p_mat2a_file (mat2a_import_id, data_type, date_creation, data_num, file_path, file_size, data_crc, data)
						VALUES($MAT2A_oid, '$data_type', date(now()), $data_num, '$file_name', $file_size, '$MAT2A_sha1', '$filebuff')";
			iCTI_execute($sqlcmd);
			$start = $start + 10000000;
			$data_num++;
		}
	}
	else {
		debug($data_path . " n'existe pas");
	}
	
	
	// Suppression génération temporaire
	$sqlcmd = "DELETE FROM pmsi.p_mat2a_data WHERE mat2a_import_id = $MAT2A_oid";
	iCTI_execute($sqlcmd);
	
	// Décompression fichier et import dans la base CTI
	$zip = @zip_open(realpath($MAT2A_zipfile));

	if ($zip) {
		
		while ($zip_entry = zip_read($zip)) {

			if (zip_entry_open($zip, $zip_entry)) {
				
				$MAT2A_filename = trim(zip_entry_name($zip_entry));
				$MAT2A_file = realpath("../../../TEMP/") . "/$MAT2A_filename";
				@unlink($MAT2A_file);
				$MAT2A_file = str_replace("\\","/",$MAT2A_file);

                // gestion du sous-dossier MAT2A présent dans les fichiers sip ePMSI depuis fin 2017
                $MAT2A_file = str_ireplace("//MAT2A","",$MAT2A_file);
                				
				logInfoMsg("Décompression $MAT2A_filename");

                $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

                $convert = new ConvertEncodage($buf);
                $content = $convert->toISO_8859_1();

                file_put_contents($MAT2A_file, $content);

				$sqlcmd = "SELECT pmsi.cti_import_mat2a_file($MAT2A_oid, '$MAT2A_file')";
				iCTI_execute($sqlcmd);

				@unlink($MAT2A_file);
				
				zip_entry_close($zip_entry);
			}
		}
		zip_close($zip);
	}
	
	// Modif de CLA le 09-11-2015
	// Dans le fichier 1.V.4.MDAME, le tableau A concerne les UCD et le tableau B les LPP. S'il n'y a pas d'UCD,
	// le tableau des LPP est enregistré dans p_mat2a_data avec table_sequence = 1 alors qu'on s'attend à ce qu'il soit table_mat2a = 2
	// --> dans ce cas là, on force table_sequence à 2
	$sqlcmd = "
			UPDATE pmsi.p_mat2a_data SET
				table_sequence = 2
			WHERE 1=1
				AND file_code::text || table_sequence::text = ANY (ARRAY(
						SELECT 
							file_code::text || table_sequence::text 
						FROM pmsi.p_mat2a_data 
						WHERE 
							line_type = 'T' 
							AND data_mat2a[2] ilike '%dispositifs médicaux%' 
							AND file_code = 'T1V4MDAME')::text[]
					)
				AND table_sequence = 1;";
	iCTI_execute($sqlcmd);
	
	// Finalisation import fichier
	
	logInfoMsg("Finalisation. Extraction compteurs");
	
	$sqlcmd = "VACUUM FULL pmsi.p_mat2a_data";
	iCTI_execute($sqlcmd);
	
	
	// Mise à jour entete fichier selon données
	$sqlcmd = "UPDATE pmsi.p_mat2a_import SET
					mat2a_date = subview.mat2a_date,
					mat2a_rsa_transmis = subview.mat2a_rsa_transmis,
					mat2a_rsa_seances = subview.mat2a_rsa_seances,
					mat2a_rsa_0_nuits = subview.mat2a_rsa_0_nuits,
					mat2a_rsa_traites = subview.mat2a_rsa_transmis - 
								subview.mat2a_rsa_non_traites_1 - 
								subview.mat2a_rsa_non_traites_2 - 
								subview.mat2a_rsa_non_traites_3 - 
								subview.mat2a_rsa_non_traites_4,
					mat2a_nb_sejours_valorises = subview.mat2a_nb_sejours_valorises,
					mat2a_br_sejours_valorises = subview.mat2a_br_sejours_valorises,
					mat2a_rsa_prestations_base_remb = subview.mat2a_br_sejours_valorises
				FROM (
					SELECT
						MAX(CASE WHEN file_code = 'T1D2RTP' AND line_type = 'T'
							THEN to_date(split_part(data_mat2a[1],'Date du traitement:',2),'DD/MM.YYYY') 
							ELSE '00010101' END) AS mat2a_date,
						MAX(CASE WHEN file_code = 'T1D2RTP' AND data_mat2a[1] ILIKE '%Nb de RSA transmis%' 
							THEN base.cti_to_number(data_mat2a[2]) 
							ELSE 0 END) AS mat2a_rsa_transmis,
						MAX(CASE WHEN file_code = 'T1D2RTP' AND data_mat2a[1] ILIKE '%Nb de RSA en CMD 90%' 
							THEN base.cti_to_number(data_mat2a[2]) 
							ELSE 0 END) AS mat2a_rsa_non_traites_1,
						MAX(CASE WHEN file_code = 'T1D2RTP' AND data_mat2a[1] ILIKE '%Nb de RSA hors période%'
							THEN base.cti_to_number(data_mat2a[2]) 
							ELSE 0 END) AS mat2a_rsa_non_traites_2,
						MAX(CASE WHEN file_code = 'T1V1SV' AND data_mat2a[1] ILIKE '%prestation inter-établissement%' 
							THEN base.cti_to_number(data_mat2a[2]) 
							ELSE 0 END) AS mat2a_rsa_non_traites_3,
						MAX(CASE WHEN file_code = 'T1D2RTP' AND data_mat2a[1] ILIKE '%Nb de RSA en GHS 9999%' 
							THEN base.cti_to_number(data_mat2a[2])
							ELSE 0 END) AS mat2a_rsa_non_traites_4,
						MAX(CASE WHEN file_code = 'T1D2RTP' AND data_mat2a[1] ILIKE '%Nb de RSA séances%' 
							THEN base.cti_to_number(data_mat2a[2]) 
							ELSE 0 END) AS mat2a_rsa_seances,
						MAX(CASE WHEN data_mat2a[1] ILIKE '%Nb de RSA DS=0%' 
							THEN base.cti_to_number(data_mat2a[2]) 
							ELSE 0 END) AS mat2a_rsa_0_nuits,
						MAX(CASE WHEN file_code = 'T1V1SV' AND data_mat2a[1] ILIKE '%Séjours valorisés%'
							THEN base.cti_to_number(data_mat2a[2]) 
							ELSE 0 END) AS mat2a_nb_sejours_valorises,
						MAX(CASE WHEN file_code = 'T1V1SV' AND data_mat2a[1] ILIKE '%Séjours valorisés%' 
							THEN base.cti_to_number(data_mat2a[3]) 
							WHEN file_code = 'T1V1CP' AND table_sequence = 2 AND line_type = 'F' 
							THEN base.cti_to_number(data_mat2a[4])  
							WHEN file_code = 'T1V1CP' AND table_sequence = 1 AND line_type = 'F' 
							THEN base.cti_to_number(data_mat2a[4]) 
							ELSE 0 END) 
						+
						MAX(CASE WHEN file_code = 'T1V4SYNTS' AND data_mat2a[1] ILIKE '%RSF activité externe supprimés%' 
							THEN base.cti_to_number(data_mat2a[5]) 
							ELSE 0 END)
						+
						MAX(CASE WHEN file_code = 'T1V4SYNTS' AND data_mat2a[1] ILIKE '%Autres anomalies%' 
							THEN base.cti_to_number(data_mat2a[5]) 
							ELSE 0 END)
						+
						MAX(CASE WHEN file_code = 'T1V4SYNTS' AND data_mat2a[1] ILIKE '%prestation inter-établissement%'  AND $ENV_TYPEETS = '1'
							THEN base.cti_to_number(data_mat2a[5]) 
							ELSE 0 END)
						+
						MAX(CASE WHEN file_code = 'T1V4SYNTS' AND data_mat2a[1] ILIKE '%Anomalies sur EXB%'  AND $ENV_TYPEETS = '1'
							THEN base.cti_to_number(data_mat2a[5]) 
							ELSE 0 END)
							AS mat2a_br_sejours_valorises
					FROM pmsi.p_mat2a_data
					WHERE mat2a_import_id = $MAT2A_oid AND
						(
							file_code = 'T1D2RTP' AND line_type = 'T' AND table_sequence = 1 OR
							file_code = 'T1D2RTP' AND line_type = 'D' AND table_sequence = 1 OR
							file_code = 'T1V1SV' AND line_type = 'D' AND table_sequence = 1 OR
							file_code = 'T1V1CP' AND line_type = 'F' OR
							file_code = 'T1V4SYNTS' AND line_type = 'D' AND table_sequence = 1
						)
				) subview
				WHERE p_mat2a_import.oid = $MAT2A_oid;";
				
	iCTI_execute($sqlcmd);
	
	// Référence à l'import
	$sqlcmd = "UPDATE pmsi.p_imports
			SET mat2a_import_id = p_mat2a_import.oid
			FROM pmsi.p_mat2a_import
			WHERE
				p_mat2a_import.oid = $MAT2A_oid AND
				date_part('year',p_imports.date_fin) = p_mat2a_import.mat2a_annee AND
				date_part('month',p_imports.date_fin) = p_mat2a_import.mat2a_mois AND
				etat = 'G' AND
				p_imports.oid IN (SELECT import_id FROM pmsi.p_rss WHERE etat = '' GROUP BY 1);";
	iCTI_execute($sqlcmd);

	logInfoMsg("Finalisation. Ajustements");
	
	$sqlcmd = "SELECT pmsi.cti_ajust_with_mat2a(-1,$MAT2A_oid)";
	iCTI_execute($sqlcmd);

	logInfoMsg("Recalcul chiffrier OVALIDE");
	$sqlcmd = "SELECT pmsi.cti_imports_calc_stats((SELECT max(oid) from pmsi.p_imports WHERE mat2a_import_id = $MAT2A_oid));";
	iCTI_execute($sqlcmd);


}

function debug($msg) {
	global $debug;
	if ($debug == true) {
		file_put_contents('yep.txt', PHP_EOL . date('Y-m-d H:i:s') . "\t\t" . $msg, FILE_APPEND);
	}
}

// Initialisations
function initialize() {

global $ENV_TYPEETS;
global $ENV_FINESS;
global $ENV_LOCALKEYS;

global $MAT2A_zipfile;
global $MAT2A_zipfilename;

	// Paramètres généraux iCTI
	$file = "../../../settings/settings.XML";
	$settings_xml = simplexml_load_file($file);
	
	if (! $settings_xml) {
		logErrorMsg("Paramétrage environement incorrect");
		return FALSE;
	}
	
	$ENV_TYPEETS = "0";
	$ENV_CONSOLIDATION = "0";
	$ENV_FINESS = "999999999";
	$ENV_LOCALKEYS = "";
	foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if ($propertyNode['name'] == 'CONSOLIDATION') {
				$ENV_CONSOLIDATION = $propertyNode['value'];
			}
			if ($propertyNode['name'] == 'TYPEETS') {
				$ENV_TYPEETS = $propertyNode['value'];
			}
			if ($propertyNode['name'] == 'FINESS') {
				$ENV_FINESS = $propertyNode['value'];
			}
			if ($propertyNode['name'] == 'LOCALKEYS') {
				$ENV_LOCALKEYS = $propertyNode['value'];
			}
		}
	}


	// Pas dans consolidation
	if ($ENV_CONSOLIDATION == "1") {
		logErrorMsg("Cet environnement est un environnement consolidé");
		return FALSE;
	}



	// Type établissement
	if ($ENV_TYPEETS != "2" && $ENV_TYPEETS != "3") {
		$ENV_TYPEETS = "1";
	}
	
	
	// Arguments transmis ?
	$cti_args = new CTI_Args_class();

    $MAT2A_zipfile = '';

	$MAT2A_zipfile = $cti_args->args["-fs"];

    if ($MAT2A_zipfile === '') {
        $MAT2A_zipfile = $cti_args->args["--filename-source"];
    }

    if ($MAT2A_zipfile === '') {
        logErrorMsg("Le fichier source doit être précisé.");
        return FALSE;
    }

	$MAT2A_zipfile = str_replace("\"","",$MAT2A_zipfile);

    $MAT2A_zipfilename = '';
	$MAT2A_zipfilename = $cti_args->args["-fd"];

    if ($MAT2A_zipfilename === '') {
        $MAT2A_zipfilename = $cti_args->args["--filename-destination"];
    }

	if ("$MAT2A_zipfilename" == "") {
		$MAT2A_zipfilename = $MAT2A_zipfile;
	}
	
	if (! file_exists($MAT2A_zipfile)) {
		logErrorMsg("Fichier $MAT2A_zipfile inexistant");
		return FALSE;
	}

	return TRUE;
}

function iCTI_connect() {

global $iCTI_connexion;

	$iCTI_connexion = FALSE;

	$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
	$ret = $iCTI_connexion->connect();
	
	if ($iCTI_connexion) {
		
	}
	
	if (!$ret) {
		logErrorMsg("La connexion PostgreSQL iCTI a échoué");
		return FALSE;
	}
		
	
	return $ret;


}



function iCTI_execute($sqlcmd) {

	global $ENDSTATUS;
	global $iCTI_connexion;
	global $nbtrans;

	$toResult = $iCTI_connexion->query($sqlcmd);
	if ($toResult == FALSE) {
		$error = pg_last_error($iCTI_connexion);
		debug($error);
		logErrorMsg("Erreur $error pour $sqlcmd");
	}


	return $toResult;
	
	
}


function iCTI_query($sqlcmd) {

		$toResult = iCTI_execute($sqlcmd);
		if ($toResult != FALSE) {
			$record = pg_fetch_array($toResult);
			return $record;
		}
	}


function iCTI_disconnect() {

	global $iCTI_connexion;
	
	
	
	$iCTI_connexion->close();
}

?>