<?php

if (!defined('__ROOT__') ) {
    list($environmentPath) = explode(DIRECTORY_SEPARATOR.'modules', dirname(__FILE__));
    $environmentPath .= DIRECTORY_SEPARATOR;
    define('__ROOT__', $environmentPath);
}

require_once __ROOT__.'/modules/base/php/Functions.php';
require_once __ROOT__.'/modules/base/php/startSession.php';
require_once __ROOT__ .'/modules/pmsi/import_rss_rsf/iCTI_convert_druide.php';
require_once __ROOT__ .'/modules/base/php/lib/cti/Autoloader.php';
Autoloader::register();

global $finess;
global $in_file;
global $in_importFileDate;
global $tmp_path;

set_time_limit(3600);
ini_set('upload_max_filesize', '220M');
ini_set('post_max_size', '220M');
ini_set('memory_limit', '1024M');


$importFile = @$_POST["importFile"];
$in_importFileDate = @$_POST["importFileDate"];

initializeTempDir();


$tmp_path = __ROOT__ . "/temp";
$uploadfile = $tmp_path . "/" . $importFile;


$response = new JsonResponse(200, "Fichié uploadé");

$in_file = basename($_FILES['Filedata']['name']);
if (!move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadfile)) {
    $response = new JsonResponse(500, "Le fichier $importFile n'a pas été téléchargé. Erreur système");
    $response->send();
    return;
}


// controle fichier

// IN.ZIP ou OUT.ZIP
$error = "";
if (strtoupper(substr($importFile, -4, 4)) === ".ZIP") {
    $error = control_zipfile($uploadfile);
} // Fichiers texte
else {
    $error = control_txtfile($uploadfile);
}

$returnCode = $error !== "" ? "KO" : "OK";

$data = array(
    "returnCode" =>$returnCode,
    "returnTexte" => $error
);

$response = new JsonResponse(200, $data);


$response->send();


function control_zipfile($ZIP_filepath)
{

    global $finess;
    global $typeEts;
    global $in_importFileDate;

    $ZIP_finess = "";
    $ZIP_mois = "";
    $ZIP_pmsitype = "";
    $ZIP_error = "";
    $from_druide = false;

    if (!file_exists($ZIP_filepath)) {
        return "Le fichier zip n'existe pas";
    }

    $ZIP_filedate = $in_importFileDate;

    $ZIP_archive = new ZipArchive();
    if ($ZIP_archive->open($ZIP_filepath) === FALSE) {
        return "Décompression impossible";
    }


    for ($i = 0; $i < $ZIP_archive->numFiles; $i++) {
        $ZIP_entry = $ZIP_archive->statIndex($i);

        $ZIP_in_filename = trim($ZIP_entry["name"]);
        $ZIP_in_filedate = (float)$ZIP_entry["mtime"];


        if (stripos($ZIP_in_filename, ".rss") > 0) {
            $ZIP_pmsitype = "ZIN";
            $array = explode(".", $ZIP_in_filename);
            $ZIP_finess = trim($array[0]);
            if (strlen(trim($array[2])) < 2) {
                $array[2] = "0" . trim($array[2]);
            }
            $ZIP_mois = trim($array[1]) . trim($array[2]);
            $ZIP_filedate = $ZIP_in_filedate;
        }
    }

    if ($ZIP_pmsitype === "") {
        for ($i = 0; $i < $ZIP_archive->numFiles; $i++) {
            $ZIP_entry = $ZIP_archive->statIndex($i);

            $ZIP_in_filename = trim($ZIP_entry["name"]);
            $ZIP_in_filedate = (float)$ZIP_entry["mtime"];
            if (stripos($ZIP_in_filename, ".sign") > 0) {
                // Druides RSS public
                if (stripos($ZIP_filepath, ".SEJOURS") > 0) {
                    $ZIP_pmsitype = "DRUIDE_SEJ";
                    $from_druide = true;
                }
                // Druides RSF Externes public
                if (stripos($ZIP_filepath, ".RSFACE") > 0) {
                    $ZIP_pmsitype = "DRUIDE_ACE";
                    $from_druide = true;
                }
                // Druides RSS + RSF privé
                if (stripos($ZIP_filepath, ".RSFOQN") > 0) {
                    $ZIP_pmsitype = "DRUIDE_OQN";
                    $from_druide = true;
                }
                $array = explode(".", $ZIP_in_filename);
                $ZIP_finess = trim($array[0]);
                if (strlen(trim($array[2])) < 2) {
                    $array[2] = "0" . trim($array[2]);
                }
                $ZIP_mois = trim($array[1]) . trim($array[2]);
                $ZIP_filedate = $ZIP_in_filedate;
            }
            if (stripos($ZIP_in_filename, ".rsa") > 0) {
                $ZIP_pmsitype = "ZOU";
                $array = explode(".", $ZIP_in_filename);
                $ZIP_finess = trim($array[0]);
                if (strlen(trim($array[2])) < 2) {
                    $array[2] = "0" . trim($array[2]);
                }
                $ZIP_mois = trim($array[1]) . trim($array[2]);
                $ZIP_filedate = $ZIP_in_filedate;
            }
            if ($ZIP_pmsitype !== "ZOU" && (stripos($ZIP_in_filename, ".rsf.txt") > 0 || stripos($ZIP_in_filename, ".rsf.ini.txt") > 0)) {
                $ZIP_pmsitype = "ZIF";
                $array = explode(".", $ZIP_in_filename);
                $ZIP_finess = trim($array[0]);
                if (strlen(trim($array[2])) < 2) {
                    $array[2] = "0" . trim($array[2]);
                }
                $ZIP_mois = trim($array[1]) . trim($array[2]);
                $ZIP_filedate = $ZIP_in_filedate;
            }
            if ($ZIP_pmsitype !== "ZOU" && $ZIP_pmsitype !== "DRUIDE_ACE" && stripos($ZIP_in_filename, ".rsfa") > 0) {
                $ZIP_pmsitype = "ZOF";
                $array = explode(".", $ZIP_in_filename);
                $ZIP_finess = trim($array[0]);
                if (strlen(trim($array[2])) < 2) {
                    $array[2] = "0" . trim($array[2]);
                }
                $ZIP_mois = trim($array[1]) . trim($array[2]);
                $ZIP_filedate = $ZIP_in_filedate;
            }
        }
    }



    @$ZIP_archive->close();


    // Si pas trouvé (norme standard, essayer de trouver selon le contenu)
    if ($ZIP_pmsitype === "") {

        @$ZIP_archive->open($ZIP_filepath);

        $ZIP_rss_index = -1;
        $ZIP_rsf_index = -1;

        for ($i = 0; $i < $ZIP_archive->numFiles; $i++) {
            $ZIP_entry = $ZIP_archive->statIndex($i);


            $ZIP_in_filename = trim($ZIP_entry["name"]);
            $ZIP_in_filedate = (float)$ZIP_entry["mtime"];

            $ZIP_in_buffer_handle = $ZIP_archive->getStream($ZIP_in_filename);

            $ZIP_pmsisubtype = "";

            if ($ZIP_in_buffer_handle) {

                $ZIP_in_buffer = fgets($ZIP_in_buffer_handle, 100000);

                $no_ligne = 0;

                while (!feof($ZIP_in_buffer_handle)) {
                    $buffer = fgets($ZIP_in_buffer_handle, 99999);

                    $no_ligne++;
                    if (trim($buffer) !== "" && $no_ligne < 1000000000000) {
                        if ($ZIP_pmsisubtype === "") {
                            if (substr($buffer, 15, 9) == $finess) {
                                $ZIP_pmsitype = "ZIN";
                                $ZIP_pmsisubtype = "RSS";
                                $ZIP_finess = $finess;
                                $ZIP_mois = "";
                                $ZIP_filedate = $ZIP_in_filedate;
                                $ZIP_rss_index = $i;
                            }
                        }

                        if ($ZIP_pmsisubtype === "") {
                            if (substr($buffer, 0, 1) === "A" && substr($buffer, 1, 9) == $finess) {
                                $ZIP_pmsitype = "ZIN";
                                $ZIP_pmsisubtype = "RSF";
                                $ZIP_finess = $finess;
                                $ZIP_mois = "";
                                $ZIP_filedate = $ZIP_in_filedate;
                            }
                        }

                        if ($ZIP_pmsisubtype === "RSS") {
                            if ((float)substr($buffer, 106, 4) >= 2000 && (float)substr($buffer, 106, 4) < 2020) {
                                $mois = substr($buffer, 106, 4) . substr($buffer, 104, 2);
                                if ($mois > $ZIP_mois) {
                                    $ZIP_mois = $mois;
                                }
                            }
                        }

                        if ($ZIP_pmsisubtype === "RSF") {
                            if (substr($buffer, 0, 1) == "A") {
                                if ((float)substr($buffer, 89, 4) >= 2000 && (float)substr($buffer, 89, 4) < 2020) {
                                    $mois = substr($buffer, 89, 4) . substr($buffer, 87, 2);
                                    if ($mois > $ZIP_mois) {
                                        $ZIP_mois = $mois;
                                    }
                                }
                            }
                        }

                    }

                }
                fclose($ZIP_in_buffer_handle);
            }

        }

        if ($ZIP_rss_index >= 0) {
            $ZIP_entry = $ZIP_archive->statIndex($ZIP_rss_index);
            $ZIP_mois_Y = substr($ZIP_mois, 0, 4);
            $ZIP_mois_m = substr($ZIP_mois, 4, 2);
            $ZIP_in_name = trim($ZIP_entry["name"]);
            $ZIP_in_newname = "$ZIP_finess.$ZIP_mois_Y.$ZIP_mois_m.rss.txt";
            @$ZIP_archive->renameName($ZIP_in_name, $ZIP_in_newname);
        }
        if ($ZIP_rsf_index >= 0) {
            $ZIP_entry = $ZIP_archive->statIndex($ZIP_rsf_index);
            $ZIP_mois_Y = substr($ZIP_mois, 0, 4);
            $ZIP_mois_m = substr($ZIP_mois, 4, 2);
            $ZIP_in_name = trim($ZIP_entry["name"]);
            $ZIP_in_newname = "$ZIP_finess.$ZIP_mois_Y.$ZIP_mois_m.rsf.txt";
            @$ZIP_archive->renameName($ZIP_in_name, $ZIP_in_newname);
        }

        @$ZIP_archive->close();


    }
    if ($ZIP_finess != $finess) { // comparaison du finess du fichier  a importer par rapport au finess de l'environnement

        $ZIP_error = "Finess différent $ZIP_finess de $finess";

    }


    if ($ZIP_error === "" && $ZIP_pmsitype === "") {
        $ZIP_error = "Données non PMSI (ni RSS, ni RSF, ni RSA)";
    }
    if ($ZIP_error === "" && $ZIP_pmsitype === "ZOF") {
        $ZIP_error = "Fichier PREFACE out.zip non supporté, veuillez importer le fichier in.zip de PREFACE";
    }

    if ($ZIP_error === "" && alreadyTXT()) {
        $ZIP_error = "Fichier ZIP incompatible avec RSS ou RSF TXT déjà chargé";
    }

    if ($ZIP_error === "" && $ZIP_pmsitype === "ZIF" && $typeEts !== "2" && $typeEts !== "3") {
        $ZIP_error = "Format RSF IN.ZIP incompatible pour exOQN";
    }




    if ($ZIP_error !== "") {
        @unlink($ZIP_filepath);
    } else {
        $ZIP_error = valide_file($ZIP_filepath, $ZIP_pmsitype, $ZIP_finess, $ZIP_mois, $ZIP_filedate, $from_druide);
    }

    return $ZIP_error;

}


function control_txtfile($TXT_filepath)
{

    global $finess;
    global $typeEts;
    global $in_importFileDate;

    $TXT_finess = "";
    $TXT_annee = "";
    $TXT_mois = "";
    $TXT_pmsitype = "";
    $TXT_error = "";


    if (!file_exists($TXT_filepath)) {
        return "Le fichier txt n'existe pas";
    }

    $TXT_filedate = $in_importFileDate;

    $no_ligne = 0;
    $buffer = "";

    // format RSS/RSF ?
    $TXT_handle = @fopen($TXT_filepath, "r");
    if ($TXT_handle) {
        while (!feof($TXT_handle)) {
            $buffer = fgets($TXT_handle, 99999);

            $no_ligne++;
            if (trim($buffer) !== "" && $no_ligne < 1000000000000) {
                if ($TXT_pmsitype === "") {
                    if (substr($buffer, 15, 9) === $finess && strlen($buffer) > 100) {
                        $TXT_pmsitype = "RSS";
                        $TXT_finess = $finess;
                        $TXT_annee = "";
                        $TXT_mois = "";
                    }
                }
                if ($TXT_pmsitype === "") {
                    if (substr($buffer, 0, 1) === "A" && substr($buffer, 1, 9) === $finess && strlen($buffer) > 100) {
                        $TXT_pmsitype = "RSF";
                        $TXT_finess = $finess;
                        $TXT_annee = "";
                        $TXT_mois = "";
                    }
                }
                if ($TXT_pmsitype === "RSS") {
                    if ((float)substr($buffer, 106, 4) >= 2000 && (float)substr($buffer, 106, 4) < 2020) {
                        $mois = substr($buffer, 106, 4) . substr($buffer, 104, 2);
                        if ($mois > $TXT_mois) {
                            $TXT_mois = $mois;
                        }
                    }
                }
                if ($TXT_pmsitype === "RSF") {
                    if (substr($buffer, 0, 1) == "A") {
                        if ((float)substr($buffer, 89, 4) >= 2000 && (float)substr($buffer, 89, 4) < 2020) {
                            $mois = substr($buffer, 89, 4) . substr($buffer, 87, 2);
                            if ($mois > $TXT_mois) {
                                $TXT_mois = $mois;
                            }
                        }
                    }
                }


            }

        }
        fclose($TXT_handle);
    }

    // Si pas format RSS/RSF, verifier données complémentaires
    if ($TXT_pmsitype === "") {

        $maxCol = 0;
        $length = 0;
        $maxLength = 0;
        $no_ligne = 0;

        $TXT_handle = @fopen($TXT_filepath, "r");
        $TXT_filename = basename($TXT_filepath);
        if ($TXT_handle) {
            while (!feof($TXT_handle)) {
                $buffer = fgets($TXT_handle, 99999);

                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 10) {

                    $array = explode("\t", $buffer);
                    if (count($array) <= 1) {
                        $array = explode(";", $buffer);
                    }
                    $nbCol = count($array);
                    if ($nbCol > $maxCol) {
                        $maxCol = $nbCol;
                    }
                    $length = strlen(trim($buffer));
                    if ($length > $maxLength) {
                        $maxLength = $length;
                    }
                }

            }
            fclose($TXT_handle);
        }

        // Fichsup transports
        if ($maxCol == 1 && $maxLength <= 31) {
            $TXT_pmsitype = "TSP";
            // recuperation du mois et de l'annee dans le nom du FICHSUP transports
            $TXT_fileparts = explode('.', $TXT_filename);
            if (count($TXT_fileparts) > 1) {
                $TXT_annee = $TXT_fileparts[1];
                $TXT_mois = $TXT_annee . str_pad($TXT_fileparts[2], 2, '0', STR_PAD_LEFT);
            }
        }

        if ($maxCol == 2) {
            $TXT_pmsitype = "RSM";
        }
        // Pour Baclesse, les nombres de colonnes sont différents pour les fichiers de rss-noms
        // by CLA 04-03-2013
        if ($finess == '140000639') {
            if ($maxCol == 4) {
                $TXT_pmsitype = "RSI";
            } else if ($maxCol == 5) {
                $TXT_pmsitype = "MED";
            }
        } else {
            if ($maxCol == 3) {
                $TXT_pmsitype = "RSI";
            }
            if ($maxCol > 3 && $maxCol < 6) {
                $TXT_pmsitype = "MED";
            }
        }
        if ($maxCol > 6 && $maxCol < 30) {
            $TXT_pmsitype = "ACM";
        }
        if ($maxCol > 30) {
            if (stripos($TXT_filename, '.valo.') !== false) {
                $TXT_pmsitype = "VSJ";
            }
            if (stripos($TXT_filename, '.valo.ace') !== false || stripos($TXT_filename, '.valo_ace') !== false) {
                $TXT_pmsitype = "VSE";
            }
            // recuperation du mois et de l'annee dans le nom du fichier de valo
            $TXT_fileparts = explode('.', $TXT_filename);
            if (count($TXT_fileparts) > 1) {
                $TXT_annee = $TXT_fileparts[1];
                $TXT_mois = $TXT_annee . str_pad($TXT_fileparts[2], 2, '0', STR_PAD_LEFT);
            }
        }
        if ($TXT_pmsitype !== "") {
            $TXT_finess = $finess;
            $TXT_annee = ($TXT_annee === "") ? "0000" : $TXT_annee;
            $TXT_mois = ($TXT_mois === "") ? "000000" : $TXT_mois;
        }
    }


    if ($TXT_pmsitype === "") {
        $TXT_error = "Données non PMSI (ni RSS, ni RSF, ni RSA)";
    }

    if ($TXT_pmsitype === "RSS" && !($typeEts !== "2" && $typeEts !== "3")) {
        $TXT_error = "Format RSS.TXT incompatible pour exDG";
    }

    if ($TXT_pmsitype === "RSF" && !($typeEts !== "2" && $typeEts !== "3")) {
        $TXT_error = "Format RSF.TXT incompatible pour exDG";
    }
    if ($TXT_pmsitype === "RSS" || $TXT_pmsitype === "RSF") {
        if ($TXT_finess !== $finess) {
            $TXT_error = "Finess différent $TXT_finess de $finess";
        }
    }
    if ($TXT_pmsitype === "RSS" || $TXT_pmsitype === "RSF") {
        if (alreadyZIP()) {
            $TXT_error = "Fichier TXT incompatible avec RSS ou RSF ZIP déjà chargé";
        }
    }


    if ($TXT_error !== "") {
        @unlink($TXT_filepath);
    } else {
        valide_file($TXT_filepath, $TXT_pmsitype, $TXT_finess, $TXT_mois, $TXT_filedate);
    }

    return $TXT_error;

}


function valide_file($ZIP_filepath, $ZIP_pmsitype, $ZIP_finess, $ZIP_mois, $ZIP_filedate, $from_druide = false)
{
    $druide_error = "";
    $path = dirname($ZIP_filepath);
    $name = basename($ZIP_filepath);
    $prefix = "PMSIMPORT." . $ZIP_pmsitype . ".";
    $prefixComp = "PMSIMPORT." . $ZIP_pmsitype . "." . $ZIP_finess . "." . $ZIP_mois . "." . $ZIP_filedate . ".";


    $rep = @opendir($path);
    if ($rep > 0) {
        while ($file = readdir($rep)) {
            if ($file !== '..' && $file !== '.' && $file !== '') {
                $longFile = $path . '/' . $file;

                if (strpos($file, $prefix) === 0) {
                    @unlink($longFile);
                }
            }
        }
    }
    @closedir($rep);
    $newPathFile = "$path/$prefixComp$name";
    rename($ZIP_filepath, $newPathFile);

    // Pour Druide, il faut convertir, de plus on copie les originaux dans le dossier D:/CTI/Druides/mois
    if ($from_druide) {
        try {
            convertDruide($newPathFile);
        } catch (Exception $e) {
            $druide_error = $e->getMessage();
        }
        //TODO: si le telechargement des fichiers druides fonctionne bien on pourra suppprimer la fonction
        // et la notion de IsKeepDruidesFiles
        if (Environnement::getInstance()->getIsKeepDruidesFiles()){
            copyDruidesOriginalFile($name, $newPathFile, $ZIP_mois);
        }
    }
    return $druide_error;
}


// test si un fichier TXT RSS ou RSF
function alreadyTXT()
{

    global $tmp_path;


    $path = $tmp_path;
    $rep = @opendir($path);
    if ($rep > 0) {
        while ($FILE_fullname = readdir($rep)) {
            if ($FILE_fullname !== '..' && $FILE_fullname !== '.' && $FILE_fullname !== '' && strpos($FILE_fullname, "PMSIMPORT.") === 0) {
                if (strpos($FILE_fullname, "PMSIMPORT.RSS.") === 0 || strpos($FILE_fullname, "PMSIMPORT.RSF.") === 0) {
                    return TRUE;
                }
            }
        }
    }
    @closedir($rep);


    return FALSE;

}


// test si un fichier TXT RSS ou RSF
function alreadyZIP()
{

    global $tmp_path;


    $path = $tmp_path;
    $rep = @opendir($path);
    if ($rep > 0) {
        while ($FILE_fullname = readdir($rep)) {
            if ($FILE_fullname !== '..' && $FILE_fullname !== '.' && $FILE_fullname !== '' && strpos($FILE_fullname, "PMSIMPORT.") === 0) {
                if (strpos($FILE_fullname, "PMSIMPORT.ZIN.") === 0 || strpos($FILE_fullname, "PMSIMPORT.ZOU.") === 0 || strpos($FILE_fullname, "PMSIMPORT.ZIF.") === 0) {
                    return TRUE;
                }
            }
        }
    }
    @closedir($rep);


    return FALSE;

}


function copyDruidesOriginalFile($name, $newPathFile, $ZIP_mois)
{

    $druidesPath = Environnement::getInstance()->getKeepDruidesFilesPath();

    // Dossier pour insérer les fichiers Druides par défault si rien est indiqué dans les Settings de l'environnement
    // ex:  D:/CTI/Druides/032024
    if ($druidesPath === ""){
        $arrPath = explode( "/",  Environnement::getInstance()->getRootPath());
        $disque = $arrPath[0];

        $ctiPath = $disque . "/CTI";
        if (!file_exists($ctiPath) && !mkdir($ctiPath) && !is_dir($ctiPath)) {
            throw new RuntimeException("Le dossier CTI n'existe pas");
        }

        $druidesPath = $ctiPath . "/cti_pmsi_imports_lots/";
    }

    if(substr_compare($druidesPath, "/", -1, 1) !== 0){
        $druidesPath .= "/";
    }

    $druidesPath .= $ZIP_mois;

    if (!file_exists($druidesPath) && mkdir($druidesPath, 0700, true) && !is_dir($druidesPath)) {
        throw new RuntimeException(sprintf('Directory "%s" was not created', $druidesPath));
    }

    $filepathDruides = $druidesPath . '/' . $name;
    if (!copy($newPathFile, $filepathDruides)) {
        throw new RuntimeException(sprintf('failed to copy  "%s"', $filepathDruides));
    }

}

