<!DOCTYPE html>
<html lang="it">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">

        <!-- uikit -->
        <link href="include/uikit_theme/bower_components/uikit/css/uikit.almost-flat.min.css" rel="stylesheet" type="text/css"/>
       
        <!-- altair admin -->
        <link href="include/uikit_theme/assets/css/main.min.css" rel="stylesheet" type="text/css"/>
        
        <!-- themes -->
        <link href="include/uikit_theme/assets/css/themes/themes_combined.min.css" rel="stylesheet" type="text/css"/>

        <!-- Font awesome 5 -->
        <link href="include/uikit_theme/assets/icons/fontawesome-free-5/css/all.min.css" rel="stylesheet" type="text/css"/>
		  
		<!-- flag icons -->
		<link rel="stylesheet" href="include/uikit_theme/assets/icons/flags/flags.min.css" media="all">
        
        <title>IMPORT STUDIO DICOM</title>
       
        <!-- google web fonts (in locale) -->
        <script src="include/uikit_theme/assets/js/custom/webfont.js" type="text/javascript" async=""></script>
        <link href="include/uikit_theme/assets/css/webfontsStyles.css" rel="stylesheet" type="text/css"/>
        

        <!-- jQuery -->
        <script src="include/uikit_theme/bower_components/jquery/dist/jquery.min.js" type="text/javascript"></script>
        <script src="include/uikit_theme/bower_components/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
        <!-- common functions -->
        <script src="include/uikit_theme/assets/js/common.min.js" type="text/javascript"></script>
        <!-- uikit functions -->
        <script src="include/uikit_theme/assets/js/uikit_custom.min.js" type="text/javascript"></script>
        <!-- altair core functions -->
        <script src="include/uikit_theme/assets/js/altair_admin_common.min.js" type="text/javascript"></script>
        <!-- altair login page functions -->
        <script src="include/uikit_theme/assets/js/pages/login.min.js" type="text/javascript"></script>

        <link href="import.css" rel="stylesheet" type="text/css"/>

    </head>

<body style="padding-top: 0px !important;">

    <script>
        $( document ).ready(function() {

            $('form').on('submit', function(e){
                //$('input').attr("disabled", true);

                //altair_helpers.content_preloader_show('md', 'info');

                var msg = "<br/><span style='align: center; font-wight: bold;'>CARICAMENTO IN CORSO<br/>";
                msg += "<br/>NON CHIUDERE LA PAGINA<br/>E ATTENDERE LA CONCLUSIONE DEL CARICAMENTO<br/><br/>";
                msg += "<br/>L'operazione potrebbe richiedere fino a qualche minuto a seconda della dimensione dello studio<br/>";
                UIkit.notify(   msg, 
                                {status: "warning", timeout: 30000}
                            );
            });

        });
    </script>


    <div style='margin-left: 1%; margin-right: 1%; width: 98%; height: 60px; background-color: #1976d2;'>
        <div style="float: left; height: 50px; width: 50%;">
            <img src="images/logo.png" alt="" height="50px">
            <span class="uk-badge uk-badge-success uk-text-upper">IMPORT STUDI DICOM ESTERNI</span>
        </div>
        <div style="float: right; height: 50px; border: 1px;">
            <!--div style="float: right; color: white; height: 50px; width: 70px;">
                <img style="height: 50px; margin-right: 20px; margin-top: 2px;" src="images/x-ray_worker.png" alt="" >
            </div-->
            <div style="float: right; color: white; height: 50px; vertical-align: middle; padding: 20px;">
                <span style='font-weight: bold;'><?= $_POST["list_name"]?></span>
            </div>
        </div>
    </div>

    <div style='margin-left: 1%; margin-right: 1%; lightgray; width: 98%;'  class='background_ris'>
    <div style='padding: 30px; width: 100%'>
<?php
/**
 * @copyright Gmed Srl
 * @author Sciarrone Riccardo <riccardos@gmed.it>
 *
 * carica uno studio da file
 */


// Report all errors except E_NOTICE
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


include __DIR__ . "/conf/config.inc.php";
include __DIR__ . "/include/basic_function.php";
include __DIR__ . "/include/dcm_function.php";


$this_pid = __DIR__ . "/../cron_" . basename(__FILE__, ".php") . ".pid";
if (file_exists($this_pid)) {
    unlink($this_pid);
}

//echo "<pre>", var_dump( $_POST ), "</pre>";

$pid_name = "import_studies";


$fk_import = -1;

$si = -1;
$user_id = -1;
$order_id = -1;
$patient_id = -1;

$pg_ok = false;

if ( $_SERVER['REQUEST_METHOD'] != 'POST' ){
    //echo "SERVER:<pre>", var_dump( $_SERVER ), "</pre>";
    echo $_SERVER['REQUEST_METHOD'];
    die( "MANCANO I DATI DELL'ORDINE!! (1)" );
}

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ){
    //echo "POST<pre>", var_dump($_POST), "</pre>";

    $si = $_POST["si"];
    $user_id = $_POST["user_id"];
    $order_id = $_POST["order_id"];
    $patient_id = $_POST["patient_id"];

    $cdc_id = $_POST["cdc_id"];
    $username = $_POST["username"];
    $list_name = $_POST["list_name"];
    $fullname_passed = $_POST["fullname_passed"];

    if( !isset($_POST["order_id"]) || !isset($_POST["patient_id"])){
        //echo "SERVER:<pre>", var_dump( $_POST ), "</pre>";
        die( "MANCANO I DATI DELL'ORDINE!! (2)" );
    }


    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => IMPORT_restar_url . '/report/json?type=ORDER&identifier=' . $order_id,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
    ));
    $response = curl_exec($curl);

    curl_close($curl);
    //echo $response;
    $ordine = json_decode( $response, true );

    //echo "ORDINE: <pre>", var_dump( $ordine ), "</pre><hr/>";
    if( !isset($ordine["PATIENT"]) || !isset($ordine["ORDER"])){
        echo  IMPORT_restar_url . '/report/json?type=ORDER&identifier=' . $order_id . "<br/>";
        //echo "SERVER:<pre>", var_dump( $_POST ), "</pre>";
        die( "MANCANO I DATI DELL'ORDINE!! (3)" );
    }

    /*
    echo 'FILE RICEVUTO:<pre>';
    print_r( $_FILES );
    echo '</pre>';
    //die();
    */

    if( isset($_POST["import_folder"]) ){

        //echo "INZIO A CARICARE LA CARTELLA!!<br>";
        $uuid = "";
        $find_dcm = false;
        $fls = $_FILES["files"];
        
        $fk_import = 0;
        $fk_imports = "0";

        $current_parent_patient = "";

        for( $fxx = 0; $fxx < count( $fls["tmp_name"] ); $fxx++ ) {
            // leggo tutti i file presenti

            $f_type = $fls["type"][ $fxx ];
            $f_tmp_name = $fls["tmp_name"][ $fxx ];
            $f_full_path = "N.D.";
            if( isset($fls["full_path"]) ){
                $f_full_path = $fls["full_path"][ $fxx ];
            }
            $f_name = $fls["name"][ $fxx ];
            $f_error = $fls["error"][ $fxx ];
            $f_size = $fls["size"][ $fxx ];

            //echo "$fxx leggo il file $f_tmp_name di tipo $f_type<br/>";


            if ( $f_type == 'application/dicom' || $f_type == 'application/zip' || $f_type == 'application/octet-stream' ){
                // è un DCM o uno ZIP

                // ora inserisco in Orthanc
                $cmd = orthanc_url . '/instances';
                $POSTFIELDS = file_get_contents( $f_tmp_name );
                $instance = call_orthanc( $cmd, "IMPORT", false, 'POST', $POSTFIELDS);

                if( isset($instance["error"]) ){
                    // studio non trovato! passo alla prossima
                    $pos = strpos($instance["descr"], 'Bad file format');
                    if ( $f_type != 'application/octet-stream' || $pos===false ){
                        // octed-stream potrebbe essere un file "qualsiasi" anche NON un DCM
                        echo "ERRORE IMPORT <br/>$f_type  $f_full_path - ". $instance["error"] . "<br/>" .$instance["descr"] . "<hr/>" ;
                        WriteLog( "ERRORE IMPORT  $f_type $f_full_path - " . $instance["error"] . "\n" . $instance["descr"], import_logfile, "ERROR" );
                    }
                }
                else {
                    // import OK!!
                    //echoo( "<strong>$f_name</strong> / $f_full_path");

                    $instnc = $instance;
                    if ( $f_type == 'application/zip' ){
                        $instnc = $instance[0];
                        //echoo( $instnc, true );
                    }

                    // 2023-05-09
                    // ora controllo se il paziente è lo stesso dell'istanza precedente!
                    if ( $current_parent_patient != $instnc["ParentPatient"] ){
                        // è il primo! inserisco il record nel DB
                        //echo "trovato nuovo PAZIENTE: " . $instnc["ParentPatient"] . "<br/>";
                        $uuid = uniqid();
                        $sql = "  INSERT INTO public.dcm_imports
                                      ( uuid, ip, idorder, idpatient, iduser, import_date, session_id, 
                                        file_name, 
                                        file_full_path, 
                                        file_type, 
                                        file_tmp_name, 
                                        file_error, 
                                        file_size,
                                        status )
                                  VALUES( '$uuid', '" .  getUserIP() . "', $order_id, $patient_id, $user_id, '" . date("Y-m-d H:i:s") . "', '$si', 
                                          'IMPORT DIR', 
                                          '', 
                                          'DIR', 
                                          '', 
                                          0, 
                                          " . count($fls["tmp_name"]) . ",
                                          0) ";
                        $ris = query_execute( $sql );
                
                        $import = query_select("  SELECT  id
                                                  FROM    public.dcm_imports
                                                  WHERE   uuid = '$uuid' ");
                
                        if ( IsNull($import[0]['id']) ) {
                            // NULLA DA elaborare
                            WriteLog( "ERRORE NELLA CREAZIONE DELL'IMPORT", import_logfile, "ERROR" );
                            die( "ERRORE NELLA CREAZIONE DELL'IMPORT <br/>" );
                        }
                        $fk_import = $import[0]['id'];
                        $current_parent_patient = $instnc["ParentPatient"];
                        //echo "Nuovo FK_IMPT  $fk_import <br/>" ;
                        $fk_imports .= ",$fk_import";
                    }

                    $sql = "  INSERT INTO public.dcm_imports_instances
                                (
                                    fk_import, instance_id, parent_patient, parent_series, parent_study, \"path\", status,
                                    file_name, 
                                    file_full_path, 
                                    file_type, 
                                    file_tmp_name, 
                                    file_error, 
                                    file_size
                                )
                                VALUES
                                (
                                    $fk_import, '" . $instnc["ID"] . "', '" . $instnc["ParentPatient"] . "', '" . $instnc["ParentSeries"] . "', '" . $instnc["ParentStudy"] . "', '" . $instnc["Path"] . "', '" . $instnc["Status"] . "',
                                    '$f_name', 
                                    '$f_full_path', 
                                    '$f_type', 
                                    '$f_tmp_name', 
                                    $f_error, 
                                    $f_size
                                ) ";
                    //echoo( "$sql <br/>" );
                    $ris = query_execute( $sql );
                }
                //echoo( "<hr/>");
            }
        }
        $pg_ok = true;
        //echo "FINE CARICAMENTO CARTELLA!!<br><hr/><br/>";
    }


    if( isset($_POST["import_file"]) ){
        // arrivo dall'import di un FILE
        $fl = $_FILES['fileToUpload'];

        //function call_orthanc($url, $type = "GENERIC", $single_value = FALSE, $custom_request = 'GET', $post_fields = "{}", $check_error_in_resp = TRUE) {
        $cmd = orthanc_url . '/instances';
        $POSTFIELDS = file_get_contents($fl['tmp_name']);
        $instances = call_orthanc( $cmd, "IMPORT", false, 'POST', $POSTFIELDS );

        if( isset($instances["error"]) ){
            // studio non trovato! passo alla prossima
            echoo( "ERRORE IMPORT " . $instances["error"] . " - " .$instances["descr"] . "\n<hr/>\n" );
            WriteLog( "ERRORE  IMPORT  " . $instances["error"] . " - " . $instances["descr"], import_logfile, "ERROR" );
            die( "" );
        }

        // sono tornate le istanze del file
        // echoo( $instances, true );

        // forse su php 7 non c'è
        if ( !isset($fl["full_path"]) ){
            $fl["full_path"] = "N.D.";
        }

        $uuid = uniqid();
        $sql = "  INSERT INTO public.dcm_imports
                      ( uuid, ip, idorder, idpatient, iduser, import_date, session_id, 
                        file_name, 
                        file_full_path, 
                        file_type, 
                        file_tmp_name, 
                        file_error, 
                        file_size,
                        status )
                  VALUES( '$uuid', '" .  getUserIP() . "', $order_id, $patient_id, $user_id, '" . date("Y-m-d H:i:s") . "', '$si', 
                          '" . $fl["name"] . "', 
                          '" . $fl["full_path"] . "', 
                          '" . $fl["type"] . "', 
                          '" . $fl["tmp_name"] . "', 
                          " . $fl["error"] . ", 
                          " . $fl["size"] . ",
                          0) ";
        $ris = query_execute( $sql );

        $import = query_select("  SELECT  id
                                  FROM    public.dcm_imports
                                  WHERE   uuid = '$uuid' ");

        if ( IsNull($import[0]['id']) ) {
            // NULLA DA elaborare
            WriteLog( "ERRORE NELLA CREAZIONE DELL'IMPORT", import_logfile, "ERROR" );
            die( "ERRORE NELLA CREAZIONE DELL'IMPORT <br/>" );
        }
        $fk_imports = $fk_import = $import[0]['id'];

        foreach( $instances as $inst ){
            $sql = "  INSERT INTO public.dcm_imports_instances
                        (fk_import, instance_id, parent_patient, parent_series, parent_study, \"path\", status)
                      VALUES
                        ($fk_import, '" . $inst["ID"] . "', '" . $inst["ParentPatient"] . "', '" . $inst["ParentSeries"] . "', '" . $inst["ParentStudy"] . "', '" . $inst["Path"] . "', '" . $inst["Status"] . "') ";
              $ris = query_execute( $sql );
        }

        WriteLog( "INSERITO IMPORT $fk_import / $uuid  con " . count($instances) . " istanze!", import_logfile, "INFO" );
        //die( "STUDIO IMPORTATO!!" );

        $pg_ok = true;
    }

    if( isset($_POST["da_ris"]) && trim($_POST["da_ris"])!='' ){
        $pg_ok = true;
    }

}
else {
    // non ho passato dati
    $pg_ok = false;
}


if( isset($_GET["fk_import"]) &&  $_GET["fk_import"] < 0 ){
    // per debug!!
    $fk_import = abs( $_GET["fk_import"] );

    $sql = "  SELECT  *
              FROM    public.dcm_imports
              WHERE   id = $fk_import ";
    $impt = query_select( $sql );

    $si = $impt[0]["session_id"];
    $user_id = $impt[0]["iduser"];
    $order_id = $impt[0]["idorder"];
    $patient_id = $impt[0]["idpatient"];

    $pg_ok = true;
}


if ( !$pg_ok ){
    die( "BUONGIORNO STRANIERO!<br/>COME POSSO ESSERTI UTILE?" );
}
?>
    
    <?php
    //echo "IMPORT STUDI per " . $ordine["PATIENT"]["FAMILY_NAME"] . "^" . $ordine["PATIENT"]["GIVEN_NAME"] . "<br/>";

    $pt_name = $ordine["PATIENT"]["FAMILY_NAME"] . "^" . $ordine["PATIENT"]["GIVEN_NAME"];
    $pt_dob = str_replace( "-", "", substr( $ordine["PATIENT"]["DOB"], 0, 10 ) );
    $age = determine_age( $ordine["PATIENT"]["DOB"] );

    echo "<div id='pt-div'>";
    echo "<span style='font-size: 1.2em; font-weight: bold;'>PAZIENTE DELL'ORDINE:</span>";
    echo "<h1 class='colore_ris'>" . $ordine["PATIENT"]["FAMILY_NAME"] . " " . $ordine["PATIENT"]["GIVEN_NAME"] . " (" . $age . " anni) </h1>";

    echo '
    <div class="uk-width-1-1 uk-margin-top uk-margin-small-bottom">
        <span class="uk-text-bold">Luogo di nascita</span>: ' . $ordine["PATIENT"]["BIRTH_PLACE"]["DENOMINAZIONE_IT"] .' , 
        <span class="uk-text-bold">Data di nascita</span>: ' . date( 'd/m/Y', strtotime($ordine["PATIENT"]["DOB"])) . '
    </div> ';

    //echo "<pre>", var_dump( $ordine ), "</pre>";
    echo "</div>";


    if ( $fk_import > 0 ){
        // l'import è stato eseguito!!
        ?>
                <form action="import_go.php" method="post" >
        <?php


        $sql = "  SELECT  *
                  FROM    public.dcm_imports
                  WHERE   id = $fk_import ";
        $impt = query_select( $sql );

        //echoo( $impt, true );

        // elenco i pazienti
        $sql = "  SELECT  distinct(parent_patient) as pp
                  FROM    public.dcm_imports_instances
                  WHERE   fk_import IN ($fk_imports)  ";

        $pts = query_select( $sql );

        if ( IsNull($pts[0]['pp']) ) {
            // NULLA DA elaborare
            WriteLog( "NESSUN PAZIENTE IMPORTATO $fk_import", import_logfile, "ERROR" );
            die( "NESSUN PAZIENTE IMPORTATO $fk_import<br/>" );
        }


        $total_pt_ok = true;
        echo "<div class='sottotitolo_ris' style='margin-bottom: 50px; width: 89%;'>";
        echo ($impt[0]["file_name"] == "IMPORT DIR" ? "<span style='font-weight: bold;'>IMPORTATA CARTELLA</span>" : "<span style='font-weight: bold;'>File importato:</span> " . $impt[0]["file_name"]) . "<br/>";
        echo "</div>";
 
        echo "<table style='width: 93%;'>
                    <thead>
                        <tr>
                            <th align='left' style='width: 45%;'><span class='sottotitolo_ris'>Paziente trovati nell'import:</span></th>
                            <th align='left' style=''><span class='sottotitolo_ris'>Studi per paziente:</span></th>
                        </tr>
                    </thead>
                    <tbody>";
        foreach( $pts as $pt ){
            $cmd = orthanc_url . '/patients/' . $pt["pp"];
            $patient = call_orthanc( $cmd, "GET_PATIENT", false, 'GET');

            echo "<tr style='padding: 20px; border-bottom: 2px dotted; margin: 10px;'><td>";
            echo "<span style='font-size: 1.2em; font-weight: bold;' class='colore_ris'>" . $patient["MainDicomTags"]["PatientName"] . " (" . $patient["MainDicomTags"]["PatientBirthDate"] . ") " . $patient["MainDicomTags"]["PatientSex"] . "</span><br/>";
            echo "<br/>Verifica automatica corridpondenza dati anagrafici:<br/>";

            echo "<ul>";
            $pt_ok = true;
            if ( strtoupper($pt_name) != strtoupper($patient["MainDicomTags"]["PatientName"]) ){
                echo "<li><span class='pt_error''>IL NOME PAZIENTE NON CORRISPONDE</span></li>";
                $pt_ok = false;
                $total_pt_ok = false;
            }

            if( $pt_dob != $patient["MainDicomTags"]["PatientBirthDate"] ){
                echo "<li><span class='pt_error''>LA DATA DI NASCITA DEL PAZIENTE NON CORRISPONDE</span></li>";
                $pt_ok = false;
                $total_pt_ok = false;
            }

            if( $ordine["PATIENT"]["SEX"] != $patient["MainDicomTags"]["PatientSex"] ){
                echo "<li><span class='pt_error'>IL SESSO DEL PAZIENTE NON CORRISPONDE</span></li>";
                $pt_ok = false;
                $total_pt_ok = false;
            }
            
            if ( $pt_ok) {
                echo "<li><span class='pt_ok''>IL PAZIENTE CORRISPONDE</span></li>";
            }
            echo "</ul>";
            
            echo "</td><td>";

            $sql = "    SELECT  distinct(parent_study) as ps
                        FROM    public.dcm_imports_instances
                        WHERE   fk_import IN ($fk_imports) 
                                AND parent_patient = '" . $pt["pp"] . "' ";

            $studies = query_select( $sql );

            if ( IsNull($studies[0]['ps']) ) {
                // NULLA DA elaborare
                WriteLog( "NESSUNO STUDIO IMPORTATO $fk_import", import_logfile, "ERROR" );
                die( "NESSUNO STUDIO IMPORTATO $fk_import<br/>" );
            }
            //echo "Trovati i seguenti studi: <br/>";

            $nr_std = 0;
            foreach( $studies as $std ){
                
                if  ( $nr_std ){
                    echo "<hr/>";
                }
                $nr_std++;

                //echoo( $std["ps"] );

                $cmd = orthanc_url . '/studies/' . $std["ps"];
                $study = call_orthanc( $cmd, "GET_STUDIES", false, 'GET');
                
                //echoo( "DATI DELLO STUDIO:", false, true );
                //echoo( $study, true );

                echo $study["MainDicomTags"]["InstitutionName"] . "<br/>";
                echo "<strong>" . $study["MainDicomTags"]["StudyDescription"] . "</strong><br/>";
                echo "data studio: " . $study["MainDicomTags"]["StudyDate"] . "<br/>";
                echo "Study Instance UID: " . $study["MainDicomTags"]["StudyInstanceUID"] . "<br/><br/>";

                // 2023-05-02 - SR
                // ORA cerco se lo studio è già sul PACS FINALE
                if ( IMPORT_check_remote_pacs ){
                    //echo "TEST sul PACS<br/>";
                    $std_already_in_pacs = false;

                    $post_fields = '{
                        "Level": "Study",
                        "Query": {
                            "AccessionNumber": "",
                            "PatientBirthDate": "",
                            "PatientID": "",
                            "PatientName": "",
                            "PatientSex": "",
                            "StudyDate": "",
                            "StudyDescription": "",
                            "StudyInstanceUID": "' . $study["MainDicomTags"]["StudyInstanceUID"] . '"
                        }
                    }';

                    /*
                    * torna ID della query
                    * quindi faccio una nuova chiamata per vedere il risultato!!
                    */
                    $cmd = IMPORT_remote_orthanc . "/modalities/" . IMPORT_AET_remote_pacs . "/query";
                    $query = call_orthanc( $cmd, "C-FIND", false, 'POST', $post_fields );
                    // http://192.168.62.134:8042/queries/db539fbe-0db7-4c1a-a4e4-a7816448e608/answers/0/content?simplify
                    
                    //echo "QUERY:<br/>$cmd<br/>$post_fields";
                    //echoo( $query, true );

                    if ( isset($query["ID"]) ){
                        sleep( 2 );
                        $cmd = IMPORT_remote_orthanc . "/queries/" . $query["ID"] . "/answers";
                        $answer = call_orthanc( $cmd, "C-FIND", false, 'GET', null );
                        
                        //echoo( "RISPOSTA ALLA QUERY:<br/>$cmd<br/>", false, true );
                        //echoo( $answer, true );

                        if ( isset($answer["0"]) ){
                            $cmd .= "/0/content?simplify";
                            $q_answer = call_orthanc( $cmd, "C-FIND", false, 'GET', null );

                            //echoo( "ANSWER:", false, true );
                            //echoo( $q_answer, true );
                            $std_already_in_pacs = true;

                            echoo ( "<span style='font-size: 1.0em; color: red;'>WARNING:<br/>STUDIO GIA' PRESENTE NEL PACS</span><br/>" );

                        }
                    }
                }

            }      

            $desinenza = "IMPORTA QUESTO STUDIO";
            if ( $nr_std > 1 ){
                $desinenza = "IMPORTA QUESTI STUDI";
            }

            $chk = "";
            $chk_descr = "<span style='font-size: 1.1em; color: darkred;'>$desinenza (conferma richiesta)</span>";
            if( $pt_ok ){
                // questo paziente corrisponde!!
                $chk= "checked='checked'";
                $chk_descr = "<span style='font-size: 1.1em; font-weight: bold; color: darkgreen;'>$desinenza</span>";
            }
            ?>

            <input type="checkbox" name="import_this[]" class="import_this" id="<?=$pt["pp"]?>" value="<?=$pt["pp"]?>"  <?=$chk?> /> <?=$chk_descr?>
            <br/>

            <?php
            echo "</td></tr>";
        }
        echo "</tbody></table>";

        $padding_conferma = 20;
        $class_conferma = "md-btn md-btn-primary md-btn-icon md-btn-large";

        $padding_annulla = 10;
        $class_annulla = "md-btn md-btn-default md-btn-icon md-btn-small";

        if( !$total_pt_ok || $std_already_in_pacs ){
            $padding_conferma = 10;
            $class_conferma = "md-btn md-btn-danger md-btn-icon md-btn-small";

            $padding_annulla = 20;
            $class_annulla = "md-btn md-btn-primary md-btn-icon md-btn-large";
        }

        
        ?>

            <input type="hidden" name="si" value="<?=$si?>">
            <input type="hidden" name="user_id" value="<?=$user_id?>">
            <input type="hidden" name="order_id" value="<?=$order_id?>">
            <input type="hidden" name="patient_id" value="<?=$patient_id?>">
            <input type="hidden" name="import_id" value="<?=$fk_imports?>">
            <input type="hidden" name="cdc_id" value="<?=$cdc_id?>">
            <input type="hidden" name="username" value="<?=$username?>">
            <input type="hidden" name="list_name" value="<?=$list_name?>">
            <input type="hidden" name="fullname_passed" value="<?=$fullname_passed?>">
            <br/>
            <input type="submit" value="CONFERMA STUDIO" name="conferma_import" style="padding: <?=$padding_conferma?>px !important;" class='<?=$class_conferma?>'>
            <input type="submit" value="ANNULLA IMPORT" name="annulla_import" style="padding: <?=$padding_annulla?>px !important;" class='<?=$class_annulla?>'>
        </form>
        <?php
    }
    else {
        // inizia l'import!!
        ?>
            <div id="ul-div">
                <ul class="uk-tab" data-uk-tab="{connect:'#my-id3'}" style='margin-top: 20px; margin-bottom: 0px !important'>
                    <li id="tab3" style='margin-left: 30px !important; margin-right: 50px !important;'>
                        <img style="height: 50px; margin-right: 10px; float: left;" src="images/upload-folder.png" alt="" >
                        <a style="float: left;" href="">IMPORT DIRECTORY DICOM (CD, USB)</a>
                    </li>
                    <li id="tab1">
                        <img style="height: 50px; margin-right: 10px; float: left;" src="images/upload-file.png" alt="" >
                        <a style="float: left;" href="">IMPORT SINGOLO FILE DICOM (.dcm .zip)&nbsp;&nbsp;&nbsp;</a>
                    </li>
                </ul>
                <ul id="my-id3" class="uk-switcher uk-margin" style="margin-top: 5px;">
                    <li>
                        <!--img style="float: left; height: 30px; margin-right: 10px;" src="images/upload-folder.png" alt="" -->
                        <div style='float: left; background-color: white; padding: 30px; width: 100%;'>
                            <span style="font-size: 1.5em; font-weight: bold; margin-botton: 20px;">CARICO DIRECTORY DICOM</span>
                            <span style="font-size: 0.8em; font-weight: bold; margin-botton: 20px;"><br/>usare questa funzionalità per caricare da CD e chiavette USB </span>
                            <form action="#" method="post" enctype="multipart/form-data">
                                <input type="hidden" name="si" value="<?=$si?>">
                                <input type="hidden" name="user_id" value="<?=$user_id?>">
                                <input type="hidden" name="order_id" value="<?=$order_id?>">
                                <input type="hidden" name="patient_id" value="<?=$patient_id?>">
                                <input type="hidden" name="cdc_id" value="<?=$cdc_id?>">
                                <input type="hidden" name="username" value="<?=$username?>">
                                <input type="hidden" name="list_name" value="<?=$list_name?>">
                                <input type="hidden" name="fullname_passed" value="<?=$fullname_passed?>">
                                <br/>
                                
                                <span class='colore_ris' style="font-size: 1.1em; font-weight: bold;" style='padding: 20px;'> 
                                Seleziona cartella da caricare: </span><br/>
                                <input type="file" name="files[]" id="files" multiple directory="" webkitdirectory="" moxdirectory="" />
                                <br/><br/> <br/><br/> 
                                <input type="Submit" class="uk-button uk-button-primary" value="CARICA DIRECTORY" name="import_folder" />
                            </form>
                        </div>
                    </li>
                    <li>
                        <!--img style="float: left; height: 30px; margin-right: 10px;" src="images/upload-file.png" alt="" -->
                        <div style='float: left; background-color: white; padding: 30px; width: 100%;'>
                            <span style="font-size: 1.5em; font-weight: bold; margin-botton: 20px;">CARICA SINGOLO FILE DICOM</span>
                            <span style="font-size: 0.8em; font-weight: bold; margin-botton: 20px;"><br/>usare questa funzionalità per caricare uno studio in singolo file (DICOM DIR e/o ZIP)</span>
                            <form action="#" method="post" enctype="multipart/form-data">
                                <input type="hidden" name="si" value="<?=$si?>">
                                <input type="hidden" name="user_id" value="<?=$user_id?>">
                                <input type="hidden" name="order_id" value="<?=$order_id?>">
                                <input type="hidden" name="patient_id" value="<?=$patient_id?>">
                                <input type="hidden" name="cdc_id" value="<?=$cdc_id?>">
                                <input type="hidden" name="username" value="<?=$username?>">
                                <input type="hidden" name="list_name" value="<?=$list_name?>">
                                <input type="hidden" name="fullname_passed" value="<?=$fullname_passed?>">
                                <br/>
                                <span class='colore_ris'  style="font-size: 1.1em; color: blue; font-weight: bold;"> 
                                Seleziona lo studio da caricare:</span><br/>
                                <input type="file" name="fileToUpload" id="fileToUpload" >
                                <br/><br/> <br/><br/> 
                                <input type="submit" class="uk-button uk-button-primary" value="CARICA STUDIO" name="import_file">
                            </form>
                        </div>
                    </li>
                </ul>
            </div>
        <?php
    }
    ?>
    </div> 
</div> 




    </body>
</html>
