<?php
require_once("../../base/php/startSession.php");
require_once("../../base/php/classDatabase.php");
require_once("../../base/php/Functions.php");
require_once("../../base/php/WebAppLog.php");

global $database;
global $finess;
global $typeEts;
global $tmp_path;

global $in_import_texte;

set_time_limit(3600);
ini_set('memory_limit', '256M');


$in_import_texte = @$_POST["import_texte"];
if ($in_import_texte == "") {
    $in_import_texte = @$_GET["import_texte"];
}


initializeDir();


$tmp_path = "../../../temp";

$import_id = 0;
$returnCode = "OK";
$returnTexte = "";

get_files($import_id, $returnCode, $returnTexte);


$httpString = "";
$httpString = $httpString . "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
$httpString = $httpString . "\n<HTTP_SERVICE returnCode=\"$returnCode\" returnTexte=\"$returnTexte\" import_id=\"$import_id\" >";
$httpString = $httpString . "\n</HTTP_SERVICE>";


$httpString = gzcompress($httpString, 9);
$httpString = "_c_" . base64_encode($httpString);

echo "<CTICONTENT>$httpString</CTICONTENT>";
//echo "$httpString";


// récupération historique
function get_files(&$import_id, &$returnCode, &$returnTexte)
{

    global $database;

    global $in_import_texte;

    $database = new Database("iCTI");

    global $tmp_path;

    global $ENV_TYPEETS;

    global $FILES_array;


    $FILES_array = array();

    $httpString = "";


    $path = $tmp_path;
    $rep = @opendir($path);
    if ($rep > 0) {
        while ($FILE_fullname = readdir($rep)) {
            if ($FILE_fullname != '..' && $FILE_fullname != '.' && $FILE_fullname != '' && substr($FILE_fullname, 0, 10) == "PMSIMPORT.") {
                $FILE_fullpath = $path . '/' . $FILE_fullname;

                $fileType = "";
                $path_parts = pathinfo($FILE_fullpath);

                $fileType = strtoupper($path_parts['extension']);
                if (is_dir($FILE_fullpath)) {
                    $fileType = "DIR";
                }

                $array = explode(".", $FILE_fullname);
                $FILE_index = 0;
                $FILE_pmsitype = $array[1];
                $FILE_finess = $array[2];
                $FILE_mois = $array[3];
                if ($FILE_mois == "0000") {
                    $FILE_mois = "";
                }
                $FILE_date = date("d/m/Y H:i", $array[4]);
                array_shift($array);
                array_shift($array);
                array_shift($array);
                array_shift($array);
                array_shift($array);
                $FILE_name = implode(".", $array);
                $FILE_size = filesize($FILE_fullpath);
                $FILE_pmsitypeTexte = $FILE_pmsitype;
                switch ($FILE_pmsitype) {
                    case "DRUIDE_OQN" :
                        $FILE_pmsitypeTexte = "DRUIDES OQN";
                        $FILE_index = 5;
                        break;
                    case "DRUIDE_SEJ" :
                        $FILE_pmsitypeTexte = "DRUIDES SEJOURS";
                        $FILE_index = 6;
                        break;
                    case "DRUIDE_ACE" :
                        $FILE_pmsitypeTexte = "DRUIDES RSFACE";
                        $FILE_index = 7;
                        break;
                    case "RSS" :
                        $FILE_pmsitypeTexte = "RSS.TXT (ex OQN)";
                        $FILE_index = 11;
                        break;
                    case "RSF" :
                        $FILE_pmsitypeTexte = "RSF.TXT (ex OQN)";
                        $FILE_index = 12;
                        break;
                    case "ZIN" :
                        $FILE_pmsitypeTexte = "RSS.IN.ZIP";
                        $FILE_index = 1;
                        break;
                    case "ZOU" :
                        $FILE_pmsitypeTexte = "RSS.OUT.ZIP (ex DG)";
                        $FILE_index = 2;
                        break;
                    case "ZIF" :
                        $FILE_pmsitypeTexte = "RSF.IN.ZIP (ex DG)";
                        $FILE_index = 3;
                        break;
                    case "MED" :
                        $FILE_pmsitypeTexte = "Médecins";
                        $FILE_index = 21;
                        break;
                    case "RSM" :
                        $FILE_pmsitype = "RSSMED";
                        $FILE_pmsitypeTexte = "Médecins par RSS";
                        $FILE_index = 22;
                        break;
                    case "RSI" :
                        $FILE_pmsitype = "RSSNOM";
                        $FILE_pmsitypeTexte = "Identités des RSS";
                        $FILE_index = 23;
                        break;
                    case "ACM" :
                        $FILE_pmsitype = "ACTMED";
                        $FILE_pmsitypeTexte = "Exécutants actes";
                        $FILE_index = 24;
                        break;
                    case "VSJ" :
                        $FILE_pmsitypeTexte = "Valorisation séjours";
                        $FILE_index = 25;
                        break;
                    case "VSE" :
                        $FILE_pmsitypeTexte = "Valorisation ACE";
                        $FILE_index = 26;
                        break;
                    case "TSP" :
                        $FILE_pmsitypeTexte = "FICHSUP transports";
                        $FILE_index = 27;
                        break;
                }

                $FILE_object["fullname"] = $FILE_fullname;
                $FILE_object["name"] = $FILE_name;
                $FILE_object["fullpath"] = $FILE_fullpath;
                $FILE_object["pmsitype"] = $FILE_pmsitype;
                $FILE_object["pmsitypeTexte"] = $FILE_pmsitypeTexte;
                $FILE_object["finess"] = $FILE_finess;
                $FILE_object["mois"] = $FILE_mois;
                $FILE_object["date"] = $FILE_date;
                $FILE_object["size"] = $FILE_size;

                $FILE_object["crc"] = @md5_file($FILE_fullpath);


                $FILES_array[$FILE_index] = $FILE_object;

            }
        }
    }
    @closedir($rep);

    ksort($FILES_array);


    // Fichiers remontés
    $ZIN_object = isset($FILES_array[1]) ? $FILES_array[1] : '';
    $ZOU_object = isset($FILES_array[2]) ? $FILES_array[2] : '';
    $ZIF_object = isset($FILES_array[3]) ? $FILES_array[3] : '';

    // Druides
    $DRUIDE_OQN_object = isset($FILES_array[5]) ? $FILES_array[5] : '';
    $DRUIDE_SEJ_object = isset($FILES_array[6]) ? $FILES_array[6] : '';
    $DRUIDE_ACE_object = isset($FILES_array[7]) ? $FILES_array[7] : '';

    $RSS_object = '';
    $RSF_object = '';
    if (!$ZIN_object) {
        $RSS_object = isset($FILES_array[11]) ? $FILES_array[11] : '';
        $RSF_object = isset($FILES_array[12]) ? $FILES_array[12] : '';
    }

    $MED_object = isset($FILES_array[21]) ? $FILES_array[21] : '';
    $RSM_object = isset($FILES_array[22]) ? $FILES_array[22] : '';
    $RSI_object = isset($FILES_array[23]) ? $FILES_array[23] : '';
    $ACM_object = isset($FILES_array[24]) ? $FILES_array[24] : '';
    $VSJ_object = isset($FILES_array[25]) ? $FILES_array[25] : '';
    $VSE_object = isset($FILES_array[26]) ? $FILES_array[26] : '';
    $TSP_object = isset($FILES_array[27]) ? $FILES_array[27] : '';

    $ZIN_crc = isset($ZIN_object["crc"]) ? trim($ZIN_object["crc"]) : '';
    $ZOU_crc = isset($ZOU_object["crc"]) ? trim($ZOU_object["crc"]) : '';
    $ZIF_crc = isset($ZIF_object["crc"]) ? trim($ZIF_object["crc"]) : '';

    $DRUIDE_OQN_crc = isset($DRUIDE_OQN_object["crc"]) ? trim($DRUIDE_OQN_object["crc"]) : '';
    $DRUIDE_SEJ_crc = isset($DRUIDE_SEJ_object["crc"]) ? trim($DRUIDE_SEJ_object["crc"]) : '';
    $DRUIDE_ACE_crc = isset($DRUIDE_ACE_object["crc"]) ? trim($DRUIDE_ACE_object["crc"]) : '';

    $RSS_crc = isset($RSS_object["crc"]) ? trim($RSS_object["crc"]) : '';
    $RSF_crc = isset($RSF_object["crc"]) ? trim($RSF_object["crc"]) : '';

    $MED_crc = isset($MED_object["crc"]) ? trim($MED_object["crc"]) : '';
    $RSM_crc = isset($RSM_object["crc"]) ? trim($RSM_object["crc"]) : '';
    $RSI_crc = isset($RSI_object["crc"]) ? trim($RSI_object["crc"]) : '';
    $ACM_crc = isset($ACM_object["crc"]) ? trim($ACM_object["crc"]) : '';
    $VSJ_crc = isset($VSJ_object["crc"]) ? trim($VSJ_object["crc"]) : '';
    $VSE_crc = isset($VSE_object["crc"]) ? trim($VSE_object["crc"]) : '';
    $TSP_crc = isset($TSP_object["crc"]) ? trim($TSP_object["crc"]) : '';

    // Vérification si déjà enregistré
    $sqlcmd = "SELECT oid, texte FROM
				(
					SELECT 
						p_imports.oid, 
						p_imports.texte, 
						MAX(CASE WHEN data_type = 'RSS' THEN p_imports_data.data_crc ELSE '' END) AS RSS_data_crc,
						MAX(CASE WHEN data_type = 'RSF' THEN p_imports_data.data_crc ELSE '' END) AS RSF_data_crc,
						MAX(CASE WHEN data_type = 'ZIN' THEN p_imports_data.data_crc ELSE '' END) AS ZIN_data_crc,
						MAX(CASE WHEN data_type = 'ZOU' THEN p_imports_data.data_crc ELSE '' END) AS ZOU_data_crc,
						MAX(CASE WHEN data_type = 'ZIF' THEN p_imports_data.data_crc ELSE '' END) AS ZIF_data_crc,
						MAX(CASE WHEN data_type = 'DRUIDE_OQN' THEN p_imports_data.data_crc ELSE '' END) AS DRUIDE_OQN_data_crc,
						MAX(CASE WHEN data_type = 'DRUIDE_SEJ' THEN p_imports_data.data_crc ELSE '' END) AS DRUIDE_SEJ_data_crc,
						MAX(CASE WHEN data_type = 'DRUIDE_ACE' THEN p_imports_data.data_crc ELSE '' END) AS DRUIDE_ACE_data_crc,
						MAX(CASE WHEN data_type = 'MED' THEN p_imports_data.data_crc ELSE '' END) AS MED_data_crc,
						MAX(CASE WHEN data_type = 'RSSMED' THEN p_imports_data.data_crc ELSE '' END) AS RSM_data_crc,
						MAX(CASE WHEN data_type = 'RSSNOM' THEN p_imports_data.data_crc ELSE '' END) AS RSI_data_crc,
						MAX(CASE WHEN data_type = 'ACTMED' THEN p_imports_data.data_crc ELSE '' END) AS ACM_data_crc,
						MAX(CASE WHEN data_type = 'VSJ' THEN p_imports_data.data_crc ELSE '' END) AS VSJ_data_crc,
						MAX(CASE WHEN data_type = 'VSE' THEN p_imports_data.data_crc ELSE '' END) AS VSE_data_crc,
						MAX(CASE WHEN data_type = 'TSP' THEN p_imports_data.data_crc ELSE '' END) AS TSP_data_crc
					FROM pmsi.p_imports
						JOIN pmsi.p_imports_data ON p_imports.oid = p_imports_data.import_id
					WHERE data_type IN ('RSS', 'RSF', 'ZIN', 'ZOU', 'ZIF', 'DRUIDE_OQN', 'DRUIDE_SEJ', 'DRUIDE_ACE',  'MED', 'RSSMED', 'RSSNOM', 'ACTMED', 'VSJ', 'VSE', 'TSP')
					GROUP BY 1,2
				) subview
				WHERE
					ZIN_data_crc = '$ZIN_crc' AND
					ZOU_data_crc = '$ZOU_crc' AND
					ZIF_data_crc = '$ZIF_crc' AND
					DRUIDE_OQN_data_crc = '$DRUIDE_OQN_crc' AND
					DRUIDE_SEJ_data_crc = '$DRUIDE_SEJ_crc' AND
					DRUIDE_ACE_data_crc = '$DRUIDE_ACE_crc' AND
					RSS_data_crc = '$RSS_crc' AND
					RSF_data_crc = '$RSF_crc' AND
					MED_data_crc = '$MED_crc' AND
					RSM_data_crc = '$RSM_crc' AND
					RSI_data_crc = '$RSI_crc' AND
					ACM_data_crc = '$ACM_crc' AND
					VSJ_data_crc = '$VSJ_crc' AND
					VSE_data_crc = '$VSE_crc' AND
					TSP_data_crc = '$TSP_crc'
				ORDER BY oid DESC";
    $result = $database->exec($sqlcmd);

    if ($result != false) {
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;

            $record = $database->nextRecordInto();
            if ($record != FALSE) {
                $ok = TRUE;
                $oid = floatval($record[0]);
                $texte = $record[1];
                $returnCode = "KO";
                $returnTexte = "Fichiers déjà importés sous le numéro $oid ($texte)";
            }
        }
    }

    if ($returnCode == "KO") {
        return;
    }


    // Ajout en base de données
 $sqlcmd = "INSERT INTO pmsi.p_imports (texte, etat, date_import, etat_en_cours)
						VALUES('" . pg_escape_string($in_import_texte) . "', '', CURRENT_DATE, 'I')";
 $result = $database->exec($sqlcmd);
 if ($result == false) {
     $returnCode = "KO";
        $returnTexte = "Ajout en base de données de l'entete a échoué";
     return;
 }


    // Numéro du nouveau fichier
    $import_id = 0;

    $sqlcmd = "SELECT max(oid) AS oid FROM pmsi.p_imports WHERE etat = '' AND etat_en_cours = 'I' ";
    $result = $database->exec($sqlcmd);

    if ($result != false) {
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = $database->nextRecordInto();
            if ($record != FALSE) {
                $ok = TRUE;
                $import_id = floatval($record[0]);
            }
        }
    }

    if ($import_id == 0) {
        $returnCode = "KO";
        $returnTexte = "Ajout en base de données de l'entete (2) a échoué";
        return;
    }


    foreach ($FILES_array as &$FILE_object) {
        addFile($import_id, $FILE_object["pmsitype"], $FILE_object["fullpath"], $FILE_object["name"], $FILE_object["crc"]);
    }


   $sqlcmd = "UPDATE pmsi.p_imports SET etat = 'I', etat_en_cours = '', traitement_a_faire = '' WHERE oid = $import_id ";
   $result = $database->exec($sqlcmd);


}


function addFile($import_id, $data_type, $data_path, $file_name, $data_crc)
{


    global $database;

    if (file_exists($data_path)) {
        $file_size = filesize($data_path);
        $file_name = toSQL($file_name);

        $start = 0;
        $data_num = 0;

        while ($start <= $file_size) {
            $filebuff = file_get_contents($data_path, FALSE, NULL, $start, 10000000);
            if ($data_type != "ZIN" && $data_type != "ZIF" && $data_type != "ZOU") {
                $filebuff = compress($filebuff);
            }
            $filebuff = pg_escape_bytea($filebuff);

            $sqlcmd = "INSERT INTO pmsi.p_imports_data (import_id, data_type, date_creation, data_num, data, file_path, file_size, data_crc) 
				VALUES($import_id, '$data_type', '2099-12-31', $data_num, '$filebuff', '$file_name', $file_size, '$data_crc' )";
            $result = $database->exec($sqlcmd, "", FALSE, "", "-nohtmlspecialchars");

            $start = $start + 10000000;
            $data_num++;
        }
    }

}


function initializeDir()
{

    if (!file_exists("../../../temp")) {
        @mkdir("../../../temp");
    }

}


?>